@positronic/core 0.0.55 → 0.0.57

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/src/dsl/agent-messages.js +4 -75
  2. package/dist/src/dsl/brain-runner.js +131 -47
  3. package/dist/src/dsl/brain-state-machine.js +318 -482
  4. package/dist/src/dsl/builder/brain.js +35 -1
  5. package/dist/src/dsl/constants.js +14 -2
  6. package/dist/src/dsl/create-brain.js +4 -1
  7. package/dist/src/dsl/execution/constants.js +2 -2
  8. package/dist/src/dsl/execution/event-stream.js +837 -272
  9. package/dist/src/dsl/signal-validation.js +157 -0
  10. package/dist/src/dsl/types.js +2 -2
  11. package/dist/src/index.js +5 -2
  12. package/dist/src/memory/scoped-memory.js +176 -0
  13. package/dist/src/memory/types.js +12 -0
  14. package/dist/src/tools/index.js +150 -47
  15. package/dist/src/ui/generate-ui.js +6 -3
  16. package/dist/src/yaml/data-validator.js +195 -0
  17. package/dist/types/clients/types.d.ts +39 -2
  18. package/dist/types/clients/types.d.ts.map +1 -1
  19. package/dist/types/dsl/agent-messages.d.ts +8 -14
  20. package/dist/types/dsl/agent-messages.d.ts.map +1 -1
  21. package/dist/types/dsl/brain-runner.d.ts +27 -7
  22. package/dist/types/dsl/brain-runner.d.ts.map +1 -1
  23. package/dist/types/dsl/brain-state-machine.d.ts +92 -23
  24. package/dist/types/dsl/brain-state-machine.d.ts.map +1 -1
  25. package/dist/types/dsl/brain.d.ts +2 -2
  26. package/dist/types/dsl/brain.d.ts.map +1 -1
  27. package/dist/types/dsl/builder/brain.d.ts +56 -35
  28. package/dist/types/dsl/builder/brain.d.ts.map +1 -1
  29. package/dist/types/dsl/constants.d.ts +8 -0
  30. package/dist/types/dsl/constants.d.ts.map +1 -1
  31. package/dist/types/dsl/create-brain.d.ts +17 -17
  32. package/dist/types/dsl/create-brain.d.ts.map +1 -1
  33. package/dist/types/dsl/definitions/blocks.d.ts +3 -3
  34. package/dist/types/dsl/definitions/blocks.d.ts.map +1 -1
  35. package/dist/types/dsl/definitions/events.d.ts +40 -3
  36. package/dist/types/dsl/definitions/events.d.ts.map +1 -1
  37. package/dist/types/dsl/definitions/run-params.d.ts +17 -9
  38. package/dist/types/dsl/definitions/run-params.d.ts.map +1 -1
  39. package/dist/types/dsl/execution/constants.d.ts +2 -2
  40. package/dist/types/dsl/execution/constants.d.ts.map +1 -1
  41. package/dist/types/dsl/execution/event-stream.d.ts +12 -5
  42. package/dist/types/dsl/execution/event-stream.d.ts.map +1 -1
  43. package/dist/types/dsl/signal-validation.d.ts +36 -0
  44. package/dist/types/dsl/signal-validation.d.ts.map +1 -0
  45. package/dist/types/dsl/types.d.ts +91 -2
  46. package/dist/types/dsl/types.d.ts.map +1 -1
  47. package/dist/types/index.d.ts +12 -7
  48. package/dist/types/index.d.ts.map +1 -1
  49. package/dist/types/memory/scoped-memory.d.ts +22 -0
  50. package/dist/types/memory/scoped-memory.d.ts.map +1 -0
  51. package/dist/types/memory/types.d.ts +106 -0
  52. package/dist/types/memory/types.d.ts.map +1 -0
  53. package/dist/types/tools/index.d.ts +101 -32
  54. package/dist/types/tools/index.d.ts.map +1 -1
  55. package/dist/types/ui/generate-ui.d.ts.map +1 -1
  56. package/dist/types/yaml/data-validator.d.ts +27 -1
  57. package/dist/types/yaml/data-validator.d.ts.map +1 -1
  58. package/dist/types/yaml/types.d.ts +10 -0
  59. package/dist/types/yaml/types.d.ts.map +1 -1
  60. package/package.json +1 -1
@@ -6,6 +6,9 @@ function _array_like_to_array(arr, len) {
6
6
  function _array_with_holes(arr) {
7
7
  if (Array.isArray(arr)) return arr;
8
8
  }
9
+ function _array_without_holes(arr) {
10
+ if (Array.isArray(arr)) return _array_like_to_array(arr);
11
+ }
9
12
  function _async_generator(gen) {
10
13
  var front, back;
11
14
  function send(key, arg) {
@@ -198,6 +201,9 @@ function _define_property(obj, key, value) {
198
201
  }
199
202
  return obj;
200
203
  }
204
+ function _iterable_to_array(iter) {
205
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
206
+ }
201
207
  function _iterable_to_array_limit(arr, i) {
202
208
  var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
203
209
  if (_i == null) return;
@@ -225,6 +231,9 @@ function _iterable_to_array_limit(arr, i) {
225
231
  function _non_iterable_rest() {
226
232
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
227
233
  }
234
+ function _non_iterable_spread() {
235
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
236
+ }
228
237
  function _object_spread(target) {
229
238
  for(var i = 1; i < arguments.length; i++){
230
239
  var source = arguments[i] != null ? arguments[i] : {};
@@ -298,6 +307,9 @@ function _overload_yield(value, kind) {
298
307
  function _sliced_to_array(arr, i) {
299
308
  return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
300
309
  }
310
+ function _to_consumable_array(arr) {
311
+ return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
312
+ }
301
313
  function _type_of(obj) {
302
314
  "@swc/helpers - typeof";
303
315
  return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
@@ -426,8 +438,10 @@ import { STATUS, BRAIN_EVENTS } from '../constants.js';
426
438
  import { createPatch, applyPatches } from '../json-patch.js';
427
439
  import { generateUI } from '../../ui/generate-ui.js';
428
440
  import { generatePageHtml } from '../../ui/generate-page-html.js';
441
+ import { createScopedMemory } from '../../memory/scoped-memory.js';
429
442
  import { Step } from '../builder/step.js';
430
443
  import { DEFAULT_ENV, DEFAULT_AGENT_SYSTEM_PROMPT, MAX_RETRIES } from './constants.js';
444
+ import { defaultDoneSchema } from '../../tools/index.js';
431
445
  var clone = function(value) {
432
446
  return structuredClone(value);
433
447
  };
@@ -438,7 +452,6 @@ export var BrainEventStream = /*#__PURE__*/ function() {
438
452
  _define_property(this, "currentState", void 0);
439
453
  _define_property(this, "steps", void 0);
440
454
  _define_property(this, "currentStepIndex", 0);
441
- _define_property(this, "initialState", void 0);
442
455
  _define_property(this, "brainRunId", void 0);
443
456
  _define_property(this, "title", void 0);
444
457
  _define_property(this, "description", void 0);
@@ -450,12 +463,17 @@ export var BrainEventStream = /*#__PURE__*/ function() {
450
463
  _define_property(this, "env", void 0);
451
464
  _define_property(this, "currentResponse", undefined);
452
465
  _define_property(this, "currentPage", undefined);
453
- _define_property(this, "agentResumeContext", undefined);
454
- _define_property(this, "initialCompletedSteps", void 0);
466
+ _define_property(this, "resumeContext", void 0);
455
467
  _define_property(this, "components", void 0);
456
468
  _define_property(this, "defaultTools", void 0);
457
- var _params_initialState = params.initialState, initialState = _params_initialState === void 0 ? {} : _params_initialState, initialCompletedSteps = params.initialCompletedSteps, 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, response = params.response, agentResumeContext = params.agentResumeContext, components = params.components, defaultTools = params.defaultTools;
458
- this.initialState = initialState;
469
+ _define_property(this, "signalProvider", void 0);
470
+ _define_property(this, "memoryProvider", void 0);
471
+ _define_property(this, "scopedMemory", void 0);
472
+ var blocks = params.blocks, title = params.title, description = params.description, providedBrainRunId = params.brainRunId, _params_options = params.options, options = _params_options === void 0 ? {} : _params_options, client = params.client, services = params.services, _params_resources = params.resources, resources = _params_resources === void 0 ? {} : _params_resources, pages = params.pages, env = params.env, components = params.components, defaultTools = params.defaultTools, signalProvider = params.signalProvider, memoryProvider = params.memoryProvider;
473
+ // Check if this is a resume run or fresh start
474
+ var resumeParams = params;
475
+ var initialParams = params;
476
+ var resumeContext = resumeParams.resumeContext;
459
477
  this.title = title;
460
478
  this.description = description;
461
479
  this.client = client;
@@ -464,63 +482,58 @@ export var BrainEventStream = /*#__PURE__*/ function() {
464
482
  this.resources = resources;
465
483
  this.pages = pages;
466
484
  this.env = env !== null && env !== void 0 ? env : DEFAULT_ENV;
467
- this.initialCompletedSteps = initialCompletedSteps;
485
+ this.resumeContext = resumeContext;
468
486
  this.components = components;
469
487
  this.defaultTools = defaultTools;
470
- // Initialize steps array with UUIDs and pending status
471
- this.steps = blocks.map(function(block, index) {
472
- var completedStep = initialCompletedSteps === null || initialCompletedSteps === void 0 ? void 0 : initialCompletedSteps[index];
473
- if (completedStep) {
474
- return new Step(block, completedStep.id).withStatus(completedStep.status).withPatch(completedStep.patch);
475
- }
488
+ this.signalProvider = signalProvider;
489
+ this.memoryProvider = memoryProvider;
490
+ // Create scoped memory if provider is configured
491
+ if (memoryProvider) {
492
+ this.scopedMemory = createScopedMemory(memoryProvider, title);
493
+ }
494
+ // Initialize steps - all start as pending (fresh UUIDs)
495
+ this.steps = blocks.map(function(block) {
476
496
  return new Step(block);
477
497
  });
478
- this.currentState = clone(this.initialState);
479
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
480
- try {
481
- for(var _iterator = this.steps[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
482
- var step = _step.value;
483
- if (step.serialized.status === STATUS.COMPLETE && step.serialized.patch) {
484
- this.currentState = applyPatches(this.currentState, [
485
- step.serialized.patch
486
- ]);
487
- }
498
+ if (resumeContext) {
499
+ // Resume: use state and stepIndex directly from resumeContext
500
+ this.currentState = clone(resumeContext.state);
501
+ this.currentStepIndex = resumeContext.stepIndex;
502
+ // Mark steps before stepIndex as complete (they won't be re-executed)
503
+ for(var i = 0; i < resumeContext.stepIndex; i++){
504
+ this.steps[i].withStatus(STATUS.COMPLETE);
488
505
  }
489
- } catch (err) {
490
- _didIteratorError = true;
491
- _iteratorError = err;
492
- } finally{
493
- try {
494
- if (!_iteratorNormalCompletion && _iterator.return != null) {
495
- _iterator.return();
496
- }
497
- } finally{
498
- if (_didIteratorError) {
499
- throw _iteratorError;
500
- }
506
+ // For inner brains (no signalProvider), check resumeContext for webhookResponse
507
+ // The outer brain will have set this from the signal
508
+ if (!signalProvider && resumeContext.webhookResponse && !resumeContext.agentContext) {
509
+ this.currentResponse = resumeContext.webhookResponse;
501
510
  }
511
+ // Agent webhook response is handled via agentContext (checked in executeAgent)
512
+ } else {
513
+ var _initialParams_initialState;
514
+ // Fresh start: use initialState or empty object
515
+ this.currentState = clone((_initialParams_initialState = initialParams.initialState) !== null && _initialParams_initialState !== void 0 ? _initialParams_initialState : {});
516
+ this.currentStepIndex = 0;
502
517
  }
503
518
  // Use provided ID if available, otherwise generate one
504
519
  this.brainRunId = providedBrainRunId !== null && providedBrainRunId !== void 0 ? providedBrainRunId : uuidv4();
505
- // Set agent resume context if provided (for agent webhook restarts)
506
- if (agentResumeContext) {
507
- this.agentResumeContext = agentResumeContext;
508
- // Note: We intentionally do NOT set currentResponse here.
509
- // For agent resumption, the webhook response should flow through
510
- // the messages array (via agentResumeContext), not through the
511
- // config function's response parameter. The config function is
512
- // for agent setup, not for processing webhook responses.
513
- } else if (response) {
514
- // Set initial response only for non-agent webhook restarts
515
- this.currentResponse = response;
516
- }
517
520
  }
518
521
  _create_class(BrainEventStream, [
522
+ {
523
+ key: "findWebhookResponseInResumeContext",
524
+ value: /**
525
+ * Find webhookResponse anywhere in the resumeContext tree (for nested brain resumes)
526
+ */ function findWebhookResponseInResumeContext(context) {
527
+ if (!context) return undefined;
528
+ if (context.webhookResponse) return context.webhookResponse;
529
+ return this.findWebhookResponseInResumeContext(context.innerResumeContext);
530
+ }
531
+ },
519
532
  {
520
533
  key: "next",
521
534
  value: function next() {
522
535
  return _wrap_async_generator(function() {
523
- var _this, steps, brainTitle, brainDescription, currentState, options, brainRunId, hasCompletedSteps, step, err, error, currentStep;
536
+ var _this, steps, brainTitle, brainDescription, currentState, options, brainRunId, webhookResponse, signals, webhookSignal, deepest, signals1, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, signal, err, step, err1, error, currentStep;
524
537
  return _ts_generator(this, function(_state) {
525
538
  switch(_state.label){
526
539
  case 0:
@@ -529,26 +542,25 @@ export var BrainEventStream = /*#__PURE__*/ function() {
529
542
  case 1:
530
543
  _state.trys.push([
531
544
  1,
532
- 11,
545
+ 29,
533
546
  ,
534
- 14
547
+ 32
535
548
  ]);
536
- hasCompletedSteps = steps.some(function(step) {
537
- return step.serialized.status !== STATUS.PENDING;
538
- });
549
+ if (!!this.resumeContext) return [
550
+ 3,
551
+ 4
552
+ ];
539
553
  return [
540
554
  4,
541
- _object_spread_props(_object_spread({
542
- type: hasCompletedSteps ? BRAIN_EVENTS.RESTART : BRAIN_EVENTS.START,
555
+ {
556
+ type: BRAIN_EVENTS.START,
543
557
  status: STATUS.RUNNING,
544
558
  brainTitle: brainTitle,
545
- brainDescription: brainDescription
546
- }, hasCompletedSteps ? {} : {
547
- initialState: currentState
548
- }), {
559
+ brainDescription: brainDescription,
560
+ initialState: currentState,
549
561
  options: options,
550
562
  brainRunId: brainRunId
551
- })
563
+ }
552
564
  ];
553
565
  case 2:
554
566
  _state.sent();
@@ -569,19 +581,199 @@ export var BrainEventStream = /*#__PURE__*/ function() {
569
581
  ];
570
582
  case 3:
571
583
  _state.sent();
572
- _state.label = 4;
584
+ return [
585
+ 3,
586
+ 11
587
+ ];
573
588
  case 4:
574
- if (!(this.currentStepIndex < steps.length)) return [
589
+ if (!this.signalProvider) return [
590
+ 3,
591
+ 6
592
+ ];
593
+ return [
594
+ 4,
595
+ _await_async_generator(this.signalProvider.getSignals('WEBHOOK'))
596
+ ];
597
+ case 5:
598
+ signals = _state.sent();
599
+ webhookSignal = signals.find(function(s) {
600
+ return s.type === 'WEBHOOK_RESPONSE';
601
+ });
602
+ if (webhookSignal && webhookSignal.type === 'WEBHOOK_RESPONSE') {
603
+ webhookResponse = webhookSignal.response;
604
+ // Set currentResponse for step consumption (non-agent webhooks)
605
+ this.currentResponse = webhookResponse;
606
+ // Set webhookResponse at the deepest level of the resumeContext tree
607
+ // This is needed for:
608
+ // 1. Agent webhook resumes (via resumeContext.webhookResponse)
609
+ // 2. Nested brain resumes (inner brain accesses via innerResumeContext)
610
+ if (this.resumeContext) {
611
+ deepest = this.resumeContext;
612
+ while(deepest.innerResumeContext){
613
+ deepest = deepest.innerResumeContext;
614
+ }
615
+ deepest.webhookResponse = webhookResponse;
616
+ }
617
+ }
618
+ return [
619
+ 3,
620
+ 7
621
+ ];
622
+ case 6:
623
+ // Inner brain (no signalProvider): check resumeContext for webhookResponse
624
+ // The outer brain will have set this from the signal
625
+ webhookResponse = this.findWebhookResponseInResumeContext(this.resumeContext);
626
+ _state.label = 7;
627
+ case 7:
628
+ if (!webhookResponse) return [
575
629
  3,
576
630
  9
577
631
  ];
632
+ // Emit WEBHOOK_RESPONSE to transition state machine from 'waiting' to 'running'
633
+ return [
634
+ 4,
635
+ {
636
+ type: BRAIN_EVENTS.WEBHOOK_RESPONSE,
637
+ brainRunId: brainRunId,
638
+ response: webhookResponse,
639
+ options: options !== null && options !== void 0 ? options : {}
640
+ }
641
+ ];
642
+ case 8:
643
+ _state.sent();
644
+ return [
645
+ 3,
646
+ 11
647
+ ];
648
+ case 9:
649
+ // RESUME signal or default resume behavior - emit RESUMED to transition state machine
650
+ return [
651
+ 4,
652
+ {
653
+ type: BRAIN_EVENTS.RESUMED,
654
+ status: STATUS.RUNNING,
655
+ brainTitle: brainTitle,
656
+ brainDescription: brainDescription,
657
+ brainRunId: brainRunId,
658
+ options: options !== null && options !== void 0 ? options : {}
659
+ }
660
+ ];
661
+ case 10:
662
+ _state.sent();
663
+ _state.label = 11;
664
+ case 11:
665
+ if (!(this.currentStepIndex < steps.length)) return [
666
+ 3,
667
+ 27
668
+ ];
669
+ if (!this.signalProvider) return [
670
+ 3,
671
+ 22
672
+ ];
673
+ return [
674
+ 4,
675
+ _await_async_generator(this.signalProvider.getSignals('CONTROL'))
676
+ ];
677
+ case 12:
678
+ signals1 = _state.sent();
679
+ _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
680
+ _state.label = 13;
681
+ case 13:
682
+ _state.trys.push([
683
+ 13,
684
+ 20,
685
+ 21,
686
+ 22
687
+ ]);
688
+ _iterator = signals1[Symbol.iterator]();
689
+ _state.label = 14;
690
+ case 14:
691
+ if (!!(_iteratorNormalCompletion = (_step = _iterator.next()).done)) return [
692
+ 3,
693
+ 19
694
+ ];
695
+ signal = _step.value;
696
+ if (!(signal.type === 'KILL')) return [
697
+ 3,
698
+ 16
699
+ ];
700
+ return [
701
+ 4,
702
+ {
703
+ type: BRAIN_EVENTS.CANCELLED,
704
+ status: STATUS.CANCELLED,
705
+ brainTitle: brainTitle,
706
+ brainDescription: brainDescription,
707
+ brainRunId: brainRunId,
708
+ options: options
709
+ }
710
+ ];
711
+ case 15:
712
+ _state.sent();
713
+ return [
714
+ 2
715
+ ];
716
+ case 16:
717
+ if (!(signal.type === 'PAUSE')) return [
718
+ 3,
719
+ 18
720
+ ];
721
+ return [
722
+ 4,
723
+ {
724
+ type: BRAIN_EVENTS.PAUSED,
725
+ status: STATUS.PAUSED,
726
+ brainTitle: brainTitle,
727
+ brainDescription: brainDescription,
728
+ brainRunId: brainRunId,
729
+ options: options
730
+ }
731
+ ];
732
+ case 17:
733
+ _state.sent();
734
+ return [
735
+ 2
736
+ ];
737
+ case 18:
738
+ _iteratorNormalCompletion = true;
739
+ return [
740
+ 3,
741
+ 14
742
+ ];
743
+ case 19:
744
+ return [
745
+ 3,
746
+ 22
747
+ ];
748
+ case 20:
749
+ err = _state.sent();
750
+ _didIteratorError = true;
751
+ _iteratorError = err;
752
+ return [
753
+ 3,
754
+ 22
755
+ ];
756
+ case 21:
757
+ try {
758
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
759
+ _iterator.return();
760
+ }
761
+ } finally{
762
+ if (_didIteratorError) {
763
+ throw _iteratorError;
764
+ }
765
+ }
766
+ return [
767
+ 7
768
+ ];
769
+ case 22:
578
770
  step = steps[this.currentStepIndex];
579
771
  // Skip completed steps
580
772
  if (step.serialized.status === STATUS.COMPLETE) {
581
773
  this.currentStepIndex++;
582
774
  return [
583
775
  3,
584
- 4
776
+ 11
585
777
  ];
586
778
  }
587
779
  // Step start event
@@ -592,11 +784,12 @@ export var BrainEventStream = /*#__PURE__*/ function() {
592
784
  status: STATUS.RUNNING,
593
785
  stepTitle: step.block.title,
594
786
  stepId: step.id,
787
+ stepIndex: this.currentStepIndex,
595
788
  options: options,
596
789
  brainRunId: brainRunId
597
790
  }
598
791
  ];
599
- case 5:
792
+ case 23:
600
793
  _state.sent();
601
794
  step.withStatus(STATUS.RUNNING);
602
795
  // Step Status Event to indicate that the step is running
@@ -614,7 +807,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
614
807
  brainRunId: brainRunId
615
808
  }
616
809
  ];
617
- case 6:
810
+ case 24:
618
811
  _state.sent();
619
812
  // Execute step and yield the STEP_COMPLETE event and
620
813
  // all events from inner brains if any
@@ -622,7 +815,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
622
815
  5,
623
816
  _ts_values(_async_generator_delegate(_async_iterator(this.executeStep(step))))
624
817
  ];
625
- case 7:
818
+ case 25:
626
819
  _state.sent();
627
820
  // Step Status Event
628
821
  return [
@@ -639,14 +832,14 @@ export var BrainEventStream = /*#__PURE__*/ function() {
639
832
  brainRunId: brainRunId
640
833
  }
641
834
  ];
642
- case 8:
835
+ case 26:
643
836
  _state.sent();
644
837
  this.currentStepIndex++;
645
838
  return [
646
839
  3,
647
- 4
840
+ 11
648
841
  ];
649
- case 9:
842
+ case 27:
650
843
  return [
651
844
  4,
652
845
  {
@@ -658,15 +851,15 @@ export var BrainEventStream = /*#__PURE__*/ function() {
658
851
  options: options
659
852
  }
660
853
  ];
661
- case 10:
854
+ case 28:
662
855
  _state.sent();
663
856
  return [
664
857
  3,
665
- 14
858
+ 32
666
859
  ];
667
- case 11:
668
- err = _state.sent();
669
- error = err;
860
+ case 29:
861
+ err1 = _state.sent();
862
+ error = err1;
670
863
  currentStep = steps[this.currentStepIndex];
671
864
  currentStep === null || currentStep === void 0 ? void 0 : currentStep.withStatus(STATUS.ERROR);
672
865
  return [
@@ -685,7 +878,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
685
878
  options: options
686
879
  }
687
880
  ];
688
- case 12:
881
+ case 30:
689
882
  _state.sent();
690
883
  // Step Status Event
691
884
  return [
@@ -702,10 +895,10 @@ export var BrainEventStream = /*#__PURE__*/ function() {
702
895
  brainRunId: brainRunId
703
896
  }
704
897
  ];
705
- case 13:
898
+ case 31:
706
899
  _state.sent();
707
900
  throw error;
708
- case 14:
901
+ case 32:
709
902
  return [
710
903
  2
711
904
  ];
@@ -718,7 +911,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
718
911
  key: "executeStep",
719
912
  value: function executeStep(step) {
720
913
  return _wrap_async_generator(function() {
721
- var block, stepBlock, _this_initialCompletedSteps, brainBlock, initialState, stepIndex, completedStepEntry, innerCompletedSteps, patches, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, completedStep, innerBrainPaused, _this_options, _this_options1, innerRun, _iteratorAbruptCompletion, _didIteratorError1, _iteratorError1, _iterator1, _step1, _value, event, err1, innerState, prevState, _, prevState1, stepBlock1, retries, result, _this_options2, actionPromise, error, _this_options3, serializedWaitFor;
914
+ var block, stepBlock, _this_resumeContext, brainBlock, initialState, innerResumeContext, patches, innerBrainPaused, _this_options, _this_options1, innerRun, _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, _value, event, err, _innerResumeContext_state, baseState, innerState, prevState, _, prevState1, stepBlock1, retries, result, _this_options2, actionPromise, error, _this_options3, serializedWaitFor;
722
915
  return _ts_generator(this, function(_state) {
723
916
  switch(_state.label){
724
917
  case 0:
@@ -748,51 +941,20 @@ export var BrainEventStream = /*#__PURE__*/ function() {
748
941
  ];
749
942
  brainBlock = block;
750
943
  initialState = typeof brainBlock.initialState === 'function' ? brainBlock.initialState(this.currentState) : brainBlock.initialState;
751
- // Check if this inner brain step has completed inner steps (for resume)
752
- stepIndex = this.steps.indexOf(step);
753
- completedStepEntry = (_this_initialCompletedSteps = this.initialCompletedSteps) === null || _this_initialCompletedSteps === void 0 ? void 0 : _this_initialCompletedSteps[stepIndex];
754
- innerCompletedSteps = completedStepEntry === null || completedStepEntry === void 0 ? void 0 : completedStepEntry.innerSteps;
944
+ // Check if we're resuming and if there's an inner resume context
945
+ innerResumeContext = (_this_resumeContext = this.resumeContext) === null || _this_resumeContext === void 0 ? void 0 : _this_resumeContext.innerResumeContext;
755
946
  // Run inner brain and yield all its events
756
947
  // Pass brainRunId so inner brain shares outer brain's run ID
757
- // Pass innerSteps and response for resume scenarios
758
948
  patches = [];
759
- // If resuming, include patches from already-completed inner steps
760
- // These won't be re-emitted as STEP_COMPLETE events
761
- if (innerCompletedSteps) {
762
- _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
763
- try {
764
- for(_iterator = innerCompletedSteps[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
765
- completedStep = _step.value;
766
- if (completedStep.patch) {
767
- patches.push(completedStep.patch);
768
- }
769
- }
770
- } catch (err) {
771
- _didIteratorError = true;
772
- _iteratorError = err;
773
- } finally{
774
- try {
775
- if (!_iteratorNormalCompletion && _iterator.return != null) {
776
- _iterator.return();
777
- }
778
- } finally{
779
- if (_didIteratorError) {
780
- throw _iteratorError;
781
- }
782
- }
783
- }
784
- }
785
949
  innerBrainPaused = false;
786
- innerRun = innerCompletedSteps ? brainBlock.innerBrain.run({
950
+ innerRun = innerResumeContext ? brainBlock.innerBrain.run({
787
951
  resources: this.resources,
788
952
  client: this.client,
789
- initialState: initialState,
790
- initialCompletedSteps: innerCompletedSteps,
953
+ resumeContext: innerResumeContext,
791
954
  options: (_this_options = this.options) !== null && _this_options !== void 0 ? _this_options : {},
792
955
  pages: this.pages,
793
956
  env: this.env,
794
- brainRunId: this.brainRunId,
795
- response: this.currentResponse
957
+ brainRunId: this.brainRunId
796
958
  }) : brainBlock.innerBrain.run({
797
959
  resources: this.resources,
798
960
  client: this.client,
@@ -802,7 +964,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
802
964
  env: this.env,
803
965
  brainRunId: this.brainRunId
804
966
  });
805
- _iteratorAbruptCompletion = false, _didIteratorError1 = false;
967
+ _iteratorAbruptCompletion = false, _didIteratorError = false;
806
968
  _state.label = 3;
807
969
  case 3:
808
970
  _state.trys.push([
@@ -811,19 +973,19 @@ export var BrainEventStream = /*#__PURE__*/ function() {
811
973
  10,
812
974
  15
813
975
  ]);
814
- _iterator1 = _async_iterator(innerRun);
976
+ _iterator = _async_iterator(innerRun);
815
977
  _state.label = 4;
816
978
  case 4:
817
979
  return [
818
980
  4,
819
- _await_async_generator(_iterator1.next())
981
+ _await_async_generator(_iterator.next())
820
982
  ];
821
983
  case 5:
822
- if (!(_iteratorAbruptCompletion = !(_step1 = _state.sent()).done)) return [
984
+ if (!(_iteratorAbruptCompletion = !(_step = _state.sent()).done)) return [
823
985
  3,
824
986
  8
825
987
  ];
826
- _value = _step1.value;
988
+ _value = _step.value;
827
989
  event = _value;
828
990
  return [
829
991
  4,
@@ -858,9 +1020,9 @@ export var BrainEventStream = /*#__PURE__*/ function() {
858
1020
  15
859
1021
  ];
860
1022
  case 9:
861
- err1 = _state.sent();
862
- _didIteratorError1 = true;
863
- _iteratorError1 = err1;
1023
+ err = _state.sent();
1024
+ _didIteratorError = true;
1025
+ _iteratorError = err;
864
1026
  return [
865
1027
  3,
866
1028
  15
@@ -872,13 +1034,13 @@ export var BrainEventStream = /*#__PURE__*/ function() {
872
1034
  13,
873
1035
  14
874
1036
  ]);
875
- if (!(_iteratorAbruptCompletion && _iterator1.return != null)) return [
1037
+ if (!(_iteratorAbruptCompletion && _iterator.return != null)) return [
876
1038
  3,
877
1039
  12
878
1040
  ];
879
1041
  return [
880
1042
  4,
881
- _await_async_generator(_iterator1.return())
1043
+ _await_async_generator(_iterator.return())
882
1044
  ];
883
1045
  case 11:
884
1046
  _state.sent();
@@ -889,8 +1051,8 @@ export var BrainEventStream = /*#__PURE__*/ function() {
889
1051
  14
890
1052
  ];
891
1053
  case 13:
892
- if (_didIteratorError1) {
893
- throw _iteratorError1;
1054
+ if (_didIteratorError) {
1055
+ throw _iteratorError;
894
1056
  }
895
1057
  return [
896
1058
  7
@@ -908,7 +1070,9 @@ export var BrainEventStream = /*#__PURE__*/ function() {
908
1070
  ];
909
1071
  }
910
1072
  // Apply collected patches to get final inner state
911
- innerState = applyPatches(initialState, patches);
1073
+ // When resuming, use the resumed state as base; otherwise use initialState
1074
+ baseState = (_innerResumeContext_state = innerResumeContext === null || innerResumeContext === void 0 ? void 0 : innerResumeContext.state) !== null && _innerResumeContext_state !== void 0 ? _innerResumeContext_state : initialState;
1075
+ innerState = applyPatches(baseState, patches);
912
1076
  // Get previous state before action
913
1077
  prevState = this.currentState;
914
1078
  // Update state with inner brain results
@@ -972,7 +1136,8 @@ export var BrainEventStream = /*#__PURE__*/ function() {
972
1136
  response: this.currentResponse,
973
1137
  page: this.currentPage,
974
1138
  pages: this.pages,
975
- env: this.env
1139
+ env: this.env,
1140
+ memory: this.scopedMemory
976
1141
  }, this.services)));
977
1142
  return [
978
1143
  4,
@@ -1082,7 +1247,7 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1082
1247
  key: "executeAgent",
1083
1248
  value: function executeAgent(step) {
1084
1249
  return _wrap_async_generator(function() {
1085
- var block, prevState, _this_defaultTools, defaultTools, _this_components, components, _this_options, config, _config_tools, mergedTools, messages, resumeContext, _this_options1, _this_options2, _config_prompt, prompt, _this_options3, totalTokens, iteration, _this_options4, toolsForClient, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, _step_value, name, toolDef, tool, systemPrompt, response, _this_options5, _this_options6, _iteratorNormalCompletion1, _didIteratorError1, _iteratorError1, _iterator1, _step1, toolCall, _this_options7, tool1, _this_options8, toolResult, waitForResult, webhooks, _this_options9, _this_options10, _this_options11, err;
1250
+ var _this_resumeContext, _this_resumeContext1, block, prevState, _this_defaultTools, defaultTools, _this_components, components, _this_options, config, _config_tools, mergedTools, _config_outputSchema, schema, name, responseMessages, initialMessages, agentContext, webhookResponse, _agentContext_stepId, effectiveStepId, _this_options1, _this_options2, userMessage, toolResultMessage, _this_options3, userMessage1, _config_prompt, prompt, _this_options4, totalTokens, iteration, _config_maxIterations, maxIterations, _response_responseMessages, signals, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, signal, userMessage2, _this_options5, err, _this_options6, toolsForClient, _iteratorNormalCompletion1, _didIteratorError1, _iteratorError1, _iterator1, _step1, _step_value, name1, toolDef, tool, description, componentList, systemPrompt, response, newAssistantMessage, _this_options7, tokensThisIteration, _this_options8, _this_options9, _this_options10, pendingWebhook, _iteratorNormalCompletion2, _didIteratorError2, _iteratorError2, _iterator2, _step2, toolCall, _this_options11, tool1, _this_options12, _this_options13, toolContext, toolResult, waitForResult, webhooks, _this_options14, placeholderMessage, _this_options15, toolResultMessage1, _this_options16, err, _this_options17, _this_options18;
1086
1251
  return _ts_generator(this, function(_state) {
1087
1252
  switch(_state.label){
1088
1253
  case 0:
@@ -1103,7 +1268,8 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1103
1268
  response: this.currentResponse,
1104
1269
  page: this.currentPage,
1105
1270
  pages: this.pages,
1106
- env: this.env
1271
+ env: this.env,
1272
+ memory: this.scopedMemory
1107
1273
  }, this.services)))
1108
1274
  ];
1109
1275
  case 1:
@@ -1112,17 +1278,43 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1112
1278
  this.currentPage = undefined;
1113
1279
  // Merge tools: step tools override defaults
1114
1280
  mergedTools = _object_spread({}, defaultTools, (_config_tools = config.tools) !== null && _config_tools !== void 0 ? _config_tools : {});
1115
- if (!this.agentResumeContext) return [
1281
+ // Always generate a 'done' terminal tool for every agent
1282
+ // If outputSchema is provided, use that schema; otherwise use defaultDoneSchema
1283
+ if (config.outputSchema) {
1284
+ _config_outputSchema = config.outputSchema, schema = _config_outputSchema.schema, name = _config_outputSchema.name;
1285
+ mergedTools['done'] = {
1286
+ 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),
1287
+ inputSchema: schema,
1288
+ terminal: true
1289
+ };
1290
+ } else {
1291
+ mergedTools['done'] = {
1292
+ 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.",
1293
+ inputSchema: defaultDoneSchema,
1294
+ terminal: true
1295
+ };
1296
+ }
1297
+ // Check if we're resuming from a previous agent execution
1298
+ agentContext = (_this_resumeContext = this.resumeContext) === null || _this_resumeContext === void 0 ? void 0 : _this_resumeContext.agentContext;
1299
+ webhookResponse = (_this_resumeContext1 = this.resumeContext) === null || _this_resumeContext1 === void 0 ? void 0 : _this_resumeContext1.webhookResponse;
1300
+ // Use preserved stepId from agentContext when resuming, or step.id for fresh start
1301
+ // This ensures all events for the same agent use the same stepId across resumes
1302
+ effectiveStepId = (_agentContext_stepId = agentContext === null || agentContext === void 0 ? void 0 : agentContext.stepId) !== null && _agentContext_stepId !== void 0 ? _agentContext_stepId : step.id;
1303
+ if (!agentContext) return [
1116
1304
  3,
1117
- 4
1305
+ 9
1118
1306
  ];
1119
- resumeContext = this.agentResumeContext;
1307
+ if (!(webhookResponse && agentContext.pendingToolCallId && agentContext.pendingToolName)) return [
1308
+ 3,
1309
+ 7
1310
+ ];
1311
+ // WEBHOOK RESUME: Agent was waiting for a webhook response
1120
1312
  // Emit WEBHOOK_RESPONSE event to record the response
1121
1313
  return [
1122
1314
  4,
1123
1315
  {
1124
1316
  type: BRAIN_EVENTS.WEBHOOK_RESPONSE,
1125
- response: resumeContext.webhookResponse,
1317
+ response: webhookResponse,
1126
1318
  options: (_this_options1 = this.options) !== null && _this_options1 !== void 0 ? _this_options1 : {},
1127
1319
  brainRunId: this.brainRunId
1128
1320
  }
@@ -1135,25 +1327,86 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1135
1327
  {
1136
1328
  type: BRAIN_EVENTS.AGENT_TOOL_RESULT,
1137
1329
  stepTitle: step.block.title,
1138
- stepId: step.id,
1139
- toolCallId: resumeContext.pendingToolCallId,
1140
- toolName: resumeContext.pendingToolName,
1141
- result: resumeContext.webhookResponse,
1330
+ stepId: effectiveStepId,
1331
+ toolCallId: agentContext.pendingToolCallId,
1332
+ toolName: agentContext.pendingToolName,
1333
+ result: webhookResponse,
1142
1334
  options: (_this_options2 = this.options) !== null && _this_options2 !== void 0 ? _this_options2 : {},
1143
1335
  brainRunId: this.brainRunId
1144
1336
  }
1145
1337
  ];
1146
1338
  case 3:
1147
1339
  _state.sent();
1148
- // Use restored messages from the resume context
1149
- messages = resumeContext.messages;
1150
- // Clear the context so it's only used once
1151
- this.agentResumeContext = undefined;
1340
+ // Use restored responseMessages from the agent context (preserves providerOptions)
1341
+ // Prepend the user message and append the webhook response
1342
+ // Note: reconstructed messages don't include the placeholder (we don't emit events for it),
1343
+ // so we just append the real webhook response here.
1344
+ userMessage = {
1345
+ role: 'user',
1346
+ content: agentContext.prompt
1347
+ };
1348
+ if (!this.client.createToolResultMessage) return [
1349
+ 3,
1350
+ 5
1351
+ ];
1352
+ toolResultMessage = this.client.createToolResultMessage(agentContext.pendingToolCallId, agentContext.pendingToolName, webhookResponse);
1353
+ responseMessages = [
1354
+ userMessage
1355
+ ].concat(_to_consumable_array(agentContext.responseMessages), [
1356
+ toolResultMessage
1357
+ ]);
1358
+ // Emit event for this tool result message (for reconstruction if there's another pause)
1359
+ return [
1360
+ 4,
1361
+ {
1362
+ type: BRAIN_EVENTS.AGENT_RAW_RESPONSE_MESSAGE,
1363
+ stepTitle: step.block.title,
1364
+ stepId: effectiveStepId,
1365
+ iteration: 0,
1366
+ message: toolResultMessage,
1367
+ options: (_this_options3 = this.options) !== null && _this_options3 !== void 0 ? _this_options3 : {},
1368
+ brainRunId: this.brainRunId
1369
+ }
1370
+ ];
1371
+ case 4:
1372
+ _state.sent();
1152
1373
  return [
1153
1374
  3,
1154
1375
  6
1155
1376
  ];
1156
- case 4:
1377
+ case 5:
1378
+ // Fallback if client doesn't support createToolResultMessage
1379
+ responseMessages = [
1380
+ userMessage
1381
+ ].concat(_to_consumable_array(agentContext.responseMessages));
1382
+ _state.label = 6;
1383
+ case 6:
1384
+ // Set empty initial messages since user message is in responseMessages
1385
+ initialMessages = [];
1386
+ return [
1387
+ 3,
1388
+ 8
1389
+ ];
1390
+ case 7:
1391
+ // PAUSE RESUME: Agent was paused mid-execution (no pending webhook)
1392
+ // Restore conversation history and continue from where we left off
1393
+ userMessage1 = {
1394
+ role: 'user',
1395
+ content: agentContext.prompt
1396
+ };
1397
+ responseMessages = [
1398
+ userMessage1
1399
+ ].concat(_to_consumable_array(agentContext.responseMessages));
1400
+ initialMessages = [];
1401
+ _state.label = 8;
1402
+ case 8:
1403
+ // Clear the resume context so it's only used once
1404
+ this.resumeContext = undefined;
1405
+ return [
1406
+ 3,
1407
+ 11
1408
+ ];
1409
+ case 9:
1157
1410
  // Use "Begin." as default prompt if not provided
1158
1411
  prompt = (_config_prompt = config.prompt) !== null && _config_prompt !== void 0 ? _config_prompt : 'Begin.';
1159
1412
  // Emit agent start event (only for fresh starts)
@@ -1162,75 +1415,255 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1162
1415
  {
1163
1416
  type: BRAIN_EVENTS.AGENT_START,
1164
1417
  stepTitle: step.block.title,
1165
- stepId: step.id,
1418
+ stepId: effectiveStepId,
1166
1419
  prompt: prompt,
1167
1420
  system: config.system,
1168
- options: (_this_options3 = this.options) !== null && _this_options3 !== void 0 ? _this_options3 : {},
1421
+ tools: Object.keys(mergedTools),
1422
+ options: (_this_options4 = this.options) !== null && _this_options4 !== void 0 ? _this_options4 : {},
1169
1423
  brainRunId: this.brainRunId
1170
1424
  }
1171
1425
  ];
1172
- case 5:
1426
+ case 10:
1173
1427
  _state.sent();
1174
1428
  // Initialize messages for fresh start
1175
- messages = [
1429
+ initialMessages = [
1176
1430
  {
1177
1431
  role: 'user',
1178
1432
  content: prompt
1179
1433
  }
1180
1434
  ];
1181
- _state.label = 6;
1182
- case 6:
1435
+ _state.label = 11;
1436
+ case 11:
1183
1437
  // Initialize token tracking
1184
1438
  totalTokens = 0;
1185
1439
  iteration = 0;
1186
- _state.label = 7;
1187
- case 7:
1440
+ maxIterations = (_config_maxIterations = config.maxIterations) !== null && _config_maxIterations !== void 0 ? _config_maxIterations : 100;
1441
+ _state.label = 12;
1442
+ case 12:
1188
1443
  if (!true) return [
1189
1444
  3,
1190
- 33
1445
+ 60
1191
1446
  ];
1192
1447
  iteration++;
1193
- // Emit iteration event
1448
+ if (!this.signalProvider) return [
1449
+ 3,
1450
+ 26
1451
+ ];
1194
1452
  return [
1195
1453
  4,
1196
- {
1197
- type: BRAIN_EVENTS.AGENT_ITERATION,
1198
- stepTitle: step.block.title,
1199
- stepId: step.id,
1200
- iteration: iteration,
1201
- options: (_this_options4 = this.options) !== null && _this_options4 !== void 0 ? _this_options4 : {},
1202
- brainRunId: this.brainRunId
1454
+ _await_async_generator(this.signalProvider.getSignals('ALL'))
1455
+ ];
1456
+ case 13:
1457
+ signals = _state.sent();
1458
+ _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1459
+ _state.label = 14;
1460
+ case 14:
1461
+ _state.trys.push([
1462
+ 14,
1463
+ 24,
1464
+ 25,
1465
+ 26
1466
+ ]);
1467
+ _iterator = signals[Symbol.iterator]();
1468
+ _state.label = 15;
1469
+ case 15:
1470
+ if (!!(_iteratorNormalCompletion = (_step = _iterator.next()).done)) return [
1471
+ 3,
1472
+ 23
1473
+ ];
1474
+ signal = _step.value;
1475
+ if (!(signal.type === 'KILL')) return [
1476
+ 3,
1477
+ 17
1478
+ ];
1479
+ return [
1480
+ 4,
1481
+ {
1482
+ type: BRAIN_EVENTS.CANCELLED,
1483
+ status: STATUS.CANCELLED,
1484
+ brainTitle: this.title,
1485
+ brainDescription: this.description,
1486
+ brainRunId: this.brainRunId,
1487
+ options: this.options
1203
1488
  }
1204
1489
  ];
1205
- case 8:
1490
+ case 16:
1491
+ _state.sent();
1492
+ return [
1493
+ 2
1494
+ ];
1495
+ case 17:
1496
+ if (!(signal.type === 'PAUSE')) return [
1497
+ 3,
1498
+ 19
1499
+ ];
1500
+ return [
1501
+ 4,
1502
+ {
1503
+ type: BRAIN_EVENTS.PAUSED,
1504
+ status: STATUS.PAUSED,
1505
+ brainTitle: this.title,
1506
+ brainDescription: this.description,
1507
+ brainRunId: this.brainRunId,
1508
+ options: this.options
1509
+ }
1510
+ ];
1511
+ case 18:
1512
+ _state.sent();
1513
+ return [
1514
+ 2
1515
+ ];
1516
+ case 19:
1517
+ if (!(signal.type === 'USER_MESSAGE')) return [
1518
+ 3,
1519
+ 22
1520
+ ];
1521
+ // Emit event for user message injection
1522
+ return [
1523
+ 4,
1524
+ {
1525
+ type: BRAIN_EVENTS.AGENT_USER_MESSAGE,
1526
+ stepTitle: step.block.title,
1527
+ stepId: effectiveStepId,
1528
+ content: signal.content,
1529
+ options: this.options,
1530
+ brainRunId: this.brainRunId
1531
+ }
1532
+ ];
1533
+ case 20:
1534
+ _state.sent();
1535
+ // Inject as user message into conversation
1536
+ userMessage2 = {
1537
+ role: 'user',
1538
+ content: signal.content
1539
+ };
1540
+ if (responseMessages) {
1541
+ responseMessages = _to_consumable_array(responseMessages).concat([
1542
+ userMessage2
1543
+ ]);
1544
+ } else {
1545
+ initialMessages = _to_consumable_array(initialMessages).concat([
1546
+ {
1547
+ role: 'user',
1548
+ content: signal.content
1549
+ }
1550
+ ]);
1551
+ }
1552
+ // Emit raw response message event so it shows up in agent chat view
1553
+ return [
1554
+ 4,
1555
+ {
1556
+ type: BRAIN_EVENTS.AGENT_RAW_RESPONSE_MESSAGE,
1557
+ stepTitle: step.block.title,
1558
+ stepId: effectiveStepId,
1559
+ iteration: iteration,
1560
+ message: userMessage2,
1561
+ options: (_this_options5 = this.options) !== null && _this_options5 !== void 0 ? _this_options5 : {},
1562
+ brainRunId: this.brainRunId
1563
+ }
1564
+ ];
1565
+ case 21:
1566
+ _state.sent();
1567
+ _state.label = 22;
1568
+ case 22:
1569
+ _iteratorNormalCompletion = true;
1570
+ return [
1571
+ 3,
1572
+ 15
1573
+ ];
1574
+ case 23:
1575
+ return [
1576
+ 3,
1577
+ 26
1578
+ ];
1579
+ case 24:
1580
+ err = _state.sent();
1581
+ _didIteratorError = true;
1582
+ _iteratorError = err;
1583
+ return [
1584
+ 3,
1585
+ 26
1586
+ ];
1587
+ case 25:
1588
+ try {
1589
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
1590
+ _iterator.return();
1591
+ }
1592
+ } finally{
1593
+ if (_didIteratorError) {
1594
+ throw _iteratorError;
1595
+ }
1596
+ }
1597
+ return [
1598
+ 7
1599
+ ];
1600
+ case 26:
1601
+ if (!(iteration > maxIterations)) return [
1602
+ 3,
1603
+ 29
1604
+ ];
1605
+ return [
1606
+ 4,
1607
+ {
1608
+ type: BRAIN_EVENTS.AGENT_ITERATION_LIMIT,
1609
+ stepTitle: step.block.title,
1610
+ stepId: effectiveStepId,
1611
+ iteration: iteration - 1,
1612
+ maxIterations: maxIterations,
1613
+ totalTokens: totalTokens,
1614
+ options: (_this_options6 = this.options) !== null && _this_options6 !== void 0 ? _this_options6 : {},
1615
+ brainRunId: this.brainRunId
1616
+ }
1617
+ ];
1618
+ case 27:
1619
+ _state.sent();
1620
+ return [
1621
+ 5,
1622
+ _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState))))
1623
+ ];
1624
+ case 28:
1206
1625
  _state.sent();
1626
+ return [
1627
+ 2
1628
+ ];
1629
+ case 29:
1207
1630
  // Check if client supports generateText
1208
1631
  if (!this.client.generateText) {
1209
1632
  throw new Error('Client does not support generateText. Use a client that implements generateText for agent steps.');
1210
1633
  }
1211
1634
  // Build tools object for the client (description and inputSchema only)
1212
1635
  toolsForClient = {};
1213
- _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1636
+ _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
1214
1637
  try {
1215
- for(_iterator = Object.entries(mergedTools)[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1216
- _step_value = _sliced_to_array(_step.value, 2), name = _step_value[0], toolDef = _step_value[1];
1638
+ for(_iterator1 = Object.entries(mergedTools)[Symbol.iterator](); !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){
1639
+ _step_value = _sliced_to_array(_step1.value, 2), name1 = _step_value[0], toolDef = _step_value[1];
1217
1640
  tool = toolDef;
1218
- toolsForClient[name] = {
1219
- description: tool.description,
1641
+ description = tool.description;
1642
+ // Enrich generateUI description with available component information
1643
+ if (name1 === 'generateUI' && components && Object.keys(components).length > 0) {
1644
+ componentList = Object.entries(components).map(function(param) {
1645
+ var _param = _sliced_to_array(param, 2), compName = _param[0], comp = _param[1];
1646
+ var desc = comp.description.split('\n')[0]; // First line only
1647
+ return "- ".concat(compName, ": ").concat(desc);
1648
+ }).join('\n');
1649
+ 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 } | null }\n- url: The page URL\n- webhook: For forms (hasForm=true), contains slug and identifier that can 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.");
1650
+ }
1651
+ toolsForClient[name1] = {
1652
+ description: description,
1220
1653
  inputSchema: tool.inputSchema
1221
1654
  };
1222
1655
  }
1223
1656
  } catch (err) {
1224
- _didIteratorError = true;
1225
- _iteratorError = err;
1657
+ _didIteratorError1 = true;
1658
+ _iteratorError1 = err;
1226
1659
  } finally{
1227
1660
  try {
1228
- if (!_iteratorNormalCompletion && _iterator.return != null) {
1229
- _iterator.return();
1661
+ if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
1662
+ _iterator1.return();
1230
1663
  }
1231
1664
  } finally{
1232
- if (_didIteratorError) {
1233
- throw _iteratorError;
1665
+ if (_didIteratorError1) {
1666
+ throw _iteratorError1;
1234
1667
  }
1235
1668
  }
1236
1669
  }
@@ -1240,110 +1673,153 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1240
1673
  4,
1241
1674
  _await_async_generator(this.client.generateText({
1242
1675
  system: systemPrompt,
1243
- messages: messages,
1676
+ messages: initialMessages,
1677
+ responseMessages: responseMessages,
1244
1678
  tools: toolsForClient
1245
1679
  }))
1246
1680
  ];
1247
- case 9:
1681
+ case 30:
1248
1682
  response = _state.sent();
1683
+ // Update responseMessages for next iteration (preserves providerOptions)
1684
+ responseMessages = response.responseMessages;
1685
+ // Get the new assistant message (the last one added by generateText)
1686
+ newAssistantMessage = (_response_responseMessages = response.responseMessages) === null || _response_responseMessages === void 0 ? void 0 : _response_responseMessages.at(-1);
1687
+ if (!newAssistantMessage) return [
1688
+ 3,
1689
+ 32
1690
+ ];
1691
+ return [
1692
+ 4,
1693
+ {
1694
+ type: BRAIN_EVENTS.AGENT_RAW_RESPONSE_MESSAGE,
1695
+ stepTitle: step.block.title,
1696
+ stepId: effectiveStepId,
1697
+ iteration: iteration,
1698
+ message: newAssistantMessage,
1699
+ options: (_this_options7 = this.options) !== null && _this_options7 !== void 0 ? _this_options7 : {},
1700
+ brainRunId: this.brainRunId
1701
+ }
1702
+ ];
1703
+ case 31:
1704
+ _state.sent();
1705
+ _state.label = 32;
1706
+ case 32:
1249
1707
  // Track tokens
1250
- totalTokens += response.usage.totalTokens;
1708
+ tokensThisIteration = response.usage.totalTokens;
1709
+ totalTokens += tokensThisIteration;
1710
+ // Emit iteration event (after LLM call so we have token info)
1711
+ return [
1712
+ 4,
1713
+ {
1714
+ type: BRAIN_EVENTS.AGENT_ITERATION,
1715
+ stepTitle: step.block.title,
1716
+ stepId: effectiveStepId,
1717
+ iteration: iteration,
1718
+ tokensThisIteration: tokensThisIteration,
1719
+ totalTokens: totalTokens,
1720
+ options: (_this_options8 = this.options) !== null && _this_options8 !== void 0 ? _this_options8 : {},
1721
+ brainRunId: this.brainRunId
1722
+ }
1723
+ ];
1724
+ case 33:
1725
+ _state.sent();
1251
1726
  if (!(config.maxTokens && totalTokens > config.maxTokens)) return [
1252
1727
  3,
1253
- 12
1728
+ 36
1254
1729
  ];
1255
1730
  return [
1256
1731
  4,
1257
1732
  {
1258
1733
  type: BRAIN_EVENTS.AGENT_TOKEN_LIMIT,
1259
1734
  stepTitle: step.block.title,
1260
- stepId: step.id,
1735
+ stepId: effectiveStepId,
1261
1736
  totalTokens: totalTokens,
1262
1737
  maxTokens: config.maxTokens,
1263
- options: (_this_options5 = this.options) !== null && _this_options5 !== void 0 ? _this_options5 : {},
1738
+ options: (_this_options9 = this.options) !== null && _this_options9 !== void 0 ? _this_options9 : {},
1264
1739
  brainRunId: this.brainRunId
1265
1740
  }
1266
1741
  ];
1267
- case 10:
1742
+ case 34:
1268
1743
  _state.sent();
1269
1744
  return [
1270
1745
  5,
1271
1746
  _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState))))
1272
1747
  ];
1273
- case 11:
1748
+ case 35:
1274
1749
  _state.sent();
1275
1750
  return [
1276
1751
  2
1277
1752
  ];
1278
- case 12:
1753
+ case 36:
1279
1754
  if (!response.text) return [
1280
1755
  3,
1281
- 14
1756
+ 38
1282
1757
  ];
1758
+ // Log assistant messages to console as fallback (users shouldn't rely on this)
1759
+ console.log("[Assistant] ".concat(response.text));
1283
1760
  return [
1284
1761
  4,
1285
1762
  {
1286
1763
  type: BRAIN_EVENTS.AGENT_ASSISTANT_MESSAGE,
1287
1764
  stepTitle: step.block.title,
1288
- stepId: step.id,
1765
+ stepId: effectiveStepId,
1289
1766
  content: response.text,
1290
- options: (_this_options6 = this.options) !== null && _this_options6 !== void 0 ? _this_options6 : {},
1767
+ options: (_this_options10 = this.options) !== null && _this_options10 !== void 0 ? _this_options10 : {},
1291
1768
  brainRunId: this.brainRunId
1292
1769
  }
1293
1770
  ];
1294
- case 13:
1771
+ case 37:
1295
1772
  _state.sent();
1296
- messages.push({
1297
- role: 'assistant',
1298
- content: response.text
1299
- });
1300
- _state.label = 14;
1301
- case 14:
1773
+ _state.label = 38;
1774
+ case 38:
1302
1775
  if (!(!response.toolCalls || response.toolCalls.length === 0)) return [
1303
1776
  3,
1304
- 16
1777
+ 40
1305
1778
  ];
1306
1779
  return [
1307
1780
  5,
1308
1781
  _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState))))
1309
1782
  ];
1310
- case 15:
1783
+ case 39:
1311
1784
  _state.sent();
1312
1785
  return [
1313
1786
  2
1314
1787
  ];
1315
- case 16:
1316
- _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
1317
- _state.label = 17;
1318
- case 17:
1788
+ case 40:
1789
+ // Track pending webhook if any tool returns waitFor
1790
+ // We process ALL tool calls first, then pause for webhook at the end
1791
+ pendingWebhook = null;
1792
+ _iteratorNormalCompletion2 = true, _didIteratorError2 = false, _iteratorError2 = undefined;
1793
+ _state.label = 41;
1794
+ case 41:
1319
1795
  _state.trys.push([
1320
- 17,
1321
- 30,
1322
- 31,
1323
- 32
1796
+ 41,
1797
+ 54,
1798
+ 55,
1799
+ 56
1324
1800
  ]);
1325
- _iterator1 = response.toolCalls[Symbol.iterator]();
1326
- _state.label = 18;
1327
- case 18:
1328
- if (!!(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done)) return [
1801
+ _iterator2 = response.toolCalls[Symbol.iterator]();
1802
+ _state.label = 42;
1803
+ case 42:
1804
+ if (!!(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done)) return [
1329
1805
  3,
1330
- 29
1806
+ 53
1331
1807
  ];
1332
- toolCall = _step1.value;
1808
+ toolCall = _step2.value;
1333
1809
  return [
1334
1810
  4,
1335
1811
  {
1336
1812
  type: BRAIN_EVENTS.AGENT_TOOL_CALL,
1337
1813
  stepTitle: step.block.title,
1338
- stepId: step.id,
1814
+ stepId: effectiveStepId,
1339
1815
  toolName: toolCall.toolName,
1340
1816
  toolCallId: toolCall.toolCallId,
1341
1817
  input: toolCall.args,
1342
- options: (_this_options7 = this.options) !== null && _this_options7 !== void 0 ? _this_options7 : {},
1818
+ options: (_this_options11 = this.options) !== null && _this_options11 !== void 0 ? _this_options11 : {},
1343
1819
  brainRunId: this.brainRunId
1344
1820
  }
1345
1821
  ];
1346
- case 19:
1822
+ case 43:
1347
1823
  _state.sent();
1348
1824
  tool1 = mergedTools[toolCall.toolName];
1349
1825
  if (!tool1) {
@@ -1351,152 +1827,241 @@ export var BrainEventStream = /*#__PURE__*/ function() {
1351
1827
  }
1352
1828
  if (!tool1.terminal) return [
1353
1829
  3,
1354
- 22
1830
+ 46
1355
1831
  ];
1356
1832
  return [
1357
1833
  4,
1358
1834
  {
1359
1835
  type: BRAIN_EVENTS.AGENT_COMPLETE,
1360
1836
  stepTitle: step.block.title,
1361
- stepId: step.id,
1837
+ stepId: effectiveStepId,
1362
1838
  terminalToolName: toolCall.toolName,
1363
1839
  result: toolCall.args,
1364
1840
  totalIterations: iteration,
1365
- options: (_this_options8 = this.options) !== null && _this_options8 !== void 0 ? _this_options8 : {},
1841
+ totalTokens: totalTokens,
1842
+ options: (_this_options12 = this.options) !== null && _this_options12 !== void 0 ? _this_options12 : {},
1366
1843
  brainRunId: this.brainRunId
1367
1844
  }
1368
1845
  ];
1369
- case 20:
1846
+ case 44:
1370
1847
  _state.sent();
1371
1848
  // Merge terminal result into state
1372
- this.currentState = _object_spread({}, this.currentState, toolCall.args);
1849
+ // Only namespace under outputSchema.name when 'done' tool is called with outputSchema
1850
+ if (config.outputSchema && toolCall.toolName === 'done') {
1851
+ // Namespace result under outputSchema.name
1852
+ this.currentState = _object_spread_props(_object_spread({}, this.currentState), _define_property({}, config.outputSchema.name, toolCall.args));
1853
+ } else {
1854
+ // Default behavior: spread into state root (for other terminal tools)
1855
+ this.currentState = _object_spread({}, this.currentState, toolCall.args);
1856
+ }
1373
1857
  return [
1374
1858
  5,
1375
1859
  _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState))))
1376
1860
  ];
1377
- case 21:
1861
+ case 45:
1378
1862
  _state.sent();
1379
1863
  return [
1380
1864
  2
1381
1865
  ];
1382
- case 22:
1866
+ case 46:
1383
1867
  if (!tool1.execute) return [
1384
1868
  3,
1385
- 28
1869
+ 52
1386
1870
  ];
1871
+ toolContext = {
1872
+ state: this.currentState,
1873
+ options: (_this_options13 = this.options) !== null && _this_options13 !== void 0 ? _this_options13 : {},
1874
+ client: this.client,
1875
+ resources: this.resources,
1876
+ response: this.currentResponse,
1877
+ page: this.currentPage,
1878
+ pages: this.pages,
1879
+ env: this.env,
1880
+ components: this.components,
1881
+ brainRunId: this.brainRunId,
1882
+ stepId: effectiveStepId,
1883
+ memory: this.scopedMemory
1884
+ };
1387
1885
  return [
1388
1886
  4,
1389
- _await_async_generator(tool1.execute(toolCall.args))
1887
+ _await_async_generator(tool1.execute(toolCall.args, toolContext))
1390
1888
  ];
1391
- case 23:
1889
+ case 47:
1392
1890
  toolResult = _state.sent();
1393
1891
  if (!(toolResult && (typeof toolResult === "undefined" ? "undefined" : _type_of(toolResult)) === 'object' && 'waitFor' in toolResult)) return [
1394
1892
  3,
1395
- 26
1893
+ 49
1396
1894
  ];
1397
1895
  waitForResult = toolResult;
1398
1896
  // Normalize waitFor to array (supports single or multiple webhooks)
1399
1897
  webhooks = Array.isArray(waitForResult.waitFor) ? waitForResult.waitFor : [
1400
1898
  waitForResult.waitFor
1401
1899
  ];
1402
- // Emit agent webhook event first (captures pending tool context)
1900
+ // Store webhook info - we'll emit the events after processing all tool calls
1901
+ // This ensures all other tool results are processed before pausing
1902
+ pendingWebhook = {
1903
+ toolCallId: toolCall.toolCallId,
1904
+ toolName: toolCall.toolName,
1905
+ input: toolCall.args,
1906
+ webhooks: webhooks.map(function(w) {
1907
+ return {
1908
+ slug: w.slug,
1909
+ identifier: w.identifier
1910
+ };
1911
+ })
1912
+ };
1913
+ // Emit tool result event for debugging/visibility (with pending status)
1403
1914
  return [
1404
1915
  4,
1405
1916
  {
1406
- type: BRAIN_EVENTS.AGENT_WEBHOOK,
1917
+ type: BRAIN_EVENTS.AGENT_TOOL_RESULT,
1407
1918
  stepTitle: step.block.title,
1408
- stepId: step.id,
1409
- toolCallId: toolCall.toolCallId,
1919
+ stepId: effectiveStepId,
1410
1920
  toolName: toolCall.toolName,
1411
- input: toolCall.args,
1412
- options: (_this_options9 = this.options) !== null && _this_options9 !== void 0 ? _this_options9 : {},
1921
+ toolCallId: toolCall.toolCallId,
1922
+ result: {
1923
+ status: 'waiting_for_webhook',
1924
+ webhooks: pendingWebhook.webhooks
1925
+ },
1926
+ options: (_this_options14 = this.options) !== null && _this_options14 !== void 0 ? _this_options14 : {},
1413
1927
  brainRunId: this.brainRunId
1414
1928
  }
1415
1929
  ];
1416
- case 24:
1930
+ case 48:
1417
1931
  _state.sent();
1418
- // Then emit webhook event with all webhooks (first response wins)
1932
+ // Add placeholder to responseMessages locally so the conversation stays valid
1933
+ // for any subsequent generateText calls in this execution.
1934
+ // We DON'T emit an event for it - on resume, we reconstruct from events
1935
+ // and append the real webhook response.
1936
+ if (this.client.createToolResultMessage && responseMessages) {
1937
+ placeholderMessage = this.client.createToolResultMessage(toolCall.toolCallId, toolCall.toolName, {
1938
+ status: 'waiting_for_webhook',
1939
+ webhooks: pendingWebhook.webhooks
1940
+ });
1941
+ responseMessages = _to_consumable_array(responseMessages).concat([
1942
+ placeholderMessage
1943
+ ]);
1944
+ }
1945
+ // Continue processing other tool calls - don't return yet
1946
+ return [
1947
+ 3,
1948
+ 52
1949
+ ];
1950
+ case 49:
1951
+ // Emit tool result event for debugging/visibility
1419
1952
  return [
1420
1953
  4,
1421
1954
  {
1422
- type: BRAIN_EVENTS.WEBHOOK,
1423
- waitFor: webhooks.map(function(w) {
1424
- return {
1425
- slug: w.slug,
1426
- identifier: w.identifier
1427
- };
1428
- }),
1429
- options: (_this_options10 = this.options) !== null && _this_options10 !== void 0 ? _this_options10 : {},
1955
+ type: BRAIN_EVENTS.AGENT_TOOL_RESULT,
1956
+ stepTitle: step.block.title,
1957
+ stepId: effectiveStepId,
1958
+ toolName: toolCall.toolName,
1959
+ toolCallId: toolCall.toolCallId,
1960
+ result: toolResult,
1961
+ options: (_this_options15 = this.options) !== null && _this_options15 !== void 0 ? _this_options15 : {},
1430
1962
  brainRunId: this.brainRunId
1431
1963
  }
1432
1964
  ];
1433
- case 25:
1965
+ case 50:
1434
1966
  _state.sent();
1435
- return [
1436
- 2
1967
+ if (!(this.client.createToolResultMessage && responseMessages)) return [
1968
+ 3,
1969
+ 52
1437
1970
  ];
1438
- case 26:
1439
- // Normal tool result
1971
+ toolResultMessage1 = this.client.createToolResultMessage(toolCall.toolCallId, toolCall.toolName, toolResult);
1972
+ responseMessages = _to_consumable_array(responseMessages).concat([
1973
+ toolResultMessage1
1974
+ ]);
1975
+ // Emit event for this tool result message
1440
1976
  return [
1441
1977
  4,
1442
1978
  {
1443
- type: BRAIN_EVENTS.AGENT_TOOL_RESULT,
1979
+ type: BRAIN_EVENTS.AGENT_RAW_RESPONSE_MESSAGE,
1444
1980
  stepTitle: step.block.title,
1445
- stepId: step.id,
1446
- toolName: toolCall.toolName,
1447
- toolCallId: toolCall.toolCallId,
1448
- result: toolResult,
1449
- options: (_this_options11 = this.options) !== null && _this_options11 !== void 0 ? _this_options11 : {},
1981
+ stepId: effectiveStepId,
1982
+ iteration: iteration,
1983
+ message: toolResultMessage1,
1984
+ options: (_this_options16 = this.options) !== null && _this_options16 !== void 0 ? _this_options16 : {},
1450
1985
  brainRunId: this.brainRunId
1451
1986
  }
1452
1987
  ];
1453
- case 27:
1988
+ case 51:
1454
1989
  _state.sent();
1455
- messages.push({
1456
- role: 'tool',
1457
- content: JSON.stringify(toolResult),
1458
- toolCallId: toolCall.toolCallId,
1459
- toolName: toolCall.toolName
1460
- });
1461
- _state.label = 28;
1462
- case 28:
1463
- _iteratorNormalCompletion1 = true;
1990
+ _state.label = 52;
1991
+ case 52:
1992
+ _iteratorNormalCompletion2 = true;
1464
1993
  return [
1465
1994
  3,
1466
- 18
1995
+ 42
1467
1996
  ];
1468
- case 29:
1997
+ case 53:
1469
1998
  return [
1470
1999
  3,
1471
- 32
2000
+ 56
1472
2001
  ];
1473
- case 30:
2002
+ case 54:
1474
2003
  err = _state.sent();
1475
- _didIteratorError1 = true;
1476
- _iteratorError1 = err;
2004
+ _didIteratorError2 = true;
2005
+ _iteratorError2 = err;
1477
2006
  return [
1478
2007
  3,
1479
- 32
2008
+ 56
1480
2009
  ];
1481
- case 31:
2010
+ case 55:
1482
2011
  try {
1483
- if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
1484
- _iterator1.return();
2012
+ if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
2013
+ _iterator2.return();
1485
2014
  }
1486
2015
  } finally{
1487
- if (_didIteratorError1) {
1488
- throw _iteratorError1;
2016
+ if (_didIteratorError2) {
2017
+ throw _iteratorError2;
1489
2018
  }
1490
2019
  }
1491
2020
  return [
1492
2021
  7
1493
2022
  ];
1494
- case 32:
2023
+ case 56:
2024
+ if (!pendingWebhook) return [
2025
+ 3,
2026
+ 59
2027
+ ];
2028
+ // Emit AGENT_WEBHOOK event
2029
+ return [
2030
+ 4,
2031
+ {
2032
+ type: BRAIN_EVENTS.AGENT_WEBHOOK,
2033
+ stepTitle: step.block.title,
2034
+ stepId: effectiveStepId,
2035
+ toolCallId: pendingWebhook.toolCallId,
2036
+ toolName: pendingWebhook.toolName,
2037
+ input: pendingWebhook.input,
2038
+ options: (_this_options17 = this.options) !== null && _this_options17 !== void 0 ? _this_options17 : {},
2039
+ brainRunId: this.brainRunId
2040
+ }
2041
+ ];
2042
+ case 57:
2043
+ _state.sent();
2044
+ // Emit WEBHOOK event with all webhooks (first response wins)
2045
+ return [
2046
+ 4,
2047
+ {
2048
+ type: BRAIN_EVENTS.WEBHOOK,
2049
+ waitFor: pendingWebhook.webhooks,
2050
+ options: (_this_options18 = this.options) !== null && _this_options18 !== void 0 ? _this_options18 : {},
2051
+ brainRunId: this.brainRunId
2052
+ }
2053
+ ];
2054
+ case 58:
2055
+ _state.sent();
2056
+ return [
2057
+ 2
2058
+ ];
2059
+ case 59:
1495
2060
  return [
1496
2061
  3,
1497
- 7
2062
+ 12
1498
2063
  ];
1499
- case 33:
2064
+ case 60:
1500
2065
  return [
1501
2066
  2
1502
2067
  ];