@positronic/core 0.0.76 → 0.0.78

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 (130) hide show
  1. package/dist/src/dsl/brain-runner.js +37 -182
  2. package/dist/src/dsl/brain-state-machine.js +58 -112
  3. package/dist/src/dsl/brain.js +1 -0
  4. package/dist/src/dsl/builder/brain.js +250 -404
  5. package/dist/src/dsl/builder/continuation.js +67 -0
  6. package/dist/src/dsl/constants.js +16 -17
  7. package/dist/src/dsl/create-brain.js +29 -45
  8. package/dist/src/dsl/example-webhook.js +1 -1
  9. package/dist/src/dsl/execution/constants.js +0 -4
  10. package/dist/src/dsl/execution/event-channel.js +77 -0
  11. package/dist/src/dsl/execution/event-stream.js +1625 -1462
  12. package/dist/src/dsl/signal-validation.js +0 -1
  13. package/dist/src/dsl/webhook.js +4 -1
  14. package/dist/src/files/event-wrapper.js +268 -0
  15. package/dist/src/files/index.js +1 -0
  16. package/dist/src/files/mime.js +31 -0
  17. package/dist/src/files/types.js +13 -0
  18. package/dist/src/index.js +10 -3
  19. package/dist/src/jsx-runtime.js +49 -0
  20. package/dist/src/memory/{scoped-memory.js → create-memory.js} +5 -5
  21. package/dist/src/plugins/collect-webhooks.js +49 -0
  22. package/dist/src/plugins/define-plugin.js +15 -0
  23. package/dist/src/plugins/index.js +1 -0
  24. package/dist/src/plugins/types.js +4 -0
  25. package/dist/src/store/types.js +2 -3
  26. package/dist/src/template/render-html.js +282 -0
  27. package/dist/src/template/render.js +357 -0
  28. package/dist/src/tools/index.js +88 -27
  29. package/dist/src/ui/generate-page-html.js +6 -6
  30. package/dist/src/ui/{generate-ui.js → generate-page.js} +24 -12
  31. package/dist/src/ui/parse-form-data.js +1 -11
  32. package/dist/src/ui/types.js +0 -123
  33. package/dist/src/yaml/data-validator.js +0 -27
  34. package/dist/src/yaml/type-inference.js +10 -9
  35. package/dist/types/clients/types.d.ts +15 -5
  36. package/dist/types/clients/types.d.ts.map +1 -1
  37. package/dist/types/dsl/brain-runner.d.ts +9 -14
  38. package/dist/types/dsl/brain-runner.d.ts.map +1 -1
  39. package/dist/types/dsl/brain-state-machine.d.ts +18 -28
  40. package/dist/types/dsl/brain-state-machine.d.ts.map +1 -1
  41. package/dist/types/dsl/brain.d.ts +3 -2
  42. package/dist/types/dsl/brain.d.ts.map +1 -1
  43. package/dist/types/dsl/builder/brain.d.ts +87 -230
  44. package/dist/types/dsl/builder/brain.d.ts.map +1 -1
  45. package/dist/types/dsl/builder/continuation.d.ts +16 -0
  46. package/dist/types/dsl/builder/continuation.d.ts.map +1 -0
  47. package/dist/types/dsl/constants.d.ts +12 -12
  48. package/dist/types/dsl/constants.d.ts.map +1 -1
  49. package/dist/types/dsl/create-brain.d.ts +17 -57
  50. package/dist/types/dsl/create-brain.d.ts.map +1 -1
  51. package/dist/types/dsl/definitions/blocks.d.ts +67 -55
  52. package/dist/types/dsl/definitions/blocks.d.ts.map +1 -1
  53. package/dist/types/dsl/definitions/brain-types.d.ts +8 -11
  54. package/dist/types/dsl/definitions/brain-types.d.ts.map +1 -1
  55. package/dist/types/dsl/definitions/events.d.ts +61 -55
  56. package/dist/types/dsl/definitions/events.d.ts.map +1 -1
  57. package/dist/types/dsl/definitions/run-params.d.ts +20 -21
  58. package/dist/types/dsl/definitions/run-params.d.ts.map +1 -1
  59. package/dist/types/dsl/definitions/steps.d.ts +1 -1
  60. package/dist/types/dsl/definitions/steps.d.ts.map +1 -1
  61. package/dist/types/dsl/example-webhook.d.ts +3 -3
  62. package/dist/types/dsl/example-webhook.d.ts.map +1 -1
  63. package/dist/types/dsl/execution/constants.d.ts +0 -5
  64. package/dist/types/dsl/execution/constants.d.ts.map +1 -1
  65. package/dist/types/dsl/execution/event-channel.d.ts +16 -0
  66. package/dist/types/dsl/execution/event-channel.d.ts.map +1 -0
  67. package/dist/types/dsl/execution/event-stream.d.ts +46 -34
  68. package/dist/types/dsl/execution/event-stream.d.ts.map +1 -1
  69. package/dist/types/dsl/signal-validation.d.ts.map +1 -1
  70. package/dist/types/dsl/types.d.ts +21 -83
  71. package/dist/types/dsl/types.d.ts.map +1 -1
  72. package/dist/types/dsl/webhook.d.ts +12 -2
  73. package/dist/types/dsl/webhook.d.ts.map +1 -1
  74. package/dist/types/files/event-wrapper.d.ts +20 -0
  75. package/dist/types/files/event-wrapper.d.ts.map +1 -0
  76. package/dist/types/files/index.d.ts +2 -0
  77. package/dist/types/files/index.d.ts.map +1 -0
  78. package/dist/types/files/mime.d.ts +2 -0
  79. package/dist/types/files/mime.d.ts.map +1 -0
  80. package/dist/types/files/types.d.ts +88 -0
  81. package/dist/types/files/types.d.ts.map +1 -0
  82. package/dist/types/index.d.ts +22 -12
  83. package/dist/types/index.d.ts.map +1 -1
  84. package/dist/types/jsx-runtime.d.ts +35 -0
  85. package/dist/types/jsx-runtime.d.ts.map +1 -0
  86. package/dist/types/memory/{scoped-memory.d.ts → create-memory.d.ts} +7 -7
  87. package/dist/types/memory/create-memory.d.ts.map +1 -0
  88. package/dist/types/memory/types.d.ts +4 -4
  89. package/dist/types/memory/types.d.ts.map +1 -1
  90. package/dist/types/plugins/collect-webhooks.d.ts +8 -0
  91. package/dist/types/plugins/collect-webhooks.d.ts.map +1 -0
  92. package/dist/types/plugins/define-plugin.d.ts +25 -0
  93. package/dist/types/plugins/define-plugin.d.ts.map +1 -0
  94. package/dist/types/plugins/index.d.ts +3 -0
  95. package/dist/types/plugins/index.d.ts.map +1 -0
  96. package/dist/types/plugins/types.d.ts +83 -0
  97. package/dist/types/plugins/types.d.ts.map +1 -0
  98. package/dist/types/store/index.d.ts +1 -1
  99. package/dist/types/store/index.d.ts.map +1 -1
  100. package/dist/types/store/types.d.ts +0 -8
  101. package/dist/types/store/types.d.ts.map +1 -1
  102. package/dist/types/template/render-html.d.ts +9 -0
  103. package/dist/types/template/render-html.d.ts.map +1 -0
  104. package/dist/types/template/render.d.ts +15 -0
  105. package/dist/types/template/render.d.ts.map +1 -0
  106. package/dist/types/tools/index.d.ts +39 -27
  107. package/dist/types/tools/index.d.ts.map +1 -1
  108. package/dist/types/ui/generate-page-html.d.ts +4 -6
  109. package/dist/types/ui/generate-page-html.d.ts.map +1 -1
  110. package/dist/types/ui/{generate-ui.d.ts → generate-page.d.ts} +6 -6
  111. package/dist/types/ui/generate-page.d.ts.map +1 -0
  112. package/dist/types/ui/parse-form-data.d.ts +1 -5
  113. package/dist/types/ui/parse-form-data.d.ts.map +1 -1
  114. package/dist/types/ui/types.d.ts +0 -49
  115. package/dist/types/ui/types.d.ts.map +1 -1
  116. package/dist/types/yaml/data-validator.d.ts +0 -5
  117. package/dist/types/yaml/data-validator.d.ts.map +1 -1
  118. package/dist/types/yaml/type-inference.d.ts +4 -2
  119. package/dist/types/yaml/type-inference.d.ts.map +1 -1
  120. package/dist/types/yaml/types.d.ts +0 -1
  121. package/dist/types/yaml/types.d.ts.map +1 -1
  122. package/package.json +5 -1
  123. package/dist/src/dsl/agent-messages.js +0 -5
  124. package/dist/src/ui/validate-form.js +0 -428
  125. package/dist/types/dsl/agent-messages.d.ts +0 -12
  126. package/dist/types/dsl/agent-messages.d.ts.map +0 -1
  127. package/dist/types/memory/scoped-memory.d.ts.map +0 -1
  128. package/dist/types/ui/generate-ui.d.ts.map +0 -1
  129. package/dist/types/ui/validate-form.d.ts +0 -45
  130. package/dist/types/ui/validate-form.d.ts.map +0 -1
@@ -166,6 +166,35 @@ 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
+ }
169
198
  function _await_async_generator(value) {
170
199
  return new _overload_yield(value, 0);
171
200
  }
@@ -201,6 +230,13 @@ function _define_property(obj, key, value) {
201
230
  }
202
231
  return obj;
203
232
  }
233
+ function _instanceof(left, right) {
234
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
235
+ return !!right[Symbol.hasInstance](left);
236
+ } else {
237
+ return left instanceof right;
238
+ }
239
+ }
204
240
  function _iterable_to_array(iter) {
205
241
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
206
242
  }
@@ -437,12 +473,15 @@ import { v4 as uuidv4 } from 'uuid';
437
473
  import { STATUS, BRAIN_EVENTS } from '../constants.js';
438
474
  import { createPatch, applyPatches } from '../json-patch.js';
439
475
  import { IterateResult } from '../iterate-result.js';
440
- import { generateUI } from '../../ui/generate-ui.js';
476
+ import { generatePage } from '../../ui/generate-page.js';
441
477
  import { generatePageHtml } from '../../ui/generate-page-html.js';
442
- import { createScopedMemory } from '../../memory/scoped-memory.js';
478
+ import { guessMimeType } from '../../files/mime.js';
479
+ import { EventChannel } from './event-channel.js';
480
+ import { wrapFilesWithEvents } from '../../files/event-wrapper.js';
443
481
  import { Step } from '../builder/step.js';
444
- import { DEFAULT_ENV, DEFAULT_AGENT_SYSTEM_PROMPT } from './constants.js';
445
- import { defaultDoneSchema } from '../../tools/index.js';
482
+ import { DEFAULT_ENV } from './constants.js';
483
+ import { resolveTemplate, buildTemplateContext } from '../../template/render.js';
484
+ import { renderHtml, wrapHtmlDocument } from '../../template/render-html.js';
446
485
  var clone = function(value) {
447
486
  return structuredClone(value);
448
487
  };
@@ -458,54 +497,56 @@ export var BrainEventStream = /*#__PURE__*/ function() {
458
497
  _define_property(this, "description", void 0);
459
498
  _define_property(this, "client", void 0);
460
499
  _define_property(this, "options", void 0);
461
- _define_property(this, "services", void 0);
462
500
  _define_property(this, "resources", void 0);
463
501
  _define_property(this, "pages", void 0);
464
502
  _define_property(this, "env", void 0);
465
503
  _define_property(this, "currentResponse", undefined);
466
504
  _define_property(this, "currentPage", undefined);
467
- _define_property(this, "resumeContext", void 0);
505
+ _define_property(this, "resume", void 0);
468
506
  _define_property(this, "components", void 0);
469
- _define_property(this, "defaultTools", void 0);
470
- _define_property(this, "extraTools", void 0);
471
507
  _define_property(this, "signalProvider", void 0);
472
- _define_property(this, "memoryProvider", void 0);
473
- _define_property(this, "scopedMemory", void 0);
474
508
  _define_property(this, "store", void 0);
509
+ _define_property(this, "files", void 0);
510
+ _define_property(this, "storeProvider", void 0);
511
+ _define_property(this, "pluginInjections", void 0);
512
+ _define_property(this, "pluginAdapters", void 0);
513
+ _define_property(this, "pluginConfigs", void 0);
514
+ _define_property(this, "templateContext", void 0);
475
515
  _define_property(this, "governor", void 0);
476
516
  _define_property(this, "currentUser", void 0);
477
517
  _define_property(this, "guards", new Map());
478
518
  _define_property(this, "waits", new Map());
479
519
  _define_property(this, "stopped", false);
480
520
  _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;
521
+ 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, _params_resources = params.resources, resources = _params_resources === void 0 ? {} : _params_resources, pages = params.pages, env = params.env, components = params.components, signalProvider = params.signalProvider, store = params.store, files = params.files, currentUser = params.currentUser;
482
522
  // Store governor for per-step client resolution
483
523
  this.governor = params.governor;
484
524
  this.currentUser = currentUser;
485
525
  // Check if this is a resume run or fresh start
486
526
  var resumeParams = params;
487
527
  var initialParams = params;
488
- var resumeContext = resumeParams.resumeContext;
528
+ var resume = resumeParams.resume;
489
529
  this.title = title;
490
530
  this.description = description;
491
531
  this.client = client;
492
532
  this.options = options;
493
- this.services = services;
494
533
  this.resources = resources;
495
534
  this.pages = pages;
496
535
  this.env = env !== null && env !== void 0 ? env : DEFAULT_ENV;
497
- this.resumeContext = resumeContext;
536
+ this.resume = resume;
498
537
  this.components = components;
499
- this.defaultTools = defaultTools;
500
- this.extraTools = extraTools;
501
538
  this.signalProvider = signalProvider;
502
- this.memoryProvider = memoryProvider;
503
539
  this.store = store;
540
+ this.files = files;
541
+ this.storeProvider = params.storeProvider;
542
+ var _params_pluginInjections;
543
+ this.pluginInjections = (_params_pluginInjections = params.pluginInjections) !== null && _params_pluginInjections !== void 0 ? _params_pluginInjections : {};
544
+ var _params_pluginAdapters;
545
+ this.pluginAdapters = (_params_pluginAdapters = params.pluginAdapters) !== null && _params_pluginAdapters !== void 0 ? _params_pluginAdapters : [];
546
+ var _params_pluginConfigs;
547
+ this.pluginConfigs = (_params_pluginConfigs = params.pluginConfigs) !== null && _params_pluginConfigs !== void 0 ? _params_pluginConfigs : [];
548
+ this.templateContext = buildTemplateContext(this.files, this.resources);
504
549
  this.optionsSchema = params.optionsSchema;
505
- // Create scoped memory if provider is configured
506
- if (memoryProvider) {
507
- this.scopedMemory = createScopedMemory(memoryProvider, title, this.currentUser.name);
508
- }
509
550
  // Initialize steps - track guard and wait blocks by index
510
551
  this.steps = [];
511
552
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
@@ -535,27 +576,42 @@ export var BrainEventStream = /*#__PURE__*/ function() {
535
576
  }
536
577
  }
537
578
  }
538
- if (resumeContext) {
539
- // Resume: use state and stepIndex directly from resumeContext
540
- this.currentState = clone(resumeContext.state);
541
- this.currentStepIndex = resumeContext.stepIndex;
579
+ if (resume) {
580
+ // Resume: use state and stepIndex from resume params
581
+ this.currentState = clone(resume.state);
582
+ this.currentStepIndex = resume.stepIndex;
542
583
  // Mark steps before stepIndex as complete (they won't be re-executed)
543
- for(var i = 0; i < resumeContext.stepIndex; i++){
584
+ for(var i = 0; i < resume.stepIndex; i++){
544
585
  this.steps[i].withStatus(STATUS.COMPLETE);
545
586
  }
546
- // For inner brains (no signalProvider), check resumeContext for webhookResponse
587
+ // Re-wrap IterateResult instances that were serialized to plain arrays.
588
+ // During suspension, JSON patches call toJSON() on IterateResult, turning
589
+ // them into plain [item, result][] arrays. Re-wrap so downstream steps
590
+ // can use IterateResult methods (.map, .filter, etc.)
591
+ for(var i1 = 0; i1 < resume.stepIndex; i1++){
592
+ var block1 = this.steps[i1].block;
593
+ if (block1.type === 'map') {
594
+ var mapBlock = block1;
595
+ var value = this.currentState[mapBlock.stateKey];
596
+ if (value != null && Array.isArray(value) && !_instanceof(value, IterateResult)) {
597
+ this.currentState[mapBlock.stateKey] = new IterateResult(value);
598
+ }
599
+ }
600
+ }
601
+ // For inner brains (no signalProvider), check for webhookResponse
547
602
  // The outer brain will have set this from the signal
548
- if (!signalProvider && resumeContext.webhookResponse && !resumeContext.agentContext) {
549
- this.currentResponse = resumeContext.webhookResponse;
603
+ if (!signalProvider && resume.webhookResponse) {
604
+ this.currentResponse = resume.webhookResponse;
550
605
  }
551
- // Agent webhook response is handled via agentContext (checked in executeAgent)
552
606
  // 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), {
607
+ if (resume.currentPage) {
608
+ this.currentPage = resume.currentPage.webhook ? {
609
+ url: resume.currentPage.url,
610
+ webhook: _object_spread_props(_object_spread({}, resume.currentPage.webhook), {
557
611
  schema: z.record(z.unknown())
558
612
  })
613
+ } : {
614
+ url: resume.currentPage.url
559
615
  };
560
616
  }
561
617
  } else {
@@ -569,20 +625,167 @@ export var BrainEventStream = /*#__PURE__*/ function() {
569
625
  }
570
626
  _create_class(BrainEventStream, [
571
627
  {
572
- key: "findWebhookResponseInResumeContext",
573
- value: /**
574
- * Find webhookResponse anywhere in the resumeContext tree (for nested brain resumes)
575
- */ function findWebhookResponseInResumeContext(context) {
576
- if (!context) return undefined;
577
- if (context.webhookResponse) return context.webhookResponse;
578
- return this.findWebhookResponseInResumeContext(context.innerResumeContext);
628
+ key: "next",
629
+ value: function next() {
630
+ return _wrap_async_generator(function() {
631
+ var _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, _value, event, _iteratorNormalCompletion, _didIteratorError1, _iteratorError1, _iterator1, _step1, adapter, err, err1;
632
+ return _ts_generator(this, function(_state) {
633
+ switch(_state.label){
634
+ case 0:
635
+ _iteratorAbruptCompletion = false, _didIteratorError = false;
636
+ _state.label = 1;
637
+ case 1:
638
+ _state.trys.push([
639
+ 1,
640
+ 15,
641
+ 16,
642
+ 21
643
+ ]);
644
+ _iterator = _async_iterator(this.generate());
645
+ _state.label = 2;
646
+ case 2:
647
+ return [
648
+ 4,
649
+ _await_async_generator(_iterator.next())
650
+ ];
651
+ case 3:
652
+ if (!(_iteratorAbruptCompletion = !(_step = _state.sent()).done)) return [
653
+ 3,
654
+ 14
655
+ ];
656
+ _value = _step.value;
657
+ event = _value;
658
+ _iteratorNormalCompletion = true, _didIteratorError1 = false, _iteratorError1 = undefined;
659
+ _state.label = 4;
660
+ case 4:
661
+ _state.trys.push([
662
+ 4,
663
+ 9,
664
+ 10,
665
+ 11
666
+ ]);
667
+ _iterator1 = this.pluginAdapters[Symbol.iterator]();
668
+ _state.label = 5;
669
+ case 5:
670
+ if (!!(_iteratorNormalCompletion = (_step1 = _iterator1.next()).done)) return [
671
+ 3,
672
+ 8
673
+ ];
674
+ adapter = _step1.value;
675
+ return [
676
+ 4,
677
+ _await_async_generator(adapter.dispatch(event))
678
+ ];
679
+ case 6:
680
+ _state.sent();
681
+ _state.label = 7;
682
+ case 7:
683
+ _iteratorNormalCompletion = true;
684
+ return [
685
+ 3,
686
+ 5
687
+ ];
688
+ case 8:
689
+ return [
690
+ 3,
691
+ 11
692
+ ];
693
+ case 9:
694
+ err = _state.sent();
695
+ _didIteratorError1 = true;
696
+ _iteratorError1 = err;
697
+ return [
698
+ 3,
699
+ 11
700
+ ];
701
+ case 10:
702
+ try {
703
+ if (!_iteratorNormalCompletion && _iterator1.return != null) {
704
+ _iterator1.return();
705
+ }
706
+ } finally{
707
+ if (_didIteratorError1) {
708
+ throw _iteratorError1;
709
+ }
710
+ }
711
+ return [
712
+ 7
713
+ ];
714
+ case 11:
715
+ return [
716
+ 4,
717
+ event
718
+ ];
719
+ case 12:
720
+ _state.sent();
721
+ _state.label = 13;
722
+ case 13:
723
+ _iteratorAbruptCompletion = false;
724
+ return [
725
+ 3,
726
+ 2
727
+ ];
728
+ case 14:
729
+ return [
730
+ 3,
731
+ 21
732
+ ];
733
+ case 15:
734
+ err1 = _state.sent();
735
+ _didIteratorError = true;
736
+ _iteratorError = err1;
737
+ return [
738
+ 3,
739
+ 21
740
+ ];
741
+ case 16:
742
+ _state.trys.push([
743
+ 16,
744
+ ,
745
+ 19,
746
+ 20
747
+ ]);
748
+ if (!(_iteratorAbruptCompletion && _iterator.return != null)) return [
749
+ 3,
750
+ 18
751
+ ];
752
+ return [
753
+ 4,
754
+ _await_async_generator(_iterator.return())
755
+ ];
756
+ case 17:
757
+ _state.sent();
758
+ _state.label = 18;
759
+ case 18:
760
+ return [
761
+ 3,
762
+ 20
763
+ ];
764
+ case 19:
765
+ if (_didIteratorError) {
766
+ throw _iteratorError;
767
+ }
768
+ return [
769
+ 7
770
+ ];
771
+ case 20:
772
+ return [
773
+ 7
774
+ ];
775
+ case 21:
776
+ return [
777
+ 2
778
+ ];
779
+ }
780
+ });
781
+ }).call(this);
579
782
  }
580
783
  },
581
784
  {
582
- key: "next",
583
- value: function next() {
785
+ key: "generate",
786
+ value: function generate() {
584
787
  return _wrap_async_generator(function() {
585
- var _this, steps, brainTitle, brainDescription, currentState, options, brainRunId, webhookResponse, signals, webhookSignal, deepest, signals1, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, signal, err, step, guard, waitBlock, err1, error, currentStep;
788
+ var _this, steps, brainTitle, brainDescription, currentState, options, brainRunId, webhookResponse, signals, webhookSignal, _this_resume, signals1, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, signal, err, step, guard, waitBlock, err1, error, currentStep;
586
789
  return _ts_generator(this, function(_state) {
587
790
  switch(_state.label){
588
791
  case 0:
@@ -595,7 +798,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
595
798
  ,
596
799
  36
597
800
  ]);
598
- if (!!this.resumeContext) return [
801
+ if (!!this.resume) return [
599
802
  3,
600
803
  4
601
804
  ];
@@ -617,17 +820,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
617
820
  // Emit initial step status after brain starts
618
821
  return [
619
822
  4,
620
- {
621
- type: BRAIN_EVENTS.STEP_STATUS,
622
- steps: steps.map(function(step) {
623
- var _step_serialized = step.serialized, patch = _step_serialized.patch, rest = _object_without_properties(_step_serialized, [
624
- "patch"
625
- ]);
626
- return rest;
627
- }),
628
- options: options,
629
- brainRunId: brainRunId
630
- }
823
+ this.stepStatusEvent()
631
824
  ];
632
825
  case 3:
633
826
  _state.sent();
@@ -635,7 +828,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
635
828
  if (this.optionsSchema) {
636
829
  this.options = this.optionsSchema.parse(this.options);
637
830
  } 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."));
831
+ throw new Error("Brain '".concat(brainTitle, "' received options but no schema was defined. Use withOptions() to define a schema for options."));
639
832
  }
640
833
  return [
641
834
  3,
@@ -657,18 +850,13 @@ export var BrainEventStream = /*#__PURE__*/ function() {
657
850
  });
658
851
  if (webhookSignal && webhookSignal.type === 'WEBHOOK_RESPONSE') {
659
852
  webhookResponse = webhookSignal.response;
660
- // Set currentResponse for step consumption (non-agent webhooks)
853
+ // Set currentResponse for step consumption
661
854
  this.currentResponse = webhookResponse;
662
- // Set webhookResponse at the deepest level of the resumeContext tree
663
- // This is needed for:
664
- // 1. Agent webhook resumes (via resumeContext.webhookResponse)
665
- // 2. Nested brain resumes (inner brain accesses via innerResumeContext)
666
- if (this.resumeContext) {
667
- deepest = this.resumeContext;
668
- while(deepest.innerResumeContext){
669
- deepest = deepest.innerResumeContext;
670
- }
671
- deepest.webhookResponse = webhookResponse;
855
+ // Store for propagation to inner brains
856
+ if (this.resume) {
857
+ this.resume = _object_spread_props(_object_spread({}, this.resume), {
858
+ webhookResponse: webhookResponse
859
+ });
672
860
  }
673
861
  }
674
862
  return [
@@ -676,9 +864,8 @@ export var BrainEventStream = /*#__PURE__*/ function() {
676
864
  7
677
865
  ];
678
866
  case 6:
679
- // Inner brain (no signalProvider): check resumeContext for webhookResponse
680
- // The outer brain will have set this from the signal
681
- webhookResponse = this.findWebhookResponseInResumeContext(this.resumeContext);
867
+ // Inner brain (no signalProvider): check for webhookResponse passed from outer brain
868
+ webhookResponse = (_this_resume = this.resume) === null || _this_resume === void 0 ? void 0 : _this_resume.webhookResponse;
682
869
  _state.label = 7;
683
870
  case 7:
684
871
  if (!webhookResponse) return [
@@ -886,17 +1073,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
886
1073
  // Step Status Event to indicate that the step is running
887
1074
  return [
888
1075
  4,
889
- {
890
- type: BRAIN_EVENTS.STEP_STATUS,
891
- steps: steps.map(function(step) {
892
- var _step_serialized = step.serialized, patch = _step_serialized.patch, rest = _object_without_properties(_step_serialized, [
893
- "patch"
894
- ]);
895
- return rest;
896
- }),
897
- options: options,
898
- brainRunId: brainRunId
899
- }
1076
+ this.stepStatusEvent()
900
1077
  ];
901
1078
  case 28:
902
1079
  _state.sent();
@@ -917,17 +1094,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
917
1094
  // Step Status Event
918
1095
  return [
919
1096
  4,
920
- {
921
- type: BRAIN_EVENTS.STEP_STATUS,
922
- steps: steps.map(function(step) {
923
- var _step_serialized = step.serialized, patch = _step_serialized.patch, rest = _object_without_properties(_step_serialized, [
924
- "patch"
925
- ]);
926
- return rest;
927
- }),
928
- options: options,
929
- brainRunId: brainRunId
930
- }
1097
+ this.stepStatusEvent()
931
1098
  ];
932
1099
  case 30:
933
1100
  _state.sent();
@@ -980,17 +1147,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
980
1147
  // Step Status Event
981
1148
  return [
982
1149
  4,
983
- {
984
- type: BRAIN_EVENTS.STEP_STATUS,
985
- steps: steps.map(function(step) {
986
- var _step_serialized = step.serialized, patch = _step_serialized.patch, rest = _object_without_properties(_step_serialized, [
987
- "patch"
988
- ]);
989
- return rest;
990
- }),
991
- options: options,
992
- brainRunId: brainRunId
993
- }
1150
+ this.stepStatusEvent()
994
1151
  ];
995
1152
  case 35:
996
1153
  _state.sent();
@@ -1004,6 +1161,39 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1004
1161
  }).call(this);
1005
1162
  }
1006
1163
  },
1164
+ {
1165
+ key: "stepStatusEvent",
1166
+ value: function stepStatusEvent() {
1167
+ return {
1168
+ type: BRAIN_EVENTS.STEP_STATUS,
1169
+ steps: this.steps.map(function(s) {
1170
+ var _s_serialized = s.serialized, patch = _s_serialized.patch, rest = _object_without_properties(_s_serialized, [
1171
+ "patch"
1172
+ ]);
1173
+ return rest;
1174
+ }),
1175
+ options: this.options,
1176
+ brainRunId: this.brainRunId
1177
+ };
1178
+ }
1179
+ },
1180
+ {
1181
+ key: "innerBrainParams",
1182
+ get: /** Params forwarded to inner brain runs (nested .brain() and .map() steps). */ function get() {
1183
+ return {
1184
+ resources: this.resources,
1185
+ client: this.client,
1186
+ currentUser: this.currentUser,
1187
+ env: this.env,
1188
+ brainRunId: this.brainRunId,
1189
+ governor: this.governor,
1190
+ files: this.files,
1191
+ pages: this.pages,
1192
+ storeProvider: this.storeProvider,
1193
+ pluginConfigs: this.pluginConfigs
1194
+ };
1195
+ }
1196
+ },
1007
1197
  {
1008
1198
  key: "buildStepContext",
1009
1199
  value: function buildStepContext(step) {
@@ -1017,35 +1207,36 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1017
1207
  page: this.currentPage,
1018
1208
  pages: this.pages,
1019
1209
  env: this.env,
1020
- memory: this.scopedMemory,
1210
+ components: this.components,
1021
1211
  store: this.store,
1212
+ files: this.files,
1022
1213
  currentUser: this.currentUser,
1023
1214
  brainRunId: this.brainRunId,
1024
1215
  stepId: step.id
1025
- }, this.services);
1216
+ }, this.pluginInjections);
1026
1217
  }
1027
1218
  },
1028
1219
  {
1029
1220
  key: "executeStep",
1030
1221
  value: function executeStep(step) {
1031
1222
  return _wrap_async_generator(function() {
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;
1223
+ var block, stepBlock, _this_resume, brainBlock, initialState, innerOptions, innerStack, hasInnerResume, innerEntry, remainingStack, patches, innerBrainPaused, innerRun, innerDepth, _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, _value, event, err1, _innerEntry_state, baseState, innerState, prevState, prevState1, stepBlock1, stepClient, channel, context, _this_options, wrappedFiles, stepDone, stepResult, stepError, stepPromise, _iteratorNormalCompletion, _didIteratorError1, _iteratorError1, _iterator1, _step1, event1, err, _iteratorNormalCompletion1, _didIteratorError2, _iteratorError2, _iterator2, _step2, event2, err, result;
1033
1224
  return _ts_generator(this, function(_state) {
1034
1225
  switch(_state.label){
1035
1226
  case 0:
1036
1227
  block = step.block;
1037
1228
  if (!(block.type === 'step')) return [
1038
1229
  3,
1039
- 4
1230
+ 2
1040
1231
  ];
1041
1232
  stepBlock = block;
1042
- if (!stepBlock.isUIStep) return [
1233
+ if (!stepBlock.isPageStep) return [
1043
1234
  3,
1044
1235
  2
1045
1236
  ];
1046
1237
  return [
1047
1238
  5,
1048
- _ts_values(_async_generator_delegate(_async_iterator(this.executeUIStep(step, stepBlock))))
1239
+ _ts_values(_async_generator_delegate(_async_iterator(this.executePageStep(step, stepBlock))))
1049
1240
  ];
1050
1241
  case 1:
1051
1242
  _state.sent();
@@ -1053,13 +1244,13 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1053
1244
  2
1054
1245
  ];
1055
1246
  case 2:
1056
- if (!stepBlock.iterateConfig) return [
1247
+ if (!(block.type === 'prompt')) return [
1057
1248
  3,
1058
1249
  4
1059
1250
  ];
1060
1251
  return [
1061
1252
  5,
1062
- _ts_values(_async_generator_delegate(_async_iterator(this.executeIteratePrompt(step))))
1253
+ _ts_values(_async_generator_delegate(_async_iterator(this.executePrompt(step))))
1063
1254
  ];
1064
1255
  case 3:
1065
1256
  _state.sent();
@@ -1067,18 +1258,13 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1067
1258
  2
1068
1259
  ];
1069
1260
  case 4:
1070
- if (!(block.type === 'brain')) return [
1071
- 3,
1072
- 22
1073
- ];
1074
- brainBlock = block;
1075
- if (!brainBlock.iterateConfig) return [
1261
+ if (!(block.type === 'map')) return [
1076
1262
  3,
1077
1263
  6
1078
1264
  ];
1079
1265
  return [
1080
1266
  5,
1081
- _ts_values(_async_generator_delegate(_async_iterator(this.executeIterateBrain(step))))
1267
+ _ts_values(_async_generator_delegate(_async_iterator(this.executeMap(step))))
1082
1268
  ];
1083
1269
  case 5:
1084
1270
  _state.sent();
@@ -1086,34 +1272,43 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1086
1272
  2
1087
1273
  ];
1088
1274
  case 6:
1089
- initialState = typeof brainBlock.initialState === 'function' ? brainBlock.initialState(this.currentState) : brainBlock.initialState;
1090
- // Check if we're resuming and if there's an inner resume context
1091
- innerResumeContext = (_this_resumeContext = this.resumeContext) === null || _this_resumeContext === void 0 ? void 0 : _this_resumeContext.innerResumeContext;
1275
+ if (!(block.type === 'brain')) return [
1276
+ 3,
1277
+ 21
1278
+ ];
1279
+ brainBlock = block;
1280
+ initialState = brainBlock.initialState ? typeof brainBlock.initialState === 'function' ? brainBlock.initialState(this.buildStepContext(step)) : brainBlock.initialState : {};
1281
+ innerOptions = brainBlock.options ? typeof brainBlock.options === 'function' ? brainBlock.options(this.buildStepContext(step)) : brainBlock.options : {};
1282
+ // Check if we're resuming an inner brain
1283
+ innerStack = (_this_resume = this.resume) === null || _this_resume === void 0 ? void 0 : _this_resume.innerStack;
1284
+ hasInnerResume = innerStack && innerStack.length > 0;
1285
+ innerEntry = hasInnerResume ? innerStack[0] : undefined;
1286
+ remainingStack = hasInnerResume ? innerStack.slice(1) : undefined;
1092
1287
  // Run inner brain and yield all its events
1093
1288
  // Pass brainRunId so inner brain shares outer brain's run ID
1094
1289
  patches = [];
1095
1290
  innerBrainPaused = false;
1096
- innerRun = innerResumeContext ? brainBlock.innerBrain.run({
1097
- resources: this.resources,
1098
- client: this.client,
1099
- currentUser: this.currentUser,
1100
- resumeContext: innerResumeContext,
1101
- options: (_this_options = this.options) !== null && _this_options !== void 0 ? _this_options : {},
1102
- pages: this.pages,
1103
- env: this.env,
1104
- brainRunId: this.brainRunId,
1105
- governor: this.governor
1106
- }) : brainBlock.innerBrain.run({
1107
- resources: this.resources,
1108
- client: this.client,
1109
- currentUser: this.currentUser,
1291
+ innerRun = hasInnerResume ? brainBlock.innerBrain.run(_object_spread_props(_object_spread({}, this.innerBrainParams), {
1292
+ resume: _object_spread_props(_object_spread({}, this.resume), {
1293
+ state: innerEntry.state,
1294
+ stepIndex: innerEntry.stepIndex,
1295
+ innerStack: (remainingStack === null || remainingStack === void 0 ? void 0 : remainingStack.length) ? remainingStack : undefined
1296
+ }),
1297
+ options: innerOptions
1298
+ })) : brainBlock.innerBrain.run(_object_spread_props(_object_spread({}, this.innerBrainParams), {
1110
1299
  initialState: initialState,
1111
- options: (_this_options1 = this.options) !== null && _this_options1 !== void 0 ? _this_options1 : {},
1112
- pages: this.pages,
1113
- env: this.env,
1114
- brainRunId: this.brainRunId,
1115
- governor: this.governor
1116
- });
1300
+ options: innerOptions
1301
+ }));
1302
+ // Context has been forwarded to the inner brain — clear so outer
1303
+ // brain's later steps don't consume them.
1304
+ if (hasInnerResume) {
1305
+ this.resume = undefined;
1306
+ }
1307
+ // Track nesting depth so we only collect patches from the direct
1308
+ // child brain (depth 1) and ignore patches from deeper nested brains
1309
+ // (e.g. inner brains run by .map() or nested .brain() steps).
1310
+ // Resumed brains skip their START event, so start at depth 1.
1311
+ innerDepth = hasInnerResume ? 1 : 0;
1117
1312
  _iteratorAbruptCompletion = false, _didIteratorError = false;
1118
1313
  _state.label = 7;
1119
1314
  case 7:
@@ -1143,19 +1338,29 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1143
1338
  ];
1144
1339
  case 10:
1145
1340
  _state.sent(); // Forward all inner brain events
1146
- if (event.type === BRAIN_EVENTS.STEP_COMPLETE) {
1341
+ if (event.type === BRAIN_EVENTS.START) {
1342
+ innerDepth++;
1343
+ }
1344
+ if (event.type === BRAIN_EVENTS.STEP_COMPLETE && innerDepth === 1) {
1147
1345
  patches.push(event.patch);
1148
1346
  }
1149
1347
  // If inner brain yielded a WEBHOOK event, it's pausing
1150
1348
  if (event.type === BRAIN_EVENTS.WEBHOOK) {
1151
1349
  innerBrainPaused = true;
1152
1350
  }
1153
- // If inner brain completed, break immediately to prevent hanging
1154
1351
  if (event.type === BRAIN_EVENTS.COMPLETE) {
1155
- return [
1156
- 3,
1157
- 12
1158
- ];
1352
+ innerDepth--;
1353
+ if (innerDepth === 0) {
1354
+ return [
1355
+ 3,
1356
+ 12
1357
+ ];
1358
+ }
1359
+ }
1360
+ // Errored brains emit ERROR instead of COMPLETE, so decrement depth
1361
+ // to keep tracking accurate when errors are caught (e.g. by .map() error handlers)
1362
+ if (event.type === BRAIN_EVENTS.ERROR) {
1363
+ innerDepth--;
1159
1364
  }
1160
1365
  _state.label = 11;
1161
1366
  case 11:
@@ -1170,9 +1375,9 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1170
1375
  19
1171
1376
  ];
1172
1377
  case 13:
1173
- err = _state.sent();
1378
+ err1 = _state.sent();
1174
1379
  _didIteratorError = true;
1175
- _iteratorError = err;
1380
+ _iteratorError = err1;
1176
1381
  return [
1177
1382
  3,
1178
1383
  19
@@ -1221,90 +1426,187 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1221
1426
  }
1222
1427
  // Apply collected patches to get final inner state
1223
1428
  // When resuming, use the resumed state as base; otherwise use initialState
1224
- baseState = (_innerResumeContext_state = innerResumeContext === null || innerResumeContext === void 0 ? void 0 : innerResumeContext.state) !== null && _innerResumeContext_state !== void 0 ? _innerResumeContext_state : initialState;
1429
+ baseState = (_innerEntry_state = innerEntry === null || innerEntry === void 0 ? void 0 : innerEntry.state) !== null && _innerEntry_state !== void 0 ? _innerEntry_state : initialState;
1225
1430
  innerState = applyPatches(baseState, patches);
1226
1431
  // Get previous state before action
1227
1432
  prevState = this.currentState;
1228
- // Update state with inner brain results
1229
- _ = this;
1230
- return [
1231
- 4,
1232
- _await_async_generator(brainBlock.action(this.currentState, innerState, this.services))
1233
- ];
1234
- case 20:
1235
- _.currentState = _state.sent();
1433
+ // Spread inner brain's final state onto outer state
1434
+ this.currentState = _object_spread({}, this.currentState, innerState);
1236
1435
  return [
1237
1436
  5,
1238
1437
  _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState))))
1239
1438
  ];
1240
- case 21:
1439
+ case 20:
1241
1440
  _state.sent();
1242
1441
  return [
1243
1442
  3,
1244
- 30
1443
+ 42
1245
1444
  ];
1445
+ case 21:
1446
+ // Get previous state before action
1447
+ prevState1 = this.currentState;
1448
+ stepBlock1 = block;
1449
+ // Resolve per-step client: if the step has an override, apply governor to it;
1450
+ // otherwise use the default (already-governed) client
1451
+ stepClient = stepBlock1.client ? this.governor ? this.governor(stepBlock1.client) : stepBlock1.client : this.client;
1452
+ // Event channel lets file operations (and potentially other services)
1453
+ // emit events mid-step. The race loop yields them as they arrive.
1454
+ // If no events are pushed, the loop resolves immediately with the step.
1455
+ channel = new EventChannel();
1456
+ context = this.buildStepContext(step);
1457
+ wrappedFiles = this.files ? wrapFilesWithEvents(this.files, channel, {
1458
+ options: (_this_options = this.options) !== null && _this_options !== void 0 ? _this_options : {},
1459
+ brainRunId: this.brainRunId,
1460
+ stepTitle: stepBlock1.title
1461
+ }) : undefined;
1462
+ stepDone = false;
1463
+ stepPromise = Promise.resolve(stepBlock1.action(_object_spread(_object_spread_props(_object_spread({}, context), {
1464
+ client: stepClient
1465
+ }), wrappedFiles && {
1466
+ files: wrappedFiles
1467
+ }))).then(function(r) {
1468
+ stepDone = true;
1469
+ stepResult = r;
1470
+ }, function(e) {
1471
+ stepDone = true;
1472
+ stepError = e;
1473
+ });
1474
+ _state.label = 22;
1246
1475
  case 22:
1247
- if (!(block.type === 'agent')) return [
1248
- 3,
1249
- 27
1250
- ];
1251
- agentBlock = block;
1252
- if (!agentBlock.iterateConfig) return [
1476
+ if (!!stepDone) return [
1253
1477
  3,
1254
- 24
1478
+ 32
1255
1479
  ];
1256
1480
  return [
1257
- 5,
1258
- _ts_values(_async_generator_delegate(_async_iterator(this.executeIterateAgent(step))))
1481
+ 4,
1482
+ _await_async_generator(Promise.race([
1483
+ stepPromise,
1484
+ channel.wait()
1485
+ ]))
1259
1486
  ];
1260
1487
  case 23:
1261
1488
  _state.sent();
1262
- return [
1263
- 2
1264
- ];
1489
+ _iteratorNormalCompletion = true, _didIteratorError1 = false, _iteratorError1 = undefined;
1490
+ _state.label = 24;
1265
1491
  case 24:
1266
- prevState1 = this.currentState;
1492
+ _state.trys.push([
1493
+ 24,
1494
+ 29,
1495
+ 30,
1496
+ 31
1497
+ ]);
1498
+ _iterator1 = channel.drain()[Symbol.iterator]();
1499
+ _state.label = 25;
1500
+ case 25:
1501
+ if (!!(_iteratorNormalCompletion = (_step1 = _iterator1.next()).done)) return [
1502
+ 3,
1503
+ 28
1504
+ ];
1505
+ event1 = _step1.value;
1267
1506
  return [
1268
- 5,
1269
- _ts_values(_async_generator_delegate(_async_iterator(this.executeAgent(step))))
1507
+ 4,
1508
+ event1
1270
1509
  ];
1271
- case 25:
1510
+ case 26:
1272
1511
  _state.sent();
1273
- return [
1274
- 5,
1275
- _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState1))))
1512
+ _state.label = 27;
1513
+ case 27:
1514
+ _iteratorNormalCompletion = true;
1515
+ return [
1516
+ 3,
1517
+ 25
1276
1518
  ];
1277
- case 26:
1278
- _state.sent();
1519
+ case 28:
1279
1520
  return [
1280
1521
  3,
1281
- 30
1522
+ 31
1282
1523
  ];
1283
- case 27:
1284
- // Get previous state before action
1285
- prevState2 = this.currentState;
1286
- stepBlock1 = block;
1287
- // Resolve per-step client: if the step has an override, apply governor to it;
1288
- // otherwise use the default (already-governed) client
1289
- stepClient = stepBlock1.client ? this.governor ? this.governor(stepBlock1.client) : stepBlock1.client : this.client;
1524
+ case 29:
1525
+ err = _state.sent();
1526
+ _didIteratorError1 = true;
1527
+ _iteratorError1 = err;
1528
+ return [
1529
+ 3,
1530
+ 31
1531
+ ];
1532
+ case 30:
1533
+ try {
1534
+ if (!_iteratorNormalCompletion && _iterator1.return != null) {
1535
+ _iterator1.return();
1536
+ }
1537
+ } finally{
1538
+ if (_didIteratorError1) {
1539
+ throw _iteratorError1;
1540
+ }
1541
+ }
1542
+ return [
1543
+ 7
1544
+ ];
1545
+ case 31:
1546
+ return [
1547
+ 3,
1548
+ 22
1549
+ ];
1550
+ case 32:
1551
+ _iteratorNormalCompletion1 = true, _didIteratorError2 = false, _iteratorError2 = undefined;
1552
+ _state.label = 33;
1553
+ case 33:
1554
+ _state.trys.push([
1555
+ 33,
1556
+ 38,
1557
+ 39,
1558
+ 40
1559
+ ]);
1560
+ _iterator2 = channel.drain()[Symbol.iterator]();
1561
+ _state.label = 34;
1562
+ case 34:
1563
+ if (!!(_iteratorNormalCompletion1 = (_step2 = _iterator2.next()).done)) return [
1564
+ 3,
1565
+ 37
1566
+ ];
1567
+ event2 = _step2.value;
1290
1568
  return [
1291
1569
  4,
1292
- _await_async_generator(Promise.resolve(stepBlock1.action(_object_spread({
1293
- state: this.currentState,
1294
- options: (_this_options2 = this.options) !== null && _this_options2 !== void 0 ? _this_options2 : {},
1295
- client: stepClient,
1296
- resources: this.resources,
1297
- response: this.currentResponse,
1298
- page: this.currentPage,
1299
- pages: this.pages,
1300
- env: this.env,
1301
- memory: this.scopedMemory,
1302
- store: this.store,
1303
- currentUser: this.currentUser
1304
- }, this.services))))
1570
+ event2
1305
1571
  ];
1306
- case 28:
1307
- result = _state.sent();
1572
+ case 35:
1573
+ _state.sent();
1574
+ _state.label = 36;
1575
+ case 36:
1576
+ _iteratorNormalCompletion1 = true;
1577
+ return [
1578
+ 3,
1579
+ 34
1580
+ ];
1581
+ case 37:
1582
+ return [
1583
+ 3,
1584
+ 40
1585
+ ];
1586
+ case 38:
1587
+ err = _state.sent();
1588
+ _didIteratorError2 = true;
1589
+ _iteratorError2 = err;
1590
+ return [
1591
+ 3,
1592
+ 40
1593
+ ];
1594
+ case 39:
1595
+ try {
1596
+ if (!_iteratorNormalCompletion1 && _iterator2.return != null) {
1597
+ _iterator2.return();
1598
+ }
1599
+ } finally{
1600
+ if (_didIteratorError2) {
1601
+ throw _iteratorError2;
1602
+ }
1603
+ }
1604
+ return [
1605
+ 7
1606
+ ];
1607
+ case 40:
1608
+ if (stepError) throw stepError;
1609
+ result = stepResult;
1308
1610
  // Extract state from result (handles promptResponse case)
1309
1611
  if (result && (typeof result === "undefined" ? "undefined" : _type_of(result)) === 'object' && 'promptResponse' in result) {
1310
1612
  this.currentState = result.state;
@@ -1313,9 +1615,9 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1313
1615
  }
1314
1616
  return [
1315
1617
  5,
1316
- _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState2))))
1618
+ _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState1))))
1317
1619
  ];
1318
- case 29:
1620
+ case 41:
1319
1621
  _state.sent();
1320
1622
  // Handle promptResponse - set currentResponse for next step
1321
1623
  if (result && (typeof result === "undefined" ? "undefined" : _type_of(result)) === 'object' && 'promptResponse' in result) {
@@ -1323,8 +1625,8 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1323
1625
  }
1324
1626
  // Reset currentPage after step consumes it (page is ephemeral)
1325
1627
  this.currentPage = undefined;
1326
- _state.label = 30;
1327
- case 30:
1628
+ _state.label = 42;
1629
+ case 42:
1328
1630
  return [
1329
1631
  2
1330
1632
  ];
@@ -1334,1053 +1636,934 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1334
1636
  }
1335
1637
  },
1336
1638
  {
1337
- key: "executeAgent",
1338
- value: function executeAgent(step) {
1639
+ key: "executePrompt",
1640
+ value: /**
1641
+ * Execute a prompt step. Either single-shot (generateObject) or
1642
+ * iterative tool-calling loop (generateText) when `loop` is present.
1643
+ */ function executePrompt(step) {
1339
1644
  return _wrap_async_generator(function() {
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;
1645
+ var block, prevState, config, client, prompt, system, _tmp, attachments, _tmp1, result, loopGen, _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, _value, event, err;
1341
1646
  return _ts_generator(this, function(_state) {
1342
1647
  switch(_state.label){
1343
1648
  case 0:
1344
1649
  block = step.block;
1345
- prevState = this.currentState;
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 : {});
1348
- components = (_this_components = this.components) !== null && _this_components !== void 0 ? _this_components : {};
1650
+ prevState = clone(this.currentState);
1349
1651
  return [
1350
1652
  4,
1351
- _await_async_generator(block.configFn(_object_spread({
1352
- state: this.currentState,
1353
- options: (_this_options = this.options) !== null && _this_options !== void 0 ? _this_options : {},
1354
- tools: allTools,
1355
- components: components,
1356
- client: this.client,
1357
- resources: this.resources,
1358
- response: this.currentResponse,
1359
- page: this.currentPage,
1360
- pages: this.pages,
1361
- env: this.env,
1362
- memory: this.scopedMemory,
1363
- store: this.store,
1364
- currentUser: this.currentUser
1365
- }, this.services)))
1653
+ _await_async_generator(block.configFn(this.buildStepContext(step)))
1366
1654
  ];
1367
1655
  case 1:
1368
1656
  config = _state.sent();
1369
- // Reset currentPage after configFn consumes it (page is ephemeral)
1370
- this.currentPage = undefined;
1371
- // Merge tools: step tools override defaults + extras
1372
- mergedTools = _object_spread({}, allTools, (_config_tools = config.tools) !== null && _config_tools !== void 0 ? _config_tools : {});
1373
- // Always generate a 'done' terminal tool for every agent
1374
- // If outputSchema is provided, use that schema; otherwise use defaultDoneSchema
1375
- if (config.outputSchema) {
1376
- _config_outputSchema = config.outputSchema, schema = _config_outputSchema.schema, name = _config_outputSchema.name;
1377
- mergedTools['done'] = {
1378
- description: "Signal that the task is complete and provide the final ".concat(name, " result.\n\nPURPOSE: End agent execution and return structured output to the calling system.\n\nBEHAVIOR:\n- This is a TERMINAL tool - calling it immediately ends the agent\n- No further tools will execute after this\n- No further iterations will occur\n- The input you provide becomes the agent's final output\n\nWHEN TO CALL:\n- When you have completed the assigned task\n- When you have gathered all required information\n- When you have the final answer or result ready\n\nDO NOT CALL IF:\n- You still need to gather more information\n- You are waiting for user input (use waitForWebhook instead)\n- The task is not yet complete\n\nThe schema for this result is: ").concat(name),
1379
- inputSchema: schema,
1380
- terminal: true
1381
- };
1382
- } else {
1383
- mergedTools['done'] = {
1384
- description: "Signal that the task is complete and provide a summary of what was accomplished.\n\nPURPOSE: End agent execution and return a result string to the calling system.\n\nBEHAVIOR:\n- This is a TERMINAL tool - calling it immediately ends the agent\n- No further tools will execute after this\n- No further iterations will occur\n- The result string you provide becomes the agent's final output\n\nWHEN TO CALL:\n- When you have completed the assigned task\n- When you have gathered all required information\n- When you have the final answer ready to report\n\nDO NOT CALL IF:\n- You still need to gather more information\n- You are waiting for user input (use waitForWebhook instead)\n- The task is not yet complete\n\nProvide a clear, concise summary of the outcome in the 'result' field.",
1385
- inputSchema: defaultDoneSchema,
1386
- terminal: true
1387
- };
1388
- }
1389
- // Check if we're resuming from a previous agent execution
1390
- agentContext = (_this_resumeContext = this.resumeContext) === null || _this_resumeContext === void 0 ? void 0 : _this_resumeContext.agentContext;
1391
- webhookResponse = (_this_resumeContext1 = this.resumeContext) === null || _this_resumeContext1 === void 0 ? void 0 : _this_resumeContext1.webhookResponse;
1392
- // Use preserved stepId from agentContext when resuming, or step.id for fresh start
1393
- // This ensures all events for the same agent use the same stepId across resumes
1394
- effectiveStepId = (_agentContext_stepId = agentContext === null || agentContext === void 0 ? void 0 : agentContext.stepId) !== null && _agentContext_stepId !== void 0 ? _agentContext_stepId : step.id;
1395
- if (!agentContext) return [
1396
- 3,
1397
- 9
1398
- ];
1399
- if (!(webhookResponse && agentContext.pendingToolCallId && agentContext.pendingToolName)) return [
1400
- 3,
1401
- 7
1402
- ];
1403
- // WEBHOOK RESUME: Agent was waiting for a webhook response
1404
- // Emit WEBHOOK_RESPONSE event to record the response
1657
+ client = config.client ? this.governor ? this.governor(config.client) : config.client : this.client;
1405
1658
  return [
1406
1659
  4,
1407
- {
1408
- type: BRAIN_EVENTS.WEBHOOK_RESPONSE,
1409
- response: webhookResponse,
1410
- options: (_this_options1 = this.options) !== null && _this_options1 !== void 0 ? _this_options1 : {},
1411
- brainRunId: this.brainRunId
1412
- }
1660
+ _await_async_generator(resolveTemplate(config.message, this.templateContext))
1413
1661
  ];
1414
1662
  case 2:
1415
- _state.sent();
1416
- // Emit AGENT_TOOL_RESULT for the pending tool (webhook response injected as tool result)
1663
+ prompt = _state.sent();
1664
+ if (!config.system) return [
1665
+ 3,
1666
+ 4
1667
+ ];
1417
1668
  return [
1418
1669
  4,
1419
- {
1420
- type: BRAIN_EVENTS.AGENT_TOOL_RESULT,
1421
- stepTitle: step.block.title,
1422
- stepId: effectiveStepId,
1423
- toolCallId: agentContext.pendingToolCallId,
1424
- toolName: agentContext.pendingToolName,
1425
- result: webhookResponse,
1426
- options: (_this_options2 = this.options) !== null && _this_options2 !== void 0 ? _this_options2 : {},
1427
- brainRunId: this.brainRunId
1428
- }
1670
+ _await_async_generator(resolveTemplate(config.system, this.templateContext))
1429
1671
  ];
1430
1672
  case 3:
1431
- _state.sent();
1432
- // Use restored responseMessages from the agent context (preserves providerOptions)
1433
- // Prepend the user message and append the webhook response
1434
- // Note: reconstructed messages don't include the placeholder (we don't emit events for it),
1435
- // so we just append the real webhook response here.
1436
- userMessage = {
1437
- role: 'user',
1438
- content: agentContext.prompt
1439
- };
1440
- if (!this.client.createToolResultMessage) return [
1673
+ _tmp = _state.sent();
1674
+ return [
1441
1675
  3,
1442
1676
  5
1443
1677
  ];
1444
- toolResultMessage = this.client.createToolResultMessage(agentContext.pendingToolCallId, agentContext.pendingToolName, webhookResponse);
1445
- responseMessages = [
1446
- userMessage
1447
- ].concat(_to_consumable_array(agentContext.responseMessages), [
1448
- toolResultMessage
1449
- ]);
1450
- // Emit event for this tool result message (for reconstruction if there's another pause)
1451
- return [
1452
- 4,
1453
- {
1454
- type: BRAIN_EVENTS.AGENT_RAW_RESPONSE_MESSAGE,
1455
- stepTitle: step.block.title,
1456
- stepId: effectiveStepId,
1457
- iteration: 0,
1458
- message: toolResultMessage,
1459
- options: (_this_options3 = this.options) !== null && _this_options3 !== void 0 ? _this_options3 : {},
1460
- brainRunId: this.brainRunId
1461
- }
1462
- ];
1463
1678
  case 4:
1464
- _state.sent();
1465
- return [
1679
+ _tmp = undefined;
1680
+ _state.label = 5;
1681
+ case 5:
1682
+ system = _tmp;
1683
+ if (!!config.loop) return [
1466
1684
  3,
1467
- 6
1685
+ 11
1686
+ ];
1687
+ if (!config.attachments) return [
1688
+ 3,
1689
+ 7
1690
+ ];
1691
+ return [
1692
+ 4,
1693
+ _await_async_generator(Promise.all(config.attachments.map(function(handle) {
1694
+ return _async_to_generator(function() {
1695
+ var _tmp;
1696
+ return _ts_generator(this, function(_state) {
1697
+ switch(_state.label){
1698
+ case 0:
1699
+ _tmp = {
1700
+ name: handle.name,
1701
+ mimeType: guessMimeType(handle.name)
1702
+ };
1703
+ return [
1704
+ 4,
1705
+ handle.readBytes()
1706
+ ];
1707
+ case 1:
1708
+ return [
1709
+ 2,
1710
+ (_tmp.data = _state.sent(), _tmp)
1711
+ ];
1712
+ }
1713
+ });
1714
+ })();
1715
+ })))
1468
1716
  ];
1469
- case 5:
1470
- // Fallback if client doesn't support createToolResultMessage
1471
- responseMessages = [
1472
- userMessage
1473
- ].concat(_to_consumable_array(agentContext.responseMessages));
1474
- _state.label = 6;
1475
1717
  case 6:
1476
- // Set empty initial messages since user message is in responseMessages
1477
- initialMessages = [];
1718
+ _tmp1 = _state.sent();
1478
1719
  return [
1479
1720
  3,
1480
1721
  8
1481
1722
  ];
1482
1723
  case 7:
1483
- // PAUSE RESUME: Agent was paused mid-execution (no pending webhook)
1484
- // Restore conversation history and continue from where we left off
1485
- userMessage1 = {
1486
- role: 'user',
1487
- content: agentContext.prompt
1488
- };
1489
- responseMessages = [
1490
- userMessage1
1491
- ].concat(_to_consumable_array(agentContext.responseMessages));
1492
- initialMessages = [];
1724
+ _tmp1 = undefined;
1493
1725
  _state.label = 8;
1494
1726
  case 8:
1495
- // Clear the resume context so it's only used once
1496
- this.resumeContext = undefined;
1727
+ attachments = _tmp1;
1497
1728
  return [
1498
- 3,
1499
- 11
1729
+ 4,
1730
+ _await_async_generator(client.generateObject({
1731
+ schema: config.outputSchema,
1732
+ prompt: prompt,
1733
+ system: system,
1734
+ attachments: attachments
1735
+ }))
1500
1736
  ];
1501
1737
  case 9:
1502
- // Use "Begin." as default prompt if not provided
1503
- prompt = (_config_prompt = config.prompt) !== null && _config_prompt !== void 0 ? _config_prompt : 'Begin.';
1504
- // Emit agent start event (only for fresh starts)
1738
+ result = _state.sent();
1739
+ this.currentState = _object_spread({}, this.currentState, result.object);
1505
1740
  return [
1506
- 4,
1507
- {
1508
- type: BRAIN_EVENTS.AGENT_START,
1509
- stepTitle: step.block.title,
1510
- stepId: effectiveStepId,
1511
- prompt: prompt,
1512
- system: config.system,
1513
- tools: Object.keys(mergedTools),
1514
- options: (_this_options4 = this.options) !== null && _this_options4 !== void 0 ? _this_options4 : {},
1515
- brainRunId: this.brainRunId
1516
- }
1741
+ 5,
1742
+ _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState))))
1517
1743
  ];
1518
1744
  case 10:
1519
1745
  _state.sent();
1520
- // Initialize messages for fresh start
1521
- initialMessages = [
1522
- {
1523
- role: 'user',
1524
- content: prompt
1525
- }
1746
+ return [
1747
+ 2
1526
1748
  ];
1527
- _state.label = 11;
1528
1749
  case 11:
1529
- // Initialize token tracking
1530
- totalTokens = 0;
1531
- iteration = 0;
1532
- maxIterations = (_config_maxIterations = config.maxIterations) !== null && _config_maxIterations !== void 0 ? _config_maxIterations : 100;
1750
+ // Loop path: tool-calling iteration
1751
+ loopGen = this.runPromptLoop({
1752
+ step: step,
1753
+ prompt: prompt,
1754
+ system: system,
1755
+ client: client,
1756
+ outputSchema: config.outputSchema,
1757
+ loopConfig: config.loop,
1758
+ allowWebhookSuspension: true,
1759
+ resume: this.resume
1760
+ });
1761
+ _iteratorAbruptCompletion = false, _didIteratorError = false;
1533
1762
  _state.label = 12;
1534
1763
  case 12:
1535
- if (!true) return [
1536
- 3,
1537
- 55
1538
- ];
1539
- iteration++;
1540
- if (!this.signalProvider) return [
1541
- 3,
1542
- 26
1543
- ];
1764
+ _state.trys.push([
1765
+ 12,
1766
+ 18,
1767
+ 19,
1768
+ 24
1769
+ ]);
1770
+ _iterator = _async_iterator(loopGen);
1771
+ _state.label = 13;
1772
+ case 13:
1544
1773
  return [
1545
1774
  4,
1546
- _await_async_generator(this.signalProvider.getSignals('ALL'))
1775
+ _await_async_generator(_iterator.next())
1547
1776
  ];
1548
- case 13:
1549
- signals = _state.sent();
1550
- _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1551
- _state.label = 14;
1552
1777
  case 14:
1553
- _state.trys.push([
1554
- 14,
1555
- 24,
1556
- 25,
1557
- 26
1558
- ]);
1559
- _iterator = signals[Symbol.iterator]();
1560
- _state.label = 15;
1561
- case 15:
1562
- if (!!(_iteratorNormalCompletion = (_step = _iterator.next()).done)) return [
1563
- 3,
1564
- 23
1565
- ];
1566
- signal = _step.value;
1567
- if (!(signal.type === 'KILL')) return [
1778
+ if (!(_iteratorAbruptCompletion = !(_step = _state.sent()).done)) return [
1568
1779
  3,
1569
1780
  17
1570
1781
  ];
1782
+ _value = _step.value;
1783
+ event = _value;
1571
1784
  return [
1572
1785
  4,
1573
- {
1574
- type: BRAIN_EVENTS.CANCELLED,
1575
- status: STATUS.CANCELLED,
1576
- brainTitle: this.title,
1577
- brainDescription: this.description,
1578
- brainRunId: this.brainRunId,
1579
- options: this.options
1580
- }
1786
+ event
1581
1787
  ];
1582
- case 16:
1788
+ case 15:
1583
1789
  _state.sent();
1584
- return [
1790
+ // If the loop caused a pause/cancel/webhook, stop
1791
+ if (this.stopped) return [
1585
1792
  2
1586
1793
  ];
1587
- case 17:
1588
- if (!(signal.type === 'PAUSE')) return [
1794
+ if (event.type === BRAIN_EVENTS.WEBHOOK) return [
1795
+ 2
1796
+ ];
1797
+ _state.label = 16;
1798
+ case 16:
1799
+ _iteratorAbruptCompletion = false;
1800
+ return [
1589
1801
  3,
1590
- 19
1802
+ 13
1591
1803
  ];
1804
+ case 17:
1592
1805
  return [
1593
- 4,
1594
- {
1595
- type: BRAIN_EVENTS.PAUSED,
1596
- status: STATUS.PAUSED,
1597
- brainTitle: this.title,
1598
- brainDescription: this.description,
1599
- brainRunId: this.brainRunId,
1600
- options: this.options
1601
- }
1806
+ 3,
1807
+ 24
1602
1808
  ];
1603
1809
  case 18:
1604
- _state.sent();
1810
+ err = _state.sent();
1811
+ _didIteratorError = true;
1812
+ _iteratorError = err;
1605
1813
  return [
1606
- 2
1814
+ 3,
1815
+ 24
1607
1816
  ];
1608
1817
  case 19:
1609
- if (!(signal.type === 'USER_MESSAGE')) return [
1818
+ _state.trys.push([
1819
+ 19,
1820
+ ,
1821
+ 22,
1822
+ 23
1823
+ ]);
1824
+ if (!(_iteratorAbruptCompletion && _iterator.return != null)) return [
1610
1825
  3,
1611
- 22
1826
+ 21
1612
1827
  ];
1613
- // Emit event for user message injection
1614
1828
  return [
1615
1829
  4,
1616
- {
1617
- type: BRAIN_EVENTS.AGENT_USER_MESSAGE,
1618
- stepTitle: step.block.title,
1619
- stepId: effectiveStepId,
1620
- content: signal.content,
1621
- options: this.options,
1622
- brainRunId: this.brainRunId
1623
- }
1830
+ _await_async_generator(_iterator.return())
1624
1831
  ];
1625
1832
  case 20:
1626
1833
  _state.sent();
1627
- // Inject as user message into conversation
1628
- userMessage2 = {
1629
- role: 'user',
1630
- content: signal.content
1631
- };
1632
- if (responseMessages) {
1633
- responseMessages = _to_consumable_array(responseMessages).concat([
1634
- userMessage2
1635
- ]);
1636
- } else {
1637
- initialMessages = _to_consumable_array(initialMessages).concat([
1638
- {
1639
- role: 'user',
1640
- content: signal.content
1641
- }
1642
- ]);
1643
- }
1644
- // Emit raw response message event so it shows up in agent chat view
1834
+ _state.label = 21;
1835
+ case 21:
1645
1836
  return [
1646
- 4,
1647
- {
1648
- type: BRAIN_EVENTS.AGENT_RAW_RESPONSE_MESSAGE,
1649
- stepTitle: step.block.title,
1650
- stepId: effectiveStepId,
1651
- iteration: iteration,
1652
- message: userMessage2,
1653
- options: (_this_options5 = this.options) !== null && _this_options5 !== void 0 ? _this_options5 : {},
1654
- brainRunId: this.brainRunId
1655
- }
1837
+ 3,
1838
+ 23
1656
1839
  ];
1657
- case 21:
1658
- _state.sent();
1659
- _state.label = 22;
1660
1840
  case 22:
1661
- _iteratorNormalCompletion = true;
1841
+ if (_didIteratorError) {
1842
+ throw _iteratorError;
1843
+ }
1662
1844
  return [
1663
- 3,
1664
- 15
1845
+ 7
1665
1846
  ];
1666
1847
  case 23:
1667
1848
  return [
1668
- 3,
1669
- 26
1849
+ 7
1670
1850
  ];
1671
1851
  case 24:
1672
- err = _state.sent();
1673
- _didIteratorError = true;
1674
- _iteratorError = err;
1675
1852
  return [
1676
- 3,
1677
- 26
1853
+ 5,
1854
+ _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState))))
1678
1855
  ];
1679
1856
  case 25:
1680
- try {
1681
- if (!_iteratorNormalCompletion && _iterator.return != null) {
1682
- _iterator.return();
1683
- }
1684
- } finally{
1685
- if (_didIteratorError) {
1686
- throw _iteratorError;
1687
- }
1688
- }
1689
- return [
1690
- 7
1691
- ];
1692
- case 26:
1693
- if (!(iteration > maxIterations)) return [
1694
- 3,
1695
- 28
1696
- ];
1697
- return [
1698
- 4,
1699
- {
1700
- type: BRAIN_EVENTS.AGENT_ITERATION_LIMIT,
1701
- stepTitle: step.block.title,
1702
- stepId: effectiveStepId,
1703
- iteration: iteration - 1,
1704
- maxIterations: maxIterations,
1705
- totalTokens: totalTokens,
1706
- options: (_this_options6 = this.options) !== null && _this_options6 !== void 0 ? _this_options6 : {},
1707
- brainRunId: this.brainRunId
1708
- }
1709
- ];
1710
- case 27:
1711
1857
  _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
- }
1715
1858
  return [
1716
1859
  2
1717
1860
  ];
1718
- case 28:
1719
- // Check if client supports generateText
1720
- if (!this.client.generateText) {
1721
- throw new Error('Client does not support generateText. Use a client that implements generateText for agent steps.');
1722
- }
1723
- // Build tools object for the client (description and inputSchema only)
1724
- toolsForClient = {};
1725
- _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
1861
+ }
1862
+ });
1863
+ }).call(this);
1864
+ }
1865
+ },
1866
+ {
1867
+ key: "runPromptLoop",
1868
+ value: /**
1869
+ * Shared prompt loop generator. Contains the core iteration logic:
1870
+ * resume handling, signal checks, LLM calls, tool processing, and event emission.
1871
+ *
1872
+ * Yields all PROMPT_* events. When the done tool or a terminal tool fires,
1873
+ * updates this.currentState, yields PROMPT_COMPLETE, and returns.
1874
+ * The caller is responsible for calling completeStep().
1875
+ *
1876
+ * When a webhook suspension occurs and allowWebhookSuspension is true,
1877
+ * yields PROMPT_WEBHOOK + WEBHOOK events and returns. If false, throws.
1878
+ */ function runPromptLoop(params) {
1879
+ return _wrap_async_generator(function() {
1880
+ var step, prompt, system, client, outputSchema, loopConfig, allowWebhookSuspension, resume, userTools, _loopConfig_maxIterations, maxIterations, maxTokens, _loopConfig_toolChoice, toolChoice, toolDefs, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, _step_value, name, tool, componentList, resumeCtx, _resumeCtx_stepId, stepId, stepTitle, initialMessages, responseMessages, totalTokens, iteration, webhookResponse, toolResultMsg, _this_options, _this_options1, _this_options2, signals, _iteratorNormalCompletion1, _didIteratorError1, _iteratorError1, _iterator1, _step1, signal, _this_options3, _this_options4, err, llmResult, tokensThisIteration, _this_options5, _this_options6, _this_options7, _this_options8, pendingWebhook, _iteratorNormalCompletion2, _didIteratorError2, _iteratorError2, _iterator2, _step2, toolCall, toolCallId, toolName, args, _this_options9, parsed, errorMsg, toolResultMsg1, _this_options10, _this_options11, _this_options12, tool1, _this_options13, _this_options14, toolResult, _this_options15, placeholderMsg, toolResultMsg2, _this_options16, err, toolWaitFor, webhooks, serializedWaitFor, _this_options17, _this_options18;
1881
+ return _ts_generator(this, function(_state) {
1882
+ switch(_state.label){
1883
+ case 0:
1884
+ step = params.step, prompt = params.prompt, system = params.system, client = params.client, outputSchema = params.outputSchema, loopConfig = params.loopConfig, allowWebhookSuspension = params.allowWebhookSuspension, resume = params.resume;
1885
+ userTools = loopConfig.tools, _loopConfig_maxIterations = loopConfig.maxIterations, maxIterations = _loopConfig_maxIterations === void 0 ? 100 : _loopConfig_maxIterations, maxTokens = loopConfig.maxTokens, _loopConfig_toolChoice = loopConfig.toolChoice, toolChoice = _loopConfig_toolChoice === void 0 ? 'required' : _loopConfig_toolChoice;
1886
+ // Build tool definitions for the LLM (description + inputSchema only)
1887
+ toolDefs = {};
1888
+ _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1726
1889
  try {
1727
- for(_iterator1 = Object.entries(mergedTools)[Symbol.iterator](); !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){
1728
- _step_value = _sliced_to_array(_step1.value, 2), name1 = _step_value[0], toolDef = _step_value[1];
1729
- tool = toolDef;
1730
- description = tool.description;
1731
- // Enrich generateUI description with available component information
1732
- if (name1 === 'generateUI' && components && Object.keys(components).length > 0) {
1733
- componentList = Object.entries(components).map(function(param) {
1734
- var _param = _sliced_to_array(param, 2), compName = _param[0], comp = _param[1];
1735
- var desc = comp.description.split('\n')[0]; // First line only
1736
- return "- ".concat(compName, ": ").concat(desc);
1737
- }).join('\n');
1738
- description = "Generate a web page for displaying rich content or collecting user input.\n\nSometimes you need more than simple notifications to communicate with users. This tool creates web pages that can display formatted content, dashboards, or forms to collect information.\n\nAVAILABLE COMPONENTS:\n".concat(componentList, "\n\nRETURNS: { url: string, webhook: { slug: string, identifier: string, token: string } | null }\n- url: The page URL\n- webhook: For forms (hasForm=true), contains slug, identifier, and token that must all be passed to waitForWebhook to pause execution until the user submits the form\n\nIMPORTANT: Users have no way to discover the page URL on their own. After generating a page, you must tell them the URL using whatever communication tools are available.");
1739
- }
1740
- toolsForClient[name1] = {
1741
- description: description,
1890
+ for(_iterator = Object.entries(userTools)[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1891
+ _step_value = _sliced_to_array(_step.value, 2), name = _step_value[0], tool = _step_value[1];
1892
+ toolDefs[name] = {
1893
+ description: tool.description,
1742
1894
  inputSchema: tool.inputSchema
1743
1895
  };
1744
1896
  }
1745
1897
  } catch (err) {
1746
- _didIteratorError1 = true;
1747
- _iteratorError1 = err;
1898
+ _didIteratorError = true;
1899
+ _iteratorError = err;
1748
1900
  } finally{
1749
1901
  try {
1750
- if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
1751
- _iterator1.return();
1902
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
1903
+ _iterator.return();
1752
1904
  }
1753
1905
  } finally{
1754
- if (_didIteratorError1) {
1755
- throw _iteratorError1;
1906
+ if (_didIteratorError) {
1907
+ throw _iteratorError;
1756
1908
  }
1757
1909
  }
1758
1910
  }
1759
- // Prepend default system prompt to user's system prompt
1760
- systemPrompt = config.system ? "".concat(DEFAULT_AGENT_SYSTEM_PROMPT, "\n\n").concat(config.system) : DEFAULT_AGENT_SYSTEM_PROMPT;
1761
- return [
1762
- 4,
1763
- _await_async_generator(this.client.generateText({
1764
- system: systemPrompt,
1765
- messages: initialMessages,
1766
- responseMessages: responseMessages,
1767
- tools: toolsForClient,
1768
- toolChoice: config.toolChoice
1769
- }))
1911
+ // Enrich generatePage description with available components so the outer
1912
+ // LLM (which reads tool descriptions to decide how to call them) knows what
1913
+ // UI components exist. This only matters in the prompt loop — it's the only
1914
+ // path where an LLM reads tool descriptions. Direct tool.execute() calls
1915
+ // (e.g., from a regular step) don't need this because they don't go through
1916
+ // LLM tool selection.
1917
+ if (toolDefs['generatePage'] && this.components) {
1918
+ componentList = Object.entries(this.components).map(function(param) {
1919
+ var _param = _sliced_to_array(param, 2), name = _param[0], comp = _param[1];
1920
+ return "- ".concat(name, ": ").concat(comp.description.split('\n')[0]);
1921
+ }).join('\n');
1922
+ toolDefs['generatePage'] = _object_spread_props(_object_spread({}, toolDefs['generatePage']), {
1923
+ description: toolDefs['generatePage'].description + "\n\nAvailable UI Components:\n".concat(componentList) + "\n\nIMPORTANT: When generating a page with a form (hasForm=true), the page generator" + " automatically creates a Form component. You do NOT need to include Form in your prompt." + " Just describe the form fields you need and the page generator handles the rest."
1924
+ });
1925
+ }
1926
+ // Auto-generate 'done' tool from outputSchema
1927
+ toolDefs['done'] = {
1928
+ description: "Signal that the task is complete and provide the final result.\n\nThis is a TERMINAL tool - calling it immediately ends execution.\nNo further tools will execute after this. No further iterations will occur.\nThe input you provide becomes the final output.\n\nCall this when you have completed the assigned task and have the final answer ready.\nDo NOT call if you still need to gather more information.\n\nThe output must conform to the provided schema.",
1929
+ inputSchema: outputSchema
1930
+ };
1931
+ if (!client.generateText) {
1932
+ throw new Error('Client does not support generateText, required for prompt loop in step "'.concat(step.block.title, '"'));
1933
+ }
1934
+ if (!client.createToolResultMessage) {
1935
+ throw new Error('Client does not support createToolResultMessage, required for prompt loop in step "'.concat(step.block.title, '"'));
1936
+ }
1937
+ resumeCtx = resume === null || resume === void 0 ? void 0 : resume.promptLoopContext;
1938
+ // Preserve stepId across resumes so all events correlate
1939
+ stepId = (_resumeCtx_stepId = resumeCtx === null || resumeCtx === void 0 ? void 0 : resumeCtx.stepId) !== null && _resumeCtx_stepId !== void 0 ? _resumeCtx_stepId : step.id;
1940
+ stepTitle = step.block.title;
1941
+ // Conversation state — restored from resume context or fresh
1942
+ initialMessages = [
1943
+ {
1944
+ role: 'user',
1945
+ content: prompt
1946
+ }
1770
1947
  ];
1771
- case 29:
1772
- response = _state.sent();
1773
- // Update responseMessages for next iteration (preserves providerOptions)
1774
- responseMessages = response.responseMessages;
1775
- // Get the new assistant message (the last one added by generateText)
1776
- newAssistantMessage = (_response_responseMessages = response.responseMessages) === null || _response_responseMessages === void 0 ? void 0 : _response_responseMessages.at(-1);
1777
- if (!newAssistantMessage) return [
1948
+ totalTokens = 0;
1949
+ iteration = 0;
1950
+ if (!resumeCtx) return [
1778
1951
  3,
1779
- 31
1952
+ 3
1953
+ ];
1954
+ // Resuming a paused/waiting prompt loop
1955
+ iteration = resumeCtx.iteration;
1956
+ totalTokens = resumeCtx.totalTokens;
1957
+ responseMessages = resumeCtx.responseMessages;
1958
+ // If resuming from webhook, inject the response as a tool result
1959
+ webhookResponse = resume === null || resume === void 0 ? void 0 : resume.webhookResponse;
1960
+ if (!(webhookResponse && resumeCtx.pendingToolCallId && resumeCtx.pendingToolName)) return [
1961
+ 3,
1962
+ 2
1780
1963
  ];
1964
+ toolResultMsg = client.createToolResultMessage(resumeCtx.pendingToolCallId, resumeCtx.pendingToolName, webhookResponse);
1965
+ responseMessages = _to_consumable_array(responseMessages).concat([
1966
+ toolResultMsg
1967
+ ]);
1781
1968
  return [
1782
1969
  4,
1783
1970
  {
1784
- type: BRAIN_EVENTS.AGENT_RAW_RESPONSE_MESSAGE,
1785
- stepTitle: step.block.title,
1786
- stepId: effectiveStepId,
1971
+ type: BRAIN_EVENTS.PROMPT_TOOL_RESULT,
1972
+ stepTitle: stepTitle,
1973
+ stepId: stepId,
1974
+ toolName: resumeCtx.pendingToolName,
1975
+ toolCallId: resumeCtx.pendingToolCallId,
1976
+ result: webhookResponse,
1787
1977
  iteration: iteration,
1788
- message: newAssistantMessage,
1789
- options: (_this_options7 = this.options) !== null && _this_options7 !== void 0 ? _this_options7 : {},
1978
+ options: (_this_options = this.options) !== null && _this_options !== void 0 ? _this_options : {},
1790
1979
  brainRunId: this.brainRunId
1791
1980
  }
1792
1981
  ];
1793
- case 30:
1982
+ case 1:
1794
1983
  _state.sent();
1795
- _state.label = 31;
1796
- case 31:
1797
- // Track tokens
1798
- tokensThisIteration = response.usage.totalTokens;
1799
- totalTokens += tokensThisIteration;
1800
- // Emit iteration event (after LLM call so we have token info)
1984
+ _state.label = 2;
1985
+ case 2:
1986
+ // Safe to clear: only the block that caused the pause reads this.resume,
1987
+ // and the main loop already processed webhookResponse/resumed before here
1988
+ this.resume = undefined;
1989
+ return [
1990
+ 3,
1991
+ 5
1992
+ ];
1993
+ case 3:
1994
+ // Fresh start — emit PROMPT_START
1801
1995
  return [
1802
1996
  4,
1803
1997
  {
1804
- type: BRAIN_EVENTS.AGENT_ITERATION,
1805
- stepTitle: step.block.title,
1806
- stepId: effectiveStepId,
1807
- iteration: iteration,
1808
- tokensThisIteration: tokensThisIteration,
1809
- totalTokens: totalTokens,
1810
- options: (_this_options8 = this.options) !== null && _this_options8 !== void 0 ? _this_options8 : {},
1998
+ type: BRAIN_EVENTS.PROMPT_START,
1999
+ stepTitle: stepTitle,
2000
+ stepId: stepId,
2001
+ prompt: prompt,
2002
+ system: system,
2003
+ tools: Object.keys(toolDefs),
2004
+ options: (_this_options1 = this.options) !== null && _this_options1 !== void 0 ? _this_options1 : {},
1811
2005
  brainRunId: this.brainRunId
1812
2006
  }
1813
2007
  ];
1814
- case 32:
2008
+ case 4:
1815
2009
  _state.sent();
1816
- if (!(config.maxTokens && totalTokens > config.maxTokens)) return [
2010
+ _state.label = 5;
2011
+ case 5:
2012
+ if (!true) return [
1817
2013
  3,
1818
- 34
2014
+ 51
2015
+ ];
2016
+ iteration++;
2017
+ if (!(iteration > maxIterations)) return [
2018
+ 3,
2019
+ 7
1819
2020
  ];
1820
2021
  return [
1821
2022
  4,
1822
2023
  {
1823
- type: BRAIN_EVENTS.AGENT_TOKEN_LIMIT,
1824
- stepTitle: step.block.title,
1825
- stepId: effectiveStepId,
1826
- totalTokens: totalTokens,
1827
- maxTokens: config.maxTokens,
1828
- options: (_this_options9 = this.options) !== null && _this_options9 !== void 0 ? _this_options9 : {},
2024
+ type: BRAIN_EVENTS.PROMPT_ITERATION_LIMIT,
2025
+ stepTitle: stepTitle,
2026
+ stepId: stepId,
2027
+ totalIterations: iteration - 1,
2028
+ maxIterations: maxIterations,
2029
+ options: (_this_options2 = this.options) !== null && _this_options2 !== void 0 ? _this_options2 : {},
1829
2030
  brainRunId: this.brainRunId
1830
2031
  }
1831
2032
  ];
1832
- case 33:
2033
+ case 6:
1833
2034
  _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
- }
1837
- return [
1838
- 2
1839
- ];
1840
- case 34:
1841
- if (!response.text) return [
2035
+ throw new Error("Iteration limit (".concat(maxIterations, ') reached in prompt loop "').concat(stepTitle, '"'));
2036
+ case 7:
2037
+ if (!this.signalProvider) return [
1842
2038
  3,
1843
- 36
2039
+ 18
1844
2040
  ];
1845
- // Log assistant messages to console as fallback (users shouldn't rely on this)
1846
- console.log("[Assistant] ".concat(response.text));
1847
2041
  return [
1848
2042
  4,
1849
- {
1850
- type: BRAIN_EVENTS.AGENT_ASSISTANT_MESSAGE,
1851
- stepTitle: step.block.title,
1852
- stepId: effectiveStepId,
1853
- content: response.text,
1854
- options: (_this_options10 = this.options) !== null && _this_options10 !== void 0 ? _this_options10 : {},
1855
- brainRunId: this.brainRunId
1856
- }
2043
+ _await_async_generator(this.signalProvider.getSignals('CONTROL'))
1857
2044
  ];
1858
- case 35:
1859
- _state.sent();
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
- }
1868
- // Track pending webhook if any tool returns waitFor
1869
- // We process ALL tool calls first, then pause for webhook at the end
1870
- pendingWebhook = null;
1871
- _iteratorNormalCompletion2 = true, _didIteratorError2 = false, _iteratorError2 = undefined;
1872
- _state.label = 37;
1873
- case 37:
2045
+ case 8:
2046
+ signals = _state.sent();
2047
+ _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
2048
+ _state.label = 9;
2049
+ case 9:
1874
2050
  _state.trys.push([
1875
- 37,
1876
- 49,
1877
- 50,
1878
- 51
2051
+ 9,
2052
+ 16,
2053
+ 17,
2054
+ 18
1879
2055
  ]);
1880
- _iterator2 = response.toolCalls[Symbol.iterator]();
1881
- _state.label = 38;
1882
- case 38:
1883
- if (!!(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done)) return [
2056
+ _iterator1 = signals[Symbol.iterator]();
2057
+ _state.label = 10;
2058
+ case 10:
2059
+ if (!!(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done)) return [
1884
2060
  3,
1885
- 48
2061
+ 15
1886
2062
  ];
1887
- toolCall = _step2.value;
2063
+ signal = _step1.value;
2064
+ if (!(signal.type === 'KILL')) return [
2065
+ 3,
2066
+ 12
2067
+ ];
2068
+ this.stopped = true;
1888
2069
  return [
1889
2070
  4,
1890
2071
  {
1891
- type: BRAIN_EVENTS.AGENT_TOOL_CALL,
1892
- stepTitle: step.block.title,
1893
- stepId: effectiveStepId,
1894
- toolName: toolCall.toolName,
1895
- toolCallId: toolCall.toolCallId,
1896
- input: toolCall.args,
1897
- options: (_this_options11 = this.options) !== null && _this_options11 !== void 0 ? _this_options11 : {},
1898
- brainRunId: this.brainRunId
2072
+ type: BRAIN_EVENTS.CANCELLED,
2073
+ status: STATUS.CANCELLED,
2074
+ brainTitle: this.title,
2075
+ brainDescription: this.description,
2076
+ brainRunId: this.brainRunId,
2077
+ options: (_this_options3 = this.options) !== null && _this_options3 !== void 0 ? _this_options3 : {}
1899
2078
  }
1900
2079
  ];
1901
- case 39:
2080
+ case 11:
1902
2081
  _state.sent();
1903
- tool1 = mergedTools[toolCall.toolName];
1904
- if (!tool1) {
1905
- throw new Error("Unknown tool: ".concat(toolCall.toolName));
1906
- }
1907
- if (!tool1.terminal) return [
2082
+ return [
2083
+ 2
2084
+ ];
2085
+ case 12:
2086
+ if (!(signal.type === 'PAUSE')) return [
1908
2087
  3,
1909
- 41
2088
+ 14
1910
2089
  ];
2090
+ this.stopped = true;
1911
2091
  return [
1912
2092
  4,
1913
2093
  {
1914
- type: BRAIN_EVENTS.AGENT_COMPLETE,
1915
- stepTitle: step.block.title,
1916
- stepId: effectiveStepId,
1917
- terminalToolName: toolCall.toolName,
1918
- result: toolCall.args,
1919
- totalIterations: iteration,
1920
- totalTokens: totalTokens,
1921
- options: (_this_options12 = this.options) !== null && _this_options12 !== void 0 ? _this_options12 : {},
1922
- brainRunId: this.brainRunId
2094
+ type: BRAIN_EVENTS.PAUSED,
2095
+ status: STATUS.PAUSED,
2096
+ brainTitle: this.title,
2097
+ brainDescription: this.description,
2098
+ brainRunId: this.brainRunId,
2099
+ options: (_this_options4 = this.options) !== null && _this_options4 !== void 0 ? _this_options4 : {}
1923
2100
  }
1924
2101
  ];
1925
- case 40:
2102
+ case 13:
1926
2103
  _state.sent();
1927
- // Merge terminal result into state
1928
- // Only namespace under outputSchema.name when 'done' tool is called with outputSchema
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
- }
1934
- // Namespace result under outputSchema.name
1935
- this.currentState = _object_spread_props(_object_spread({}, this.currentState), _define_property({}, config.outputSchema.name, parsed.data));
1936
- } else {
1937
- // Default behavior: spread into state root (for other terminal tools)
1938
- this.currentState = _object_spread({}, this.currentState, toolCall.args);
1939
- }
1940
2104
  return [
1941
2105
  2
1942
2106
  ];
1943
- case 41:
1944
- if (!tool1.execute) return [
2107
+ case 14:
2108
+ _iteratorNormalCompletion1 = true;
2109
+ return [
1945
2110
  3,
1946
- 47
2111
+ 10
1947
2112
  ];
1948
- toolContext = {
1949
- state: this.currentState,
1950
- options: (_this_options13 = this.options) !== null && _this_options13 !== void 0 ? _this_options13 : {},
1951
- client: this.client,
1952
- resources: this.resources,
1953
- response: this.currentResponse,
1954
- page: this.currentPage,
1955
- pages: this.pages,
1956
- env: this.env,
1957
- components: this.components,
1958
- brainRunId: this.brainRunId,
1959
- stepId: effectiveStepId,
1960
- memory: this.scopedMemory,
1961
- store: this.store,
1962
- currentUser: this.currentUser
1963
- };
2113
+ case 15:
1964
2114
  return [
1965
- 4,
1966
- _await_async_generator(tool1.execute(toolCall.args, toolContext))
1967
- ];
1968
- case 42:
1969
- toolResult = _state.sent();
1970
- if (!(toolResult && (typeof toolResult === "undefined" ? "undefined" : _type_of(toolResult)) === 'object' && 'waitFor' in toolResult)) return [
1971
2115
  3,
1972
- 44
1973
- ];
1974
- waitForResult = toolResult;
1975
- // Normalize waitFor to array (supports single or multiple webhooks)
1976
- webhooks = Array.isArray(waitForResult.waitFor) ? waitForResult.waitFor : [
1977
- waitForResult.waitFor
2116
+ 18
1978
2117
  ];
1979
- // Store webhook info - we'll emit the events after processing all tool calls
1980
- // This ensures all other tool results are processed before pausing
1981
- pendingWebhook = {
1982
- toolCallId: toolCall.toolCallId,
1983
- toolName: toolCall.toolName,
1984
- input: toolCall.args,
1985
- webhooks: webhooks.map(function(w) {
1986
- return {
1987
- slug: w.slug,
1988
- identifier: w.identifier,
1989
- token: w.token
1990
- };
1991
- }),
1992
- timeout: waitForResult.timeout
1993
- };
1994
- // Emit tool result event for debugging/visibility (with pending status)
2118
+ case 16:
2119
+ err = _state.sent();
2120
+ _didIteratorError1 = true;
2121
+ _iteratorError1 = err;
1995
2122
  return [
1996
- 4,
1997
- {
1998
- type: BRAIN_EVENTS.AGENT_TOOL_RESULT,
1999
- stepTitle: step.block.title,
2000
- stepId: effectiveStepId,
2001
- toolName: toolCall.toolName,
2002
- toolCallId: toolCall.toolCallId,
2003
- result: {
2004
- status: 'waiting_for_webhook',
2005
- webhooks: pendingWebhook.webhooks
2006
- },
2007
- options: (_this_options14 = this.options) !== null && _this_options14 !== void 0 ? _this_options14 : {},
2123
+ 3,
2124
+ 18
2125
+ ];
2126
+ case 17:
2127
+ try {
2128
+ if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
2129
+ _iterator1.return();
2130
+ }
2131
+ } finally{
2132
+ if (_didIteratorError1) {
2133
+ throw _iteratorError1;
2134
+ }
2135
+ }
2136
+ return [
2137
+ 7
2138
+ ];
2139
+ case 18:
2140
+ return [
2141
+ 4,
2142
+ _await_async_generator(client.generateText({
2143
+ system: system,
2144
+ messages: iteration === 1 ? initialMessages : [],
2145
+ responseMessages: responseMessages,
2146
+ tools: toolDefs,
2147
+ toolChoice: toolChoice
2148
+ }))
2149
+ ];
2150
+ case 19:
2151
+ llmResult = _state.sent();
2152
+ tokensThisIteration = llmResult.usage.totalTokens;
2153
+ totalTokens += tokensThisIteration;
2154
+ responseMessages = llmResult.responseMessages;
2155
+ // Emit raw response message for replay
2156
+ return [
2157
+ 4,
2158
+ {
2159
+ type: BRAIN_EVENTS.PROMPT_RAW_RESPONSE_MESSAGE,
2160
+ stepTitle: stepTitle,
2161
+ stepId: stepId,
2162
+ iteration: iteration,
2163
+ message: llmResult.responseMessages,
2164
+ options: (_this_options5 = this.options) !== null && _this_options5 !== void 0 ? _this_options5 : {},
2008
2165
  brainRunId: this.brainRunId
2009
2166
  }
2010
2167
  ];
2011
- case 43:
2168
+ case 20:
2012
2169
  _state.sent();
2013
- // Add placeholder to responseMessages locally so the conversation stays valid
2014
- // for any subsequent generateText calls in this execution.
2015
- // We DON'T emit an event for it - on resume, we reconstruct from events
2016
- // and append the real webhook response.
2017
- if (this.client.createToolResultMessage && responseMessages) {
2018
- placeholderMessage = this.client.createToolResultMessage(toolCall.toolCallId, toolCall.toolName, {
2019
- status: 'waiting_for_webhook',
2020
- webhooks: pendingWebhook.webhooks
2021
- });
2022
- responseMessages = _to_consumable_array(responseMessages).concat([
2023
- placeholderMessage
2024
- ]);
2025
- }
2026
- // Continue processing other tool calls - don't return yet
2170
+ // Emit iteration event
2027
2171
  return [
2172
+ 4,
2173
+ {
2174
+ type: BRAIN_EVENTS.PROMPT_ITERATION,
2175
+ stepTitle: stepTitle,
2176
+ stepId: stepId,
2177
+ iteration: iteration,
2178
+ tokensThisIteration: tokensThisIteration,
2179
+ totalTokens: totalTokens,
2180
+ options: (_this_options6 = this.options) !== null && _this_options6 !== void 0 ? _this_options6 : {},
2181
+ brainRunId: this.brainRunId
2182
+ }
2183
+ ];
2184
+ case 21:
2185
+ _state.sent();
2186
+ if (!(maxTokens && totalTokens >= maxTokens)) return [
2028
2187
  3,
2029
- 47
2188
+ 23
2030
2189
  ];
2031
- case 44:
2032
- // Emit tool result event for debugging/visibility
2033
2190
  return [
2034
2191
  4,
2035
2192
  {
2036
- type: BRAIN_EVENTS.AGENT_TOOL_RESULT,
2037
- stepTitle: step.block.title,
2038
- stepId: effectiveStepId,
2039
- toolName: toolCall.toolName,
2040
- toolCallId: toolCall.toolCallId,
2041
- result: toolResult,
2042
- options: (_this_options15 = this.options) !== null && _this_options15 !== void 0 ? _this_options15 : {},
2193
+ type: BRAIN_EVENTS.PROMPT_TOKEN_LIMIT,
2194
+ stepTitle: stepTitle,
2195
+ stepId: stepId,
2196
+ totalTokens: totalTokens,
2197
+ maxTokens: maxTokens,
2198
+ options: (_this_options7 = this.options) !== null && _this_options7 !== void 0 ? _this_options7 : {},
2043
2199
  brainRunId: this.brainRunId
2044
2200
  }
2045
2201
  ];
2046
- case 45:
2202
+ case 22:
2047
2203
  _state.sent();
2048
- if (!(this.client.createToolResultMessage && responseMessages)) return [
2204
+ throw new Error("Token limit (".concat(maxTokens, ') reached in prompt loop "').concat(stepTitle, '"'));
2205
+ case 23:
2206
+ if (!llmResult.text) return [
2049
2207
  3,
2050
- 47
2208
+ 25
2051
2209
  ];
2052
- toolResultMessage1 = this.client.createToolResultMessage(toolCall.toolCallId, toolCall.toolName, toolResult);
2053
- responseMessages = _to_consumable_array(responseMessages).concat([
2054
- toolResultMessage1
2055
- ]);
2056
- // Emit event for this tool result message
2057
2210
  return [
2058
2211
  4,
2059
2212
  {
2060
- type: BRAIN_EVENTS.AGENT_RAW_RESPONSE_MESSAGE,
2061
- stepTitle: step.block.title,
2062
- stepId: effectiveStepId,
2213
+ type: BRAIN_EVENTS.PROMPT_ASSISTANT_MESSAGE,
2214
+ stepTitle: stepTitle,
2215
+ stepId: stepId,
2216
+ text: llmResult.text,
2063
2217
  iteration: iteration,
2064
- message: toolResultMessage1,
2065
- options: (_this_options16 = this.options) !== null && _this_options16 !== void 0 ? _this_options16 : {},
2218
+ options: (_this_options8 = this.options) !== null && _this_options8 !== void 0 ? _this_options8 : {},
2066
2219
  brainRunId: this.brainRunId
2067
2220
  }
2068
2221
  ];
2069
- case 46:
2222
+ case 24:
2070
2223
  _state.sent();
2071
- _state.label = 47;
2072
- case 47:
2073
- _iteratorNormalCompletion2 = true;
2074
- return [
2224
+ _state.label = 25;
2225
+ case 25:
2226
+ // Check tool calls
2227
+ if (!llmResult.toolCalls || llmResult.toolCalls.length === 0) {
2228
+ if (toolChoice === 'required') {
2229
+ throw new Error("LLM did not call any tools with toolChoice 'required' in step \"".concat(stepTitle, '"'));
2230
+ }
2231
+ return [
2232
+ 3,
2233
+ 5
2234
+ ];
2235
+ }
2236
+ // Process tool calls sequentially
2237
+ pendingWebhook = null;
2238
+ _iteratorNormalCompletion2 = true, _didIteratorError2 = false, _iteratorError2 = undefined;
2239
+ _state.label = 26;
2240
+ case 26:
2241
+ _state.trys.push([
2242
+ 26,
2243
+ 45,
2244
+ 46,
2245
+ 47
2246
+ ]);
2247
+ _iterator2 = llmResult.toolCalls[Symbol.iterator]();
2248
+ _state.label = 27;
2249
+ case 27:
2250
+ if (!!(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done)) return [
2075
2251
  3,
2076
- 38
2252
+ 44
2077
2253
  ];
2078
- case 48:
2254
+ toolCall = _step2.value;
2255
+ toolCallId = toolCall.toolCallId, toolName = toolCall.toolName, args = toolCall.args;
2256
+ // Emit tool call event
2079
2257
  return [
2258
+ 4,
2259
+ {
2260
+ type: BRAIN_EVENTS.PROMPT_TOOL_CALL,
2261
+ stepTitle: stepTitle,
2262
+ stepId: stepId,
2263
+ toolName: toolName,
2264
+ toolCallId: toolCallId,
2265
+ input: args,
2266
+ iteration: iteration,
2267
+ options: (_this_options9 = this.options) !== null && _this_options9 !== void 0 ? _this_options9 : {},
2268
+ brainRunId: this.brainRunId
2269
+ }
2270
+ ];
2271
+ case 28:
2272
+ _state.sent();
2273
+ if (!(toolName === 'done')) return [
2080
2274
  3,
2081
- 51
2275
+ 33
2082
2276
  ];
2083
- case 49:
2084
- err = _state.sent();
2085
- _didIteratorError2 = true;
2086
- _iteratorError2 = err;
2087
- return [
2277
+ parsed = outputSchema.safeParse(args);
2278
+ if (!!parsed.success) return [
2088
2279
  3,
2089
- 51
2280
+ 30
2090
2281
  ];
2091
- case 50:
2092
- try {
2093
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
2094
- _iterator2.return();
2095
- }
2096
- } finally{
2097
- if (_didIteratorError2) {
2098
- throw _iteratorError2;
2099
- }
2100
- }
2282
+ // Feed validation error back to LLM so it can retry
2283
+ errorMsg = "Invalid output: ".concat(parsed.error.message, ". Please fix and try again.");
2284
+ toolResultMsg1 = client.createToolResultMessage(toolCallId, 'done', errorMsg);
2285
+ responseMessages = _to_consumable_array(responseMessages !== null && responseMessages !== void 0 ? responseMessages : []).concat([
2286
+ toolResultMsg1
2287
+ ]);
2101
2288
  return [
2102
- 7
2289
+ 4,
2290
+ {
2291
+ type: BRAIN_EVENTS.PROMPT_TOOL_RESULT,
2292
+ stepTitle: stepTitle,
2293
+ stepId: stepId,
2294
+ toolName: 'done',
2295
+ toolCallId: toolCallId,
2296
+ result: errorMsg,
2297
+ iteration: iteration,
2298
+ options: (_this_options10 = this.options) !== null && _this_options10 !== void 0 ? _this_options10 : {},
2299
+ brainRunId: this.brainRunId
2300
+ }
2103
2301
  ];
2104
- case 51:
2105
- if (!pendingWebhook) return [
2302
+ case 29:
2303
+ _state.sent();
2304
+ return [
2106
2305
  3,
2107
- 54
2108
- ];
2109
- // Emit AGENT_WEBHOOK event
2306
+ 44
2307
+ ]; // Break to next iteration so LLM can retry
2308
+ case 30:
2309
+ // Valid output — merge onto state and complete
2310
+ this.currentState = _object_spread({}, this.currentState, parsed.data);
2110
2311
  return [
2111
2312
  4,
2112
2313
  {
2113
- type: BRAIN_EVENTS.AGENT_WEBHOOK,
2114
- stepTitle: step.block.title,
2115
- stepId: effectiveStepId,
2116
- toolCallId: pendingWebhook.toolCallId,
2117
- toolName: pendingWebhook.toolName,
2118
- input: pendingWebhook.input,
2119
- options: (_this_options17 = this.options) !== null && _this_options17 !== void 0 ? _this_options17 : {},
2314
+ type: BRAIN_EVENTS.PROMPT_TOOL_RESULT,
2315
+ stepTitle: stepTitle,
2316
+ stepId: stepId,
2317
+ toolName: 'done',
2318
+ toolCallId: toolCallId,
2319
+ result: parsed.data,
2320
+ iteration: iteration,
2321
+ options: (_this_options11 = this.options) !== null && _this_options11 !== void 0 ? _this_options11 : {},
2120
2322
  brainRunId: this.brainRunId
2121
2323
  }
2122
2324
  ];
2123
- case 52:
2325
+ case 31:
2124
2326
  _state.sent();
2125
- // Emit WEBHOOK event with all webhooks (first response wins)
2126
2327
  return [
2127
2328
  4,
2128
- _object_spread_props(_object_spread({
2129
- type: BRAIN_EVENTS.WEBHOOK,
2130
- waitFor: pendingWebhook.webhooks
2131
- }, pendingWebhook.timeout !== undefined && {
2132
- timeout: pendingWebhook.timeout
2133
- }), {
2134
- options: (_this_options18 = this.options) !== null && _this_options18 !== void 0 ? _this_options18 : {},
2329
+ {
2330
+ type: BRAIN_EVENTS.PROMPT_COMPLETE,
2331
+ stepTitle: stepTitle,
2332
+ stepId: stepId,
2333
+ result: parsed.data,
2334
+ terminalTool: 'done',
2335
+ totalIterations: iteration,
2336
+ totalTokens: totalTokens,
2337
+ options: (_this_options12 = this.options) !== null && _this_options12 !== void 0 ? _this_options12 : {},
2135
2338
  brainRunId: this.brainRunId
2136
- })
2339
+ }
2137
2340
  ];
2138
- case 53:
2341
+ case 32:
2139
2342
  _state.sent();
2140
2343
  return [
2141
2344
  2
2142
2345
  ];
2143
- case 54:
2144
- return [
2346
+ case 33:
2347
+ // Handle user-defined tools
2348
+ tool1 = userTools[toolName];
2349
+ if (!tool1) {
2350
+ throw new Error('Unknown tool "'.concat(toolName, '" called in step "').concat(stepTitle, '"'));
2351
+ }
2352
+ if (!tool1.terminal) return [
2145
2353
  3,
2146
- 12
2354
+ 36
2147
2355
  ];
2148
- case 55:
2356
+ this.currentState = _object_spread({}, this.currentState, args);
2149
2357
  return [
2150
- 2
2358
+ 4,
2359
+ {
2360
+ type: BRAIN_EVENTS.PROMPT_TOOL_RESULT,
2361
+ stepTitle: stepTitle,
2362
+ stepId: stepId,
2363
+ toolName: toolName,
2364
+ toolCallId: toolCallId,
2365
+ result: args,
2366
+ iteration: iteration,
2367
+ options: (_this_options13 = this.options) !== null && _this_options13 !== void 0 ? _this_options13 : {},
2368
+ brainRunId: this.brainRunId
2369
+ }
2151
2370
  ];
2152
- }
2153
- });
2154
- }).call(this);
2155
- }
2156
- },
2157
- {
2158
- key: "executeIteratePrompt",
2159
- value: /**
2160
- * Execute an iterate prompt step, yielding one ITERATE_ITEM_COMPLETE
2161
- * event per item. Between items, checks for PAUSE/KILL signals so
2162
- * Cloudflare backends can restart the DO to reclaim memory.
2163
- */ function executeIteratePrompt(step) {
2164
- return _wrap_async_generator(function() {
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, promptText, response, error, fallback, _this_options1, finalResults;
2166
- return _ts_generator(this, function(_state) {
2167
- switch(_state.label){
2168
- case 0:
2169
- block = step.block;
2170
- iterateConfig = block.iterateConfig;
2171
- prevState = this.currentState;
2172
- rawClient = iterateConfig.client;
2173
- client = rawClient ? this.governor ? this.governor(rawClient) : rawClient : this.client;
2371
+ case 34:
2372
+ _state.sent();
2174
2373
  return [
2175
2374
  4,
2176
- _await_async_generator(iterateConfig.over(this.buildStepContext(step)))
2177
- ];
2178
- case 1:
2179
- items = _state.sent();
2180
- totalItems = items.length;
2181
- // Resume support: pick up from where we left off
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);
2375
+ {
2376
+ type: BRAIN_EVENTS.PROMPT_COMPLETE,
2377
+ stepTitle: stepTitle,
2378
+ stepId: stepId,
2379
+ result: args,
2380
+ terminalTool: toolName,
2381
+ totalIterations: iteration,
2382
+ totalTokens: totalTokens,
2383
+ options: (_this_options14 = this.options) !== null && _this_options14 !== void 0 ? _this_options14 : {},
2384
+ brainRunId: this.brainRunId
2190
2385
  }
2191
- }
2192
- // Clear resumeContext after consuming iterateProgress
2193
- if (iterateProgress) {
2194
- this.resumeContext = undefined;
2195
- }
2196
- i = startIndex;
2197
- _state.label = 2;
2198
- case 2:
2199
- if (!(i < totalItems)) return [
2200
- 3,
2201
- 20
2202
2386
  ];
2203
- if (!this.signalProvider) return [
2387
+ case 35:
2388
+ _state.sent();
2389
+ return [
2390
+ 2
2391
+ ];
2392
+ case 36:
2393
+ // Execute non-terminal tool
2394
+ toolResult = void 0;
2395
+ if (!tool1.execute) return [
2204
2396
  3,
2205
- 12
2397
+ 40
2206
2398
  ];
2207
2399
  return [
2208
2400
  4,
2209
- _await_async_generator(this.signalProvider.getSignals('CONTROL'))
2401
+ _await_async_generator(tool1.execute(args, this.buildStepContext(step)))
2210
2402
  ];
2211
- case 3:
2212
- signals = _state.sent();
2213
- _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2214
- _state.label = 4;
2215
- case 4:
2216
- _state.trys.push([
2217
- 4,
2218
- 10,
2219
- 11,
2220
- 12
2221
- ]);
2222
- _iterator = signals[Symbol.iterator]();
2223
- _state.label = 5;
2224
- case 5:
2225
- if (!!(_iteratorNormalCompletion = (_step = _iterator.next()).done)) return [
2226
- 3,
2227
- 9
2228
- ];
2229
- signal = _step.value;
2230
- if (!(signal.type === 'KILL')) return [
2403
+ case 37:
2404
+ toolResult = _state.sent();
2405
+ if (!(toolResult && (typeof toolResult === "undefined" ? "undefined" : _type_of(toolResult)) === 'object' && 'waitFor' in toolResult)) return [
2231
2406
  3,
2232
- 7
2407
+ 39
2233
2408
  ];
2234
- this.stopped = true;
2409
+ if (!allowWebhookSuspension) {
2410
+ throw new Error("Webhook/wait inside .map() prompt loop is not supported. " + 'Step "'.concat(step.block.title, '" tool "').concat(toolName, '" triggered a webhook. ') + "Remove webhook-returning tools from the map prompt loop.");
2411
+ }
2412
+ pendingWebhook = {
2413
+ toolCallId: toolCallId,
2414
+ toolName: toolName,
2415
+ input: args,
2416
+ waitFor: toolResult
2417
+ };
2418
+ // Emit tool result with waiting status
2235
2419
  return [
2236
2420
  4,
2237
2421
  {
2238
- type: BRAIN_EVENTS.CANCELLED,
2239
- status: STATUS.CANCELLED,
2240
- brainTitle: this.title,
2241
- brainDescription: this.description,
2242
- brainRunId: this.brainRunId,
2243
- options: (_this_options = this.options) !== null && _this_options !== void 0 ? _this_options : {}
2422
+ type: BRAIN_EVENTS.PROMPT_TOOL_RESULT,
2423
+ stepTitle: stepTitle,
2424
+ stepId: stepId,
2425
+ toolName: toolName,
2426
+ toolCallId: toolCallId,
2427
+ result: 'Waiting for webhook response...',
2428
+ iteration: iteration,
2429
+ status: 'waiting_for_webhook',
2430
+ options: (_this_options15 = this.options) !== null && _this_options15 !== void 0 ? _this_options15 : {},
2431
+ brainRunId: this.brainRunId
2244
2432
  }
2245
2433
  ];
2246
- case 6:
2434
+ case 38:
2247
2435
  _state.sent();
2248
- return [
2249
- 2
2250
- ];
2251
- case 7:
2252
- if (signal.type === 'PAUSE') {
2253
- // Don't yield PAUSED - pausing between iterate items is a backend
2254
- // implementation detail (e.g. Cloudflare DO restart for memory).
2255
- // Just stop execution silently; the backend handles resume.
2256
- this.stopped = true;
2257
- return [
2258
- 2
2259
- ];
2260
- }
2261
- _state.label = 8;
2262
- case 8:
2263
- _iteratorNormalCompletion = true;
2264
- return [
2265
- 3,
2266
- 5
2267
- ];
2268
- case 9:
2436
+ // Add placeholder to conversation
2437
+ placeholderMsg = client.createToolResultMessage(toolCallId, toolName, 'Waiting for webhook response...');
2438
+ responseMessages = _to_consumable_array(responseMessages !== null && responseMessages !== void 0 ? responseMessages : []).concat([
2439
+ placeholderMsg
2440
+ ]);
2441
+ // Continue processing remaining tool calls in this iteration
2269
2442
  return [
2270
2443
  3,
2271
- 12
2444
+ 43
2272
2445
  ];
2273
- case 10:
2274
- err = _state.sent();
2275
- _didIteratorError = true;
2276
- _iteratorError = err;
2446
+ case 39:
2277
2447
  return [
2278
2448
  3,
2279
- 12
2280
- ];
2281
- case 11:
2282
- try {
2283
- if (!_iteratorNormalCompletion && _iterator.return != null) {
2284
- _iterator.return();
2285
- }
2286
- } finally{
2287
- if (_didIteratorError) {
2288
- throw _iteratorError;
2289
- }
2290
- }
2291
- return [
2292
- 7
2449
+ 41
2293
2450
  ];
2294
- case 12:
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
2451
+ case 40:
2452
+ toolResult = {
2453
+ success: true
2454
+ };
2455
+ _state.label = 41;
2456
+ case 41:
2457
+ // Feed tool result back to LLM
2458
+ toolResultMsg2 = client.createToolResultMessage(toolCallId, toolName, toolResult);
2459
+ responseMessages = _to_consumable_array(responseMessages !== null && responseMessages !== void 0 ? responseMessages : []).concat([
2460
+ toolResultMsg2
2304
2461
  ]);
2305
2462
  return [
2306
2463
  4,
2307
- _await_async_generator(iterateConfig.template(item, this.resources))
2464
+ {
2465
+ type: BRAIN_EVENTS.PROMPT_TOOL_RESULT,
2466
+ stepTitle: stepTitle,
2467
+ stepId: stepId,
2468
+ toolName: toolName,
2469
+ toolCallId: toolCallId,
2470
+ result: toolResult,
2471
+ iteration: iteration,
2472
+ options: (_this_options16 = this.options) !== null && _this_options16 !== void 0 ? _this_options16 : {},
2473
+ brainRunId: this.brainRunId
2474
+ }
2308
2475
  ];
2309
- case 14:
2310
- promptText = _state.sent();
2476
+ case 42:
2477
+ _state.sent();
2478
+ _state.label = 43;
2479
+ case 43:
2480
+ _iteratorNormalCompletion2 = true;
2311
2481
  return [
2312
- 4,
2313
- _await_async_generator(client.generateObject({
2314
- schema: iterateConfig.schema,
2315
- schemaName: iterateConfig.schemaName,
2316
- prompt: promptText
2317
- }))
2482
+ 3,
2483
+ 27
2318
2484
  ];
2319
- case 15:
2320
- response = _state.sent();
2321
- result = [
2322
- item,
2323
- response.object
2485
+ case 44:
2486
+ return [
2487
+ 3,
2488
+ 47
2324
2489
  ];
2490
+ case 45:
2491
+ err = _state.sent();
2492
+ _didIteratorError2 = true;
2493
+ _iteratorError2 = err;
2325
2494
  return [
2326
2495
  3,
2327
- 17
2496
+ 47
2328
2497
  ];
2329
- case 16:
2330
- error = _state.sent();
2331
- if (iterateConfig.error) {
2332
- fallback = iterateConfig.error(item, error);
2333
- result = fallback !== null ? [
2334
- item,
2335
- fallback
2336
- ] : undefined;
2337
- } else {
2338
- throw error;
2498
+ case 46:
2499
+ try {
2500
+ if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
2501
+ _iterator2.return();
2502
+ }
2503
+ } finally{
2504
+ if (_didIteratorError2) {
2505
+ throw _iteratorError2;
2506
+ }
2339
2507
  }
2340
2508
  return [
2509
+ 7
2510
+ ];
2511
+ case 47:
2512
+ if (!pendingWebhook) return [
2341
2513
  3,
2342
- 17
2514
+ 50
2343
2515
  ];
2344
- case 17:
2345
- if (result != null) {
2346
- resultsMap.set(i, result);
2347
- }
2348
- // Yield one event per item
2516
+ toolWaitFor = pendingWebhook.waitFor;
2517
+ webhooks = Array.isArray(toolWaitFor.waitFor) ? toolWaitFor.waitFor : [
2518
+ toolWaitFor.waitFor
2519
+ ];
2520
+ serializedWaitFor = webhooks.map(function(registration) {
2521
+ return {
2522
+ slug: registration.slug,
2523
+ identifier: registration.identifier,
2524
+ token: registration.token
2525
+ };
2526
+ });
2527
+ // Emit prompt-level webhook event
2349
2528
  return [
2350
2529
  4,
2351
2530
  {
2352
- type: BRAIN_EVENTS.ITERATE_ITEM_COMPLETE,
2353
- stepTitle: step.block.title,
2354
- stepId: step.id,
2355
- itemIndex: i,
2356
- item: item,
2357
- result: result ? result[1] : undefined,
2358
- processedCount: i + 1,
2359
- totalItems: totalItems,
2360
- schemaName: iterateConfig.schemaName,
2361
- options: (_this_options1 = this.options) !== null && _this_options1 !== void 0 ? _this_options1 : {},
2531
+ type: BRAIN_EVENTS.PROMPT_WEBHOOK,
2532
+ stepTitle: stepTitle,
2533
+ stepId: stepId,
2534
+ toolCallId: pendingWebhook.toolCallId,
2535
+ toolName: pendingWebhook.toolName,
2536
+ input: pendingWebhook.input,
2537
+ options: (_this_options17 = this.options) !== null && _this_options17 !== void 0 ? _this_options17 : {},
2362
2538
  brainRunId: this.brainRunId
2363
2539
  }
2364
2540
  ];
2365
- case 18:
2541
+ case 48:
2542
+ _state.sent();
2543
+ // Emit brain-level webhook event (triggers state machine transition to waiting)
2544
+ return [
2545
+ 4,
2546
+ _object_spread_props(_object_spread({
2547
+ type: BRAIN_EVENTS.WEBHOOK,
2548
+ waitFor: serializedWaitFor
2549
+ }, toolWaitFor.timeout !== undefined && {
2550
+ timeout: toolWaitFor.timeout
2551
+ }), {
2552
+ options: (_this_options18 = this.options) !== null && _this_options18 !== void 0 ? _this_options18 : {},
2553
+ brainRunId: this.brainRunId
2554
+ })
2555
+ ];
2556
+ case 49:
2366
2557
  _state.sent();
2367
- _state.label = 19;
2368
- case 19:
2369
- i++;
2370
2558
  return [
2371
- 3,
2372
2559
  2
2373
2560
  ];
2374
- case 20:
2375
- // All items done - update state and complete step
2376
- finalResults = new IterateResult(_to_consumable_array(resultsMap.values()));
2377
- this.currentState = _object_spread_props(_object_spread({}, this.currentState), _define_property({}, iterateConfig.schemaName, finalResults));
2561
+ case 50:
2378
2562
  return [
2379
- 5,
2380
- _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState))))
2563
+ 3,
2564
+ 5
2381
2565
  ];
2382
- case 21:
2383
- _state.sent();
2566
+ case 51:
2384
2567
  return [
2385
2568
  2
2386
2569
  ];
@@ -2390,30 +2573,34 @@ export var BrainEventStream = /*#__PURE__*/ function() {
2390
2573
  }
2391
2574
  },
2392
2575
  {
2393
- key: "executeIterateBrain",
2576
+ key: "executeMap",
2394
2577
  value: /**
2395
- * Execute a nested brain iterate step. Runs the inner brain once per item
2578
+ * Execute a map step. Runs the inner brain once per item
2396
2579
  * from the `over` list, collects [item, innerState] tuples under `outputKey`.
2397
- */ function executeIterateBrain(step) {
2580
+ */ function executeMap(step) {
2398
2581
  return _wrap_async_generator(function() {
2399
- 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;
2582
+ var _this_resume, block, prevState, config, items, totalItems, iterateProgress, _iterateProgress_processedCount, startIndex, resultsMap, k, r, i, signals, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, signal, _this_options, err, item, result, prompt, itemSystem, _tmp, _tmp1, client, loopResult, response, initialState, _config_options, mapInnerOptions, innerRun, patches, _iteratorAbruptCompletion, _didIteratorError1, _iteratorError1, _iterator1, _step1, _value, event, err1, innerState, error, fallback, _this_options1, finalResults;
2400
2583
  return _ts_generator(this, function(_state) {
2401
2584
  switch(_state.label){
2402
2585
  case 0:
2403
2586
  block = step.block;
2404
- iterateConfig = block.iterateConfig;
2405
2587
  prevState = this.currentState;
2406
2588
  return [
2407
2589
  4,
2408
- _await_async_generator(iterateConfig.over(this.buildStepContext(step)))
2590
+ _await_async_generator(block.configFn(this.buildStepContext(step)))
2409
2591
  ];
2410
2592
  case 1:
2593
+ config = _state.sent();
2594
+ return [
2595
+ 4,
2596
+ _await_async_generator(config.over)
2597
+ ];
2598
+ case 2:
2411
2599
  items = _state.sent();
2412
2600
  totalItems = items.length;
2413
2601
  // Resume support
2414
- iterateProgress = (_this_resumeContext = this.resumeContext) === null || _this_resumeContext === void 0 ? void 0 : _this_resumeContext.iterateProgress;
2602
+ iterateProgress = (_this_resume = this.resume) === null || _this_resume === void 0 ? void 0 : _this_resume.iterateProgress;
2415
2603
  startIndex = (_iterateProgress_processedCount = iterateProgress === null || iterateProgress === void 0 ? void 0 : iterateProgress.processedCount) !== null && _iterateProgress_processedCount !== void 0 ? _iterateProgress_processedCount : 0;
2416
- // Use a Map for results accumulation during iteration.
2417
2604
  resultsMap = new Map();
2418
2605
  if (iterateProgress === null || iterateProgress === void 0 ? void 0 : iterateProgress.accumulatedResults) {
2419
2606
  for(k = 0; k < iterateProgress.accumulatedResults.length; k++){
@@ -2422,45 +2609,45 @@ export var BrainEventStream = /*#__PURE__*/ function() {
2422
2609
  }
2423
2610
  }
2424
2611
  if (iterateProgress) {
2425
- this.resumeContext = undefined;
2612
+ this.resume = undefined;
2426
2613
  }
2427
2614
  i = startIndex;
2428
- _state.label = 2;
2429
- case 2:
2615
+ _state.label = 3;
2616
+ case 3:
2430
2617
  if (!(i < totalItems)) return [
2431
2618
  3,
2432
- 31
2619
+ 45
2433
2620
  ];
2434
2621
  if (!this.signalProvider) return [
2435
2622
  3,
2436
- 12
2623
+ 13
2437
2624
  ];
2438
2625
  return [
2439
2626
  4,
2440
2627
  _await_async_generator(this.signalProvider.getSignals('CONTROL'))
2441
2628
  ];
2442
- case 3:
2629
+ case 4:
2443
2630
  signals = _state.sent();
2444
2631
  _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2445
- _state.label = 4;
2446
- case 4:
2632
+ _state.label = 5;
2633
+ case 5:
2447
2634
  _state.trys.push([
2448
- 4,
2449
- 10,
2635
+ 5,
2450
2636
  11,
2451
- 12
2637
+ 12,
2638
+ 13
2452
2639
  ]);
2453
2640
  _iterator = signals[Symbol.iterator]();
2454
- _state.label = 5;
2455
- case 5:
2641
+ _state.label = 6;
2642
+ case 6:
2456
2643
  if (!!(_iteratorNormalCompletion = (_step = _iterator.next()).done)) return [
2457
2644
  3,
2458
- 9
2645
+ 10
2459
2646
  ];
2460
2647
  signal = _step.value;
2461
2648
  if (!(signal.type === 'KILL')) return [
2462
2649
  3,
2463
- 7
2650
+ 8
2464
2651
  ];
2465
2652
  this.stopped = true;
2466
2653
  return [
@@ -2474,39 +2661,39 @@ export var BrainEventStream = /*#__PURE__*/ function() {
2474
2661
  options: (_this_options = this.options) !== null && _this_options !== void 0 ? _this_options : {}
2475
2662
  }
2476
2663
  ];
2477
- case 6:
2664
+ case 7:
2478
2665
  _state.sent();
2479
2666
  return [
2480
2667
  2
2481
2668
  ];
2482
- case 7:
2669
+ case 8:
2483
2670
  if (signal.type === 'PAUSE') {
2484
2671
  this.stopped = true;
2485
2672
  return [
2486
2673
  2
2487
2674
  ];
2488
2675
  }
2489
- _state.label = 8;
2490
- case 8:
2676
+ _state.label = 9;
2677
+ case 9:
2491
2678
  _iteratorNormalCompletion = true;
2492
2679
  return [
2493
2680
  3,
2494
- 5
2681
+ 6
2495
2682
  ];
2496
- case 9:
2683
+ case 10:
2497
2684
  return [
2498
2685
  3,
2499
- 12
2686
+ 13
2500
2687
  ];
2501
- case 10:
2688
+ case 11:
2502
2689
  err = _state.sent();
2503
2690
  _didIteratorError = true;
2504
2691
  _iteratorError = err;
2505
2692
  return [
2506
2693
  3,
2507
- 12
2694
+ 13
2508
2695
  ];
2509
- case 11:
2696
+ case 12:
2510
2697
  try {
2511
2698
  if (!_iteratorNormalCompletion && _iterator.return != null) {
2512
2699
  _iterator.return();
@@ -2519,62 +2706,145 @@ export var BrainEventStream = /*#__PURE__*/ function() {
2519
2706
  return [
2520
2707
  7
2521
2708
  ];
2522
- case 12:
2709
+ case 13:
2523
2710
  item = items[i];
2524
2711
  result = void 0;
2525
- _state.label = 13;
2526
- case 13:
2712
+ _state.label = 14;
2713
+ case 14:
2527
2714
  _state.trys.push([
2528
- 13,
2529
- 27,
2715
+ 14,
2716
+ 41,
2530
2717
  ,
2531
- 28
2718
+ 42
2532
2719
  ]);
2533
- initialState = iterateConfig.initialState(item, this.currentState);
2534
- innerRun = block.innerBrain.run({
2535
- resources: this.resources,
2536
- client: this.client,
2537
- currentUser: this.currentUser,
2720
+ if (!config.prompt) return [
2721
+ 3,
2722
+ 26
2723
+ ];
2724
+ return [
2725
+ 4,
2726
+ _await_async_generator(resolveTemplate(config.prompt.message(item), this.templateContext))
2727
+ ];
2728
+ case 15:
2729
+ prompt = _state.sent();
2730
+ if (!config.prompt.system) return [
2731
+ 3,
2732
+ 20
2733
+ ];
2734
+ if (!(typeof config.prompt.system === 'function')) return [
2735
+ 3,
2736
+ 17
2737
+ ];
2738
+ return [
2739
+ 4,
2740
+ _await_async_generator(resolveTemplate(config.prompt.system(item), this.templateContext))
2741
+ ];
2742
+ case 16:
2743
+ _tmp1 = _state.sent();
2744
+ return [
2745
+ 3,
2746
+ 19
2747
+ ];
2748
+ case 17:
2749
+ return [
2750
+ 4,
2751
+ _await_async_generator(resolveTemplate(config.prompt.system, this.templateContext))
2752
+ ];
2753
+ case 18:
2754
+ _tmp1 = _state.sent();
2755
+ _state.label = 19;
2756
+ case 19:
2757
+ _tmp = _tmp1;
2758
+ return [
2759
+ 3,
2760
+ 21
2761
+ ];
2762
+ case 20:
2763
+ _tmp = undefined;
2764
+ _state.label = 21;
2765
+ case 21:
2766
+ itemSystem = _tmp;
2767
+ client = config.client ? this.governor ? this.governor(config.client) : config.client : this.client;
2768
+ if (!config.prompt.loop) return [
2769
+ 3,
2770
+ 23
2771
+ ];
2772
+ return [
2773
+ 4,
2774
+ _await_async_generator(this.runMapPromptLoop(step, prompt, itemSystem, client, config.prompt.outputSchema, config.prompt.loop))
2775
+ ];
2776
+ case 22:
2777
+ loopResult = _state.sent();
2778
+ result = [
2779
+ item,
2780
+ loopResult
2781
+ ];
2782
+ return [
2783
+ 3,
2784
+ 25
2785
+ ];
2786
+ case 23:
2787
+ return [
2788
+ 4,
2789
+ _await_async_generator(client.generateObject({
2790
+ schema: config.prompt.outputSchema,
2791
+ prompt: prompt,
2792
+ system: itemSystem
2793
+ }))
2794
+ ];
2795
+ case 24:
2796
+ response = _state.sent();
2797
+ result = [
2798
+ item,
2799
+ response.object
2800
+ ];
2801
+ _state.label = 25;
2802
+ case 25:
2803
+ return [
2804
+ 3,
2805
+ 40
2806
+ ];
2807
+ case 26:
2808
+ // Brain mode: run inner brain per item
2809
+ initialState = config.initialState(item);
2810
+ mapInnerOptions = (_config_options = config.options) !== null && _config_options !== void 0 ? _config_options : {};
2811
+ innerRun = config.run.run(_object_spread_props(_object_spread({}, this.innerBrainParams), {
2538
2812
  initialState: initialState,
2539
- options: (_this_options1 = this.options) !== null && _this_options1 !== void 0 ? _this_options1 : {},
2540
- pages: this.pages,
2541
- env: this.env,
2542
- brainRunId: this.brainRunId,
2543
- governor: this.governor
2544
- });
2813
+ options: mapInnerOptions
2814
+ }));
2545
2815
  patches = [];
2546
2816
  _iteratorAbruptCompletion = false, _didIteratorError1 = false;
2547
- _state.label = 14;
2548
- case 14:
2817
+ _state.label = 27;
2818
+ case 27:
2549
2819
  _state.trys.push([
2550
- 14,
2551
- 20,
2552
- 21,
2553
- 26
2820
+ 27,
2821
+ 33,
2822
+ 34,
2823
+ 39
2554
2824
  ]);
2555
2825
  _iterator1 = _async_iterator(innerRun);
2556
- _state.label = 15;
2557
- case 15:
2826
+ _state.label = 28;
2827
+ case 28:
2558
2828
  return [
2559
2829
  4,
2560
2830
  _await_async_generator(_iterator1.next())
2561
2831
  ];
2562
- case 16:
2832
+ case 29:
2563
2833
  if (!(_iteratorAbruptCompletion = !(_step1 = _state.sent()).done)) return [
2564
2834
  3,
2565
- 19
2835
+ 32
2566
2836
  ];
2567
2837
  _value = _step1.value;
2568
2838
  event = _value;
2569
- // Throw on WEBHOOK — not supported in iterate (Phase 2)
2839
+ // Throw on WEBHOOK — not supported in map
2570
2840
  if (event.type === BRAIN_EVENTS.WEBHOOK) {
2571
- 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.");
2841
+ throw new Error("Webhook/wait inside .map() is not supported. " + 'Step "'.concat(block.title, '" item ').concat(i, " triggered a webhook. ") + "Remove .wait() from the inner brain or process items outside of .map().");
2572
2842
  }
2573
2843
  return [
2574
2844
  4,
2575
2845
  event
2576
2846
  ];
2577
- case 17:
2847
+ case 30:
2578
2848
  _state.sent(); // Forward all inner events
2579
2849
  if (event.type === BRAIN_EVENTS.STEP_COMPLETE) {
2580
2850
  patches.push(event.patch);
@@ -2582,77 +2852,79 @@ export var BrainEventStream = /*#__PURE__*/ function() {
2582
2852
  if (event.type === BRAIN_EVENTS.COMPLETE) {
2583
2853
  return [
2584
2854
  3,
2585
- 19
2855
+ 32
2586
2856
  ];
2587
2857
  }
2588
- _state.label = 18;
2589
- case 18:
2858
+ _state.label = 31;
2859
+ case 31:
2590
2860
  _iteratorAbruptCompletion = false;
2591
2861
  return [
2592
2862
  3,
2593
- 15
2863
+ 28
2594
2864
  ];
2595
- case 19:
2865
+ case 32:
2596
2866
  return [
2597
2867
  3,
2598
- 26
2868
+ 39
2599
2869
  ];
2600
- case 20:
2870
+ case 33:
2601
2871
  err1 = _state.sent();
2602
2872
  _didIteratorError1 = true;
2603
2873
  _iteratorError1 = err1;
2604
2874
  return [
2605
2875
  3,
2606
- 26
2876
+ 39
2607
2877
  ];
2608
- case 21:
2878
+ case 34:
2609
2879
  _state.trys.push([
2610
- 21,
2880
+ 34,
2611
2881
  ,
2612
- 24,
2613
- 25
2882
+ 37,
2883
+ 38
2614
2884
  ]);
2615
2885
  if (!(_iteratorAbruptCompletion && _iterator1.return != null)) return [
2616
2886
  3,
2617
- 23
2887
+ 36
2618
2888
  ];
2619
2889
  return [
2620
2890
  4,
2621
2891
  _await_async_generator(_iterator1.return())
2622
2892
  ];
2623
- case 22:
2893
+ case 35:
2624
2894
  _state.sent();
2625
- _state.label = 23;
2626
- case 23:
2895
+ _state.label = 36;
2896
+ case 36:
2627
2897
  return [
2628
2898
  3,
2629
- 25
2899
+ 38
2630
2900
  ];
2631
- case 24:
2901
+ case 37:
2632
2902
  if (_didIteratorError1) {
2633
2903
  throw _iteratorError1;
2634
2904
  }
2635
2905
  return [
2636
2906
  7
2637
2907
  ];
2638
- case 25:
2908
+ case 38:
2639
2909
  return [
2640
2910
  7
2641
2911
  ];
2642
- case 26:
2912
+ case 39:
2643
2913
  innerState = applyPatches(initialState, patches);
2644
2914
  result = [
2645
2915
  item,
2646
2916
  innerState
2647
2917
  ];
2918
+ _state.label = 40;
2919
+ case 40:
2648
2920
  return [
2649
2921
  3,
2650
- 28
2922
+ 42
2651
2923
  ];
2652
- case 27:
2924
+ case 41:
2653
2925
  error = _state.sent();
2654
- if (iterateConfig.error) {
2655
- fallback = iterateConfig.error(item, error);
2926
+ if (config.error) {
2927
+ fallback = config.error(item, error);
2656
2928
  result = fallback !== null ? [
2657
2929
  item,
2658
2930
  fallback
@@ -2662,9 +2934,9 @@ export var BrainEventStream = /*#__PURE__*/ function() {
2662
2934
  }
2663
2935
  return [
2664
2936
  3,
2665
- 28
2937
+ 42
2666
2938
  ];
2667
- case 28:
2939
+ case 42:
2668
2940
  if (result != null) {
2669
2941
  resultsMap.set(i, result);
2670
2942
  }
@@ -2679,29 +2951,29 @@ export var BrainEventStream = /*#__PURE__*/ function() {
2679
2951
  result: result ? result[1] : undefined,
2680
2952
  processedCount: i + 1,
2681
2953
  totalItems: totalItems,
2682
- schemaName: iterateConfig.outputKey,
2683
- options: (_this_options2 = this.options) !== null && _this_options2 !== void 0 ? _this_options2 : {},
2684
- brainRunId: this.brainRunId
2954
+ stateKey: block.stateKey,
2955
+ options: (_this_options1 = this.options) !== null && _this_options1 !== void 0 ? _this_options1 : {},
2956
+ brainRunId: this.brainRunId,
2957
+ canRelease: !!this.signalProvider
2685
2958
  }
2686
2959
  ];
2687
- case 29:
2960
+ case 43:
2688
2961
  _state.sent();
2689
- _state.label = 30;
2690
- case 30:
2962
+ _state.label = 44;
2963
+ case 44:
2691
2964
  i++;
2692
2965
  return [
2693
2966
  3,
2694
- 2
2967
+ 3
2695
2968
  ];
2696
- case 31:
2697
- finalResults = _to_consumable_array(resultsMap.values());
2698
- outputResults = new IterateResult(finalResults);
2699
- this.currentState = _object_spread_props(_object_spread({}, this.currentState), _define_property({}, iterateConfig.outputKey, outputResults));
2969
+ case 45:
2970
+ finalResults = new IterateResult(_to_consumable_array(resultsMap.values()));
2971
+ this.currentState = _object_spread_props(_object_spread({}, this.currentState), _define_property({}, block.stateKey, finalResults));
2700
2972
  return [
2701
2973
  5,
2702
2974
  _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState))))
2703
2975
  ];
2704
- case 32:
2976
+ case 46:
2705
2977
  _state.sent();
2706
2978
  return [
2707
2979
  2
@@ -2712,305 +2984,101 @@ export var BrainEventStream = /*#__PURE__*/ function() {
2712
2984
  }
2713
2985
  },
2714
2986
  {
2715
- key: "executeIterateAgent",
2716
- value: /**
2717
- * Execute an agent config iterate step. Runs the agent once per item
2718
- * from the `over` list, collects [item, agentResult] tuples under `outputKey`.
2719
- */ function executeIterateAgent(step) {
2987
+ key: "buildFormAction",
2988
+ value: function buildFormAction(step, formSchema) {
2989
+ var webhookIdentifier = "".concat(this.brainRunId, "-").concat(step.id);
2990
+ var formToken = crypto.randomUUID();
2991
+ var formAction = "".concat(this.env.origin, "/webhooks/system/page-form?identifier=").concat(encodeURIComponent(webhookIdentifier), "&token=").concat(encodeURIComponent(formToken));
2992
+ return {
2993
+ formAction: formAction,
2994
+ webhookIdentifier: webhookIdentifier,
2995
+ formToken: formToken,
2996
+ formSchema: formSchema
2997
+ };
2998
+ }
2999
+ },
3000
+ {
3001
+ key: "executePageStep",
3002
+ value: function executePageStep(step, stepBlock) {
2720
3003
  return _wrap_async_generator(function() {
2721
- var _this, _loop, _this_resumeContext, block, iterateConfig, prevState, items, totalItems, iterateProgress, _iterateProgress_processedCount, startIndex, resultsMap, k, r, i, _ret, finalResults;
3004
+ var prevState, pageConfigFn, pageConfig, html, formInfo, body, prompt, _pageConfig_props, data, uiResult, placementCount, placementInfo, _uiResult_text, _pageConfig_persist, pageCreateOptions, page, webhook;
2722
3005
  return _ts_generator(this, function(_state) {
2723
3006
  switch(_state.label){
2724
3007
  case 0:
2725
- _loop = function(i) {
2726
- var signals, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, signal, _this_options, err, item, result, savedState, itemConfigFn, tempBlock, tempStep, agentResult, error, fallback, _this_options1;
2727
- return _ts_generator(this, function(_state) {
2728
- switch(_state.label){
2729
- case 0:
2730
- if (!_this.signalProvider) return [
2731
- 3,
2732
- 10
2733
- ];
2734
- return [
2735
- 4,
2736
- _await_async_generator(_this.signalProvider.getSignals('CONTROL'))
2737
- ];
2738
- case 1:
2739
- signals = _state.sent();
2740
- _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2741
- _state.label = 2;
2742
- case 2:
2743
- _state.trys.push([
2744
- 2,
2745
- 8,
2746
- 9,
2747
- 10
2748
- ]);
2749
- _iterator = signals[Symbol.iterator]();
2750
- _state.label = 3;
2751
- case 3:
2752
- if (!!(_iteratorNormalCompletion = (_step = _iterator.next()).done)) return [
2753
- 3,
2754
- 7
2755
- ];
2756
- signal = _step.value;
2757
- if (!(signal.type === 'KILL')) return [
2758
- 3,
2759
- 5
2760
- ];
2761
- _this.stopped = true;
2762
- return [
2763
- 4,
2764
- {
2765
- type: BRAIN_EVENTS.CANCELLED,
2766
- status: STATUS.CANCELLED,
2767
- brainTitle: _this.title,
2768
- brainDescription: _this.description,
2769
- brainRunId: _this.brainRunId,
2770
- options: (_this_options = _this.options) !== null && _this_options !== void 0 ? _this_options : {}
2771
- }
2772
- ];
2773
- case 4:
2774
- _state.sent();
2775
- return [
2776
- 2,
2777
- {
2778
- v: void void 0
2779
- }
2780
- ];
2781
- case 5:
2782
- if (signal.type === 'PAUSE') {
2783
- _this.stopped = true;
2784
- return [
2785
- 2,
2786
- {
2787
- v: void void 0
2788
- }
2789
- ];
2790
- }
2791
- _state.label = 6;
2792
- case 6:
2793
- _iteratorNormalCompletion = true;
2794
- return [
2795
- 3,
2796
- 3
2797
- ];
2798
- case 7:
2799
- return [
2800
- 3,
2801
- 10
2802
- ];
2803
- case 8:
2804
- err = _state.sent();
2805
- _didIteratorError = true;
2806
- _iteratorError = err;
2807
- return [
2808
- 3,
2809
- 10
2810
- ];
2811
- case 9:
2812
- try {
2813
- if (!_iteratorNormalCompletion && _iterator.return != null) {
2814
- _iterator.return();
2815
- }
2816
- } finally{
2817
- if (_didIteratorError) {
2818
- throw _iteratorError;
2819
- }
2820
- }
2821
- return [
2822
- 7
2823
- ];
2824
- case 10:
2825
- item = items[i];
2826
- result = void 0;
2827
- _state.label = 11;
2828
- case 11:
2829
- _state.trys.push([
2830
- 11,
2831
- 13,
2832
- ,
2833
- 14
2834
- ]);
2835
- // Save outer state; agent will modify this.currentState
2836
- savedState = _this.currentState;
2837
- // Create a wrapper configFn that injects the item as the first argument
2838
- itemConfigFn = function(params) {
2839
- return block.configFn(item, params);
2840
- };
2841
- // Create a temporary agent block with the per-item configFn
2842
- tempBlock = {
2843
- type: 'agent',
2844
- title: block.title,
2845
- configFn: itemConfigFn
2846
- };
2847
- tempStep = new Step(tempBlock);
2848
- return [
2849
- 5,
2850
- _ts_values(_async_generator_delegate(_async_iterator(_this.executeAgent(tempStep))))
2851
- ];
2852
- case 12:
2853
- _state.sent();
2854
- // Capture agent result from this.currentState, then restore outer state
2855
- agentResult = _this.currentState;
2856
- _this.currentState = savedState;
2857
- result = [
2858
- item,
2859
- agentResult
2860
- ];
2861
- return [
2862
- 3,
2863
- 14
2864
- ];
2865
- case 13:
2866
- error = _state.sent();
2867
- if (iterateConfig.error) {
2868
- fallback = iterateConfig.error(item, error);
2869
- result = fallback !== null ? [
2870
- item,
2871
- fallback
2872
- ] : undefined;
2873
- } else {
2874
- throw error;
2875
- }
2876
- return [
2877
- 3,
2878
- 14
2879
- ];
2880
- case 14:
2881
- if (result != null) {
2882
- resultsMap.set(i, result);
2883
- }
2884
- return [
2885
- 4,
2886
- {
2887
- type: BRAIN_EVENTS.ITERATE_ITEM_COMPLETE,
2888
- stepTitle: step.block.title,
2889
- stepId: step.id,
2890
- itemIndex: i,
2891
- item: item,
2892
- result: result ? result[1] : undefined,
2893
- processedCount: i + 1,
2894
- totalItems: totalItems,
2895
- schemaName: iterateConfig.outputKey,
2896
- options: (_this_options1 = _this.options) !== null && _this_options1 !== void 0 ? _this_options1 : {},
2897
- brainRunId: _this.brainRunId
2898
- }
2899
- ];
2900
- case 15:
2901
- _state.sent();
2902
- return [
2903
- 2
2904
- ];
2905
- }
2906
- });
2907
- };
2908
- block = step.block;
2909
- iterateConfig = block.iterateConfig;
2910
3008
  prevState = this.currentState;
3009
+ pageConfigFn = stepBlock.pageConfigFn;
2911
3010
  return [
2912
3011
  4,
2913
- _await_async_generator(iterateConfig.over(this.buildStepContext(step)))
3012
+ _await_async_generator(pageConfigFn(this.buildStepContext(step)))
2914
3013
  ];
2915
3014
  case 1:
2916
- items = _state.sent();
2917
- totalItems = items.length;
2918
- // Resume support
2919
- iterateProgress = (_this_resumeContext = this.resumeContext) === null || _this_resumeContext === void 0 ? void 0 : _this_resumeContext.iterateProgress;
2920
- startIndex = (_iterateProgress_processedCount = iterateProgress === null || iterateProgress === void 0 ? void 0 : iterateProgress.processedCount) !== null && _iterateProgress_processedCount !== void 0 ? _iterateProgress_processedCount : 0;
2921
- // Use a Map for results accumulation during iteration.
2922
- resultsMap = new Map();
2923
- if (iterateProgress === null || iterateProgress === void 0 ? void 0 : iterateProgress.accumulatedResults) {
2924
- for(k = 0; k < iterateProgress.accumulatedResults.length; k++){
2925
- r = iterateProgress.accumulatedResults[k];
2926
- if (r != null) resultsMap.set(k, r);
2927
- }
2928
- }
2929
- if (iterateProgress) {
2930
- this.resumeContext = undefined;
2931
- }
2932
- i = startIndex;
2933
- _state.label = 2;
2934
- case 2:
2935
- if (!(i < totalItems)) return [
2936
- 3,
2937
- 5
2938
- ];
2939
- _this = this;
2940
- return [
2941
- 5,
2942
- _ts_values(_loop(i))
2943
- ];
2944
- case 3:
2945
- _ret = _state.sent();
2946
- if (_type_of(_ret) === "object") return [
2947
- 2,
2948
- _ret.v
2949
- ];
2950
- _state.label = 4;
2951
- case 4:
2952
- i++;
2953
- return [
3015
+ pageConfig = _state.sent();
3016
+ if (!(this.currentResponse && pageConfig.formSchema)) return [
2954
3017
  3,
2955
- 2
3018
+ 3
2956
3019
  ];
2957
- case 5:
2958
- finalResults = new IterateResult(_to_consumable_array(resultsMap.values()));
2959
- this.currentState = _object_spread_props(_object_spread({}, this.currentState), _define_property({}, iterateConfig.outputKey, finalResults));
3020
+ this.currentState = _object_spread({}, this.currentState, this.currentResponse);
3021
+ this.currentResponse = undefined;
2960
3022
  return [
2961
3023
  5,
2962
3024
  _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState))))
2963
3025
  ];
2964
- case 6:
3026
+ case 2:
2965
3027
  _state.sent();
2966
3028
  return [
2967
3029
  2
2968
3030
  ];
2969
- }
2970
- });
2971
- }).call(this);
2972
- }
2973
- },
2974
- {
2975
- key: "executeUIStep",
2976
- value: /**
2977
- * Execute a UI generation step.
2978
- * Generates UI components, renders to HTML, creates page, and sets up webhook.
2979
- */ function executeUIStep(step, stepBlock) {
2980
- return _wrap_async_generator(function() {
2981
- var prevState, uiConfig, prompt, uiResult, placementCount, placementInfo, _uiResult_text, webhookIdentifier, formToken, formAction, html, page, _uiConfig_responseSchema, webhook;
2982
- return _ts_generator(this, function(_state) {
2983
- switch(_state.label){
2984
- case 0:
2985
- prevState = this.currentState;
2986
- // Validate required configuration
2987
- if (!this.components) {
2988
- throw new Error('UI step "'.concat(stepBlock.title, '" requires components to be configured via brain.withComponents()'));
3031
+ case 3:
3032
+ // Validate: exactly one of prompt or html must be present
3033
+ if (!pageConfig.prompt && !pageConfig.html) {
3034
+ throw new Error('Page step "'.concat(stepBlock.title, "\" requires either 'prompt' or 'html'"));
3035
+ }
3036
+ if (pageConfig.prompt && pageConfig.html) {
3037
+ throw new Error('Page step "'.concat(stepBlock.title, "\" cannot have both 'prompt' and 'html'"));
2989
3038
  }
2990
3039
  if (!this.pages) {
2991
- throw new Error('UI step "'.concat(stepBlock.title, '" requires pages service to be configured'));
3040
+ throw new Error('Page step "'.concat(stepBlock.title, '" requires pages service to be configured'));
3041
+ }
3042
+ formInfo = pageConfig.formSchema ? this.buildFormAction(step, pageConfig.formSchema) : undefined;
3043
+ if (!pageConfig.html) return [
3044
+ 3,
3045
+ 4
3046
+ ];
3047
+ body = renderHtml(pageConfig.html, formInfo ? {
3048
+ formAction: formInfo.formAction
3049
+ } : {});
3050
+ html = wrapHtmlDocument(body, {
3051
+ title: stepBlock.title
3052
+ });
3053
+ return [
3054
+ 3,
3055
+ 7
3056
+ ];
3057
+ case 4:
3058
+ // LLM-generated page
3059
+ if (!this.components) {
3060
+ throw new Error('Page step "'.concat(stepBlock.title, '" requires components to be configured via brain.withComponents()'));
2992
3061
  }
2993
- uiConfig = stepBlock.uiConfig;
2994
3062
  return [
2995
3063
  4,
2996
- _await_async_generator(uiConfig.template(this.currentState, this.resources))
3064
+ _await_async_generator(resolveTemplate(pageConfig.prompt, this.templateContext))
2997
3065
  ];
2998
- case 1:
3066
+ case 5:
2999
3067
  prompt = _state.sent();
3068
+ data = (_pageConfig_props = pageConfig.props) !== null && _pageConfig_props !== void 0 ? _pageConfig_props : {};
3000
3069
  return [
3001
3070
  4,
3002
- _await_async_generator(generateUI({
3071
+ _await_async_generator(generatePage({
3003
3072
  client: this.client,
3004
3073
  prompt: prompt,
3005
3074
  components: this.components,
3006
- schema: uiConfig.responseSchema,
3007
- data: this.currentState
3075
+ schema: pageConfig.formSchema,
3076
+ data: data
3008
3077
  }))
3009
3078
  ];
3010
- case 2:
3079
+ case 6:
3011
3080
  uiResult = _state.sent();
3012
3081
  if (!uiResult.rootId) {
3013
- // Provide detailed debug information
3014
3082
  placementCount = uiResult.placements.length;
3015
3083
  placementInfo = uiResult.placements.map(function(p) {
3016
3084
  var _p_parentId;
@@ -3018,60 +3086,104 @@ export var BrainEventStream = /*#__PURE__*/ function() {
3018
3086
  }).join(', ');
3019
3087
  if (placementCount === 0) {
3020
3088
  ;
3021
- throw new Error('UI generation failed for step "'.concat(stepBlock.title, '" - no components were placed. ') + "The LLM may not have called any component tools. " + "LLM response text: ".concat((_uiResult_text = uiResult.text) !== null && _uiResult_text !== void 0 ? _uiResult_text : '(none)'));
3089
+ throw new Error('Page generation failed for step "'.concat(stepBlock.title, '" - no components were placed. ') + "The LLM may not have called any component tools. " + "LLM response text: ".concat((_uiResult_text = uiResult.text) !== null && _uiResult_text !== void 0 ? _uiResult_text : '(none)'));
3022
3090
  } else {
3023
- throw new Error('UI generation failed for step "'.concat(stepBlock.title, '" - no root component found. ') + "".concat(placementCount, " component(s) were placed but all have a parentId: [").concat(placementInfo, "]. ") + "The first component should be placed without a parentId to serve as the root.");
3091
+ throw new Error('Page generation failed for step "'.concat(stepBlock.title, '" - no root component found. ') + "".concat(placementCount, " component(s) were placed but all have a parentId: [").concat(placementInfo, "]. ") + "The first component should be placed without a parentId to serve as the root.");
3024
3092
  }
3025
3093
  }
3026
- // Create unique identifier for this form submission webhook
3027
- webhookIdentifier = "".concat(this.brainRunId, "-").concat(step.id);
3028
- // Generate CSRF token for form submission validation
3029
- formToken = crypto.randomUUID();
3030
- // Construct form action URL for the webhook
3031
- formAction = "".concat(this.env.origin, "/webhooks/system/ui-form?identifier=").concat(encodeURIComponent(webhookIdentifier));
3032
- // Generate HTML page
3033
3094
  html = generatePageHtml({
3034
3095
  placements: uiResult.placements,
3035
3096
  rootId: uiResult.rootId,
3036
- data: this.currentState,
3097
+ data: data,
3037
3098
  title: stepBlock.title,
3038
- formAction: formAction,
3039
- formToken: formToken
3099
+ formAction: formInfo === null || formInfo === void 0 ? void 0 : formInfo.formAction
3040
3100
  });
3101
+ _state.label = 7;
3102
+ case 7:
3103
+ // Step 2: Create page and handle form/read-only branching (shared by both paths)
3104
+ pageCreateOptions = {
3105
+ persist: (_pageConfig_persist = pageConfig.persist) !== null && _pageConfig_persist !== void 0 ? _pageConfig_persist : pageConfig.ttl ? true : false,
3106
+ ttl: pageConfig.ttl
3107
+ };
3041
3108
  return [
3042
3109
  4,
3043
- _await_async_generator(this.pages.create(html))
3110
+ _await_async_generator(this.pages.create(html, pageCreateOptions))
3044
3111
  ];
3045
- case 3:
3112
+ case 8:
3046
3113
  page = _state.sent();
3047
- // Create webhook registration for form submissions
3048
- // Uses a built-in 'ui-form' webhook slug that the backend knows how to handle
3114
+ if (!formInfo) return [
3115
+ 3,
3116
+ 12
3117
+ ];
3049
3118
  webhook = {
3050
- slug: 'ui-form',
3051
- identifier: webhookIdentifier,
3052
- schema: (_uiConfig_responseSchema = uiConfig.responseSchema) !== null && _uiConfig_responseSchema !== void 0 ? _uiConfig_responseSchema : z.record(z.unknown()),
3053
- token: formToken
3119
+ slug: 'page-form',
3120
+ identifier: formInfo.webhookIdentifier,
3121
+ schema: formInfo.formSchema,
3122
+ token: formInfo.formToken
3054
3123
  };
3055
- // Set currentPage for the next step to access
3056
3124
  this.currentPage = {
3057
3125
  url: page.url,
3058
3126
  webhook: webhook
3059
3127
  };
3060
- // State doesn't change from UI step - it just sets up the page
3061
- // The next step will receive the page object and can use waitFor
3128
+ if (!pageConfig.onCreated) return [
3129
+ 3,
3130
+ 10
3131
+ ];
3132
+ return [
3133
+ 4,
3134
+ _await_async_generator(pageConfig.onCreated(this.currentPage))
3135
+ ];
3136
+ case 9:
3137
+ _state.sent();
3138
+ _state.label = 10;
3139
+ case 10:
3140
+ return [
3141
+ 4,
3142
+ {
3143
+ type: BRAIN_EVENTS.WEBHOOK,
3144
+ waitFor: [
3145
+ {
3146
+ slug: webhook.slug,
3147
+ identifier: webhook.identifier,
3148
+ token: webhook.token
3149
+ }
3150
+ ],
3151
+ options: this.options,
3152
+ brainRunId: this.brainRunId
3153
+ }
3154
+ ];
3155
+ case 11:
3156
+ _state.sent();
3157
+ this.currentPage = undefined;
3158
+ return [
3159
+ 3,
3160
+ 16
3161
+ ];
3162
+ case 12:
3163
+ if (!pageConfig.onCreated) return [
3164
+ 3,
3165
+ 14
3166
+ ];
3167
+ return [
3168
+ 4,
3169
+ _await_async_generator(pageConfig.onCreated({
3170
+ url: page.url
3171
+ }))
3172
+ ];
3173
+ case 13:
3174
+ _state.sent();
3175
+ _state.label = 14;
3176
+ case 14:
3062
3177
  return [
3063
3178
  5,
3064
3179
  _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState, {
3065
- url: page.url,
3066
- webhook: {
3067
- slug: webhook.slug,
3068
- identifier: webhook.identifier,
3069
- token: webhook.token
3070
- }
3180
+ url: page.url
3071
3181
  }))))
3072
3182
  ];
3073
- case 4:
3183
+ case 15:
3074
3184
  _state.sent();
3185
+ _state.label = 16;
3186
+ case 16:
3075
3187
  return [
3076
3188
  2
3077
3189
  ];
@@ -3084,7 +3196,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
3084
3196
  key: "executeWait",
3085
3197
  value: function executeWait(step, waitBlock) {
3086
3198
  return _wrap_async_generator(function() {
3087
- var _this, steps, options, brainRunId, _this_options, result, webhooks, serializedWaitFor;
3199
+ var _this, steps, options, brainRunId, result, webhooks, serializedWaitFor;
3088
3200
  return _ts_generator(this, function(_state) {
3089
3201
  switch(_state.label){
3090
3202
  case 0:
@@ -3107,33 +3219,13 @@ export var BrainEventStream = /*#__PURE__*/ function() {
3107
3219
  step.withStatus(STATUS.RUNNING);
3108
3220
  return [
3109
3221
  4,
3110
- {
3111
- type: BRAIN_EVENTS.STEP_STATUS,
3112
- steps: steps.map(function(s) {
3113
- var _s_serialized = s.serialized, patch = _s_serialized.patch, rest = _object_without_properties(_s_serialized, [
3114
- "patch"
3115
- ]);
3116
- return rest;
3117
- }),
3118
- options: options,
3119
- brainRunId: brainRunId
3120
- }
3222
+ this.stepStatusEvent()
3121
3223
  ];
3122
3224
  case 2:
3123
3225
  _state.sent();
3124
3226
  return [
3125
3227
  4,
3126
- _await_async_generator(waitBlock.action(_object_spread({
3127
- state: this.currentState,
3128
- options: (_this_options = this.options) !== null && _this_options !== void 0 ? _this_options : {},
3129
- client: this.client,
3130
- resources: this.resources,
3131
- page: this.currentPage,
3132
- pages: this.pages,
3133
- env: this.env,
3134
- store: this.store,
3135
- currentUser: this.currentUser
3136
- }, this.services)))
3228
+ _await_async_generator(waitBlock.action(this.buildStepContext(step)))
3137
3229
  ];
3138
3230
  case 3:
3139
3231
  result = _state.sent();
@@ -3146,17 +3238,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
3146
3238
  _state.sent();
3147
3239
  return [
3148
3240
  4,
3149
- {
3150
- type: BRAIN_EVENTS.STEP_STATUS,
3151
- steps: steps.map(function(s) {
3152
- var _s_serialized = s.serialized, patch = _s_serialized.patch, rest = _object_without_properties(_s_serialized, [
3153
- "patch"
3154
- ]);
3155
- return rest;
3156
- }),
3157
- options: options,
3158
- brainRunId: brainRunId
3159
- }
3241
+ this.stepStatusEvent()
3160
3242
  ];
3161
3243
  case 5:
3162
3244
  _state.sent();
@@ -3205,10 +3287,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
3205
3287
  switch(_state.label){
3206
3288
  case 0:
3207
3289
  _this = this, steps = _this.steps, options = _this.options, brainRunId = _this.brainRunId;
3208
- predicateResult = guard.predicate({
3209
- state: this.currentState,
3210
- options: this.options
3211
- });
3290
+ predicateResult = guard.predicate(this.buildStepContext(step));
3212
3291
  // Emit STEP_START for the guard
3213
3292
  return [
3214
3293
  4,
@@ -3227,17 +3306,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
3227
3306
  step.withStatus(STATUS.RUNNING);
3228
3307
  return [
3229
3308
  4,
3230
- {
3231
- type: BRAIN_EVENTS.STEP_STATUS,
3232
- steps: steps.map(function(s) {
3233
- var _s_serialized = s.serialized, patch = _s_serialized.patch, rest = _object_without_properties(_s_serialized, [
3234
- "patch"
3235
- ]);
3236
- return rest;
3237
- }),
3238
- options: options,
3239
- brainRunId: brainRunId
3240
- }
3309
+ this.stepStatusEvent()
3241
3310
  ];
3242
3311
  case 2:
3243
3312
  _state.sent();
@@ -3250,17 +3319,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
3250
3319
  _state.sent();
3251
3320
  return [
3252
3321
  4,
3253
- {
3254
- type: BRAIN_EVENTS.STEP_STATUS,
3255
- steps: steps.map(function(s) {
3256
- var _s_serialized = s.serialized, patch = _s_serialized.patch, rest = _object_without_properties(_s_serialized, [
3257
- "patch"
3258
- ]);
3259
- return rest;
3260
- }),
3261
- options: options,
3262
- brainRunId: brainRunId
3263
- }
3322
+ this.stepStatusEvent()
3264
3323
  ];
3265
3324
  case 4:
3266
3325
  _state.sent();
@@ -3300,17 +3359,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
3300
3359
  case 7:
3301
3360
  return [
3302
3361
  4,
3303
- {
3304
- type: BRAIN_EVENTS.STEP_STATUS,
3305
- steps: steps.map(function(s) {
3306
- var _s_serialized = s.serialized, patch = _s_serialized.patch, rest = _object_without_properties(_s_serialized, [
3307
- "patch"
3308
- ]);
3309
- return rest;
3310
- }),
3311
- options: options,
3312
- brainRunId: brainRunId
3313
- }
3362
+ this.stepStatusEvent()
3314
3363
  ];
3315
3364
  case 8:
3316
3365
  _state.sent();
@@ -3323,6 +3372,120 @@ export var BrainEventStream = /*#__PURE__*/ function() {
3323
3372
  });
3324
3373
  }
3325
3374
  },
3375
+ {
3376
+ key: "runMapPromptLoop",
3377
+ value: /**
3378
+ * Run a prompt loop for a single map item. Delegates to the shared
3379
+ * runPromptLoop generator, drains events (map doesn't forward prompt events),
3380
+ * and extracts the result from the PROMPT_COMPLETE event.
3381
+ */ function runMapPromptLoop(step, prompt, system, client, outputSchema, loopConfig) {
3382
+ return _async_to_generator(function() {
3383
+ var loopGen, result, _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, _value, event, err;
3384
+ return _ts_generator(this, function(_state) {
3385
+ switch(_state.label){
3386
+ case 0:
3387
+ loopGen = this.runPromptLoop({
3388
+ step: step,
3389
+ prompt: prompt,
3390
+ system: system,
3391
+ client: client,
3392
+ outputSchema: outputSchema,
3393
+ loopConfig: loopConfig,
3394
+ allowWebhookSuspension: false
3395
+ });
3396
+ _iteratorAbruptCompletion = false, _didIteratorError = false;
3397
+ _state.label = 1;
3398
+ case 1:
3399
+ _state.trys.push([
3400
+ 1,
3401
+ 6,
3402
+ 7,
3403
+ 12
3404
+ ]);
3405
+ _iterator = _async_iterator(loopGen);
3406
+ _state.label = 2;
3407
+ case 2:
3408
+ return [
3409
+ 4,
3410
+ _iterator.next()
3411
+ ];
3412
+ case 3:
3413
+ if (!(_iteratorAbruptCompletion = !(_step = _state.sent()).done)) return [
3414
+ 3,
3415
+ 5
3416
+ ];
3417
+ _value = _step.value;
3418
+ event = _value;
3419
+ if (event.type === BRAIN_EVENTS.PROMPT_COMPLETE) {
3420
+ result = event.result;
3421
+ }
3422
+ _state.label = 4;
3423
+ case 4:
3424
+ _iteratorAbruptCompletion = false;
3425
+ return [
3426
+ 3,
3427
+ 2
3428
+ ];
3429
+ case 5:
3430
+ return [
3431
+ 3,
3432
+ 12
3433
+ ];
3434
+ case 6:
3435
+ err = _state.sent();
3436
+ _didIteratorError = true;
3437
+ _iteratorError = err;
3438
+ return [
3439
+ 3,
3440
+ 12
3441
+ ];
3442
+ case 7:
3443
+ _state.trys.push([
3444
+ 7,
3445
+ ,
3446
+ 10,
3447
+ 11
3448
+ ]);
3449
+ if (!(_iteratorAbruptCompletion && _iterator.return != null)) return [
3450
+ 3,
3451
+ 9
3452
+ ];
3453
+ return [
3454
+ 4,
3455
+ _iterator.return()
3456
+ ];
3457
+ case 8:
3458
+ _state.sent();
3459
+ _state.label = 9;
3460
+ case 9:
3461
+ return [
3462
+ 3,
3463
+ 11
3464
+ ];
3465
+ case 10:
3466
+ if (_didIteratorError) {
3467
+ throw _iteratorError;
3468
+ }
3469
+ return [
3470
+ 7
3471
+ ];
3472
+ case 11:
3473
+ return [
3474
+ 7
3475
+ ];
3476
+ case 12:
3477
+ if (!result) {
3478
+ throw new Error('Prompt loop in map step "'.concat(step.block.title, '" did not produce a result'));
3479
+ }
3480
+ return [
3481
+ 2,
3482
+ result
3483
+ ];
3484
+ }
3485
+ });
3486
+ }).call(this);
3487
+ }
3488
+ },
3326
3489
  {
3327
3490
  key: "completeStep",
3328
3491
  value: function completeStep(step, prevState, pageContext) {