@positronic/core 0.0.52 → 0.0.53

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 (96) hide show
  1. package/dist/src/dsl/{loop-messages.js → agent-messages.js} +21 -21
  2. package/dist/src/dsl/brain-runner.js +6 -6
  3. package/dist/src/dsl/brain-state-machine.js +2 -2
  4. package/dist/src/dsl/brain.js +5 -1912
  5. package/dist/src/dsl/builder/brain.js +944 -0
  6. package/dist/src/dsl/builder/step.js +75 -0
  7. package/dist/src/dsl/constants.js +9 -10
  8. package/dist/src/dsl/create-brain.js +63 -0
  9. package/dist/src/dsl/definitions/blocks.js +1 -0
  10. package/dist/src/dsl/definitions/brain-types.js +4 -0
  11. package/dist/src/dsl/definitions/events.js +2 -0
  12. package/dist/src/dsl/definitions/run-params.js +1 -0
  13. package/dist/src/dsl/definitions/steps.js +2 -0
  14. package/dist/src/dsl/execution/constants.js +14 -0
  15. package/dist/src/dsl/execution/event-stream.js +1638 -0
  16. package/dist/src/dsl/execution/retry.js +298 -0
  17. package/dist/src/dsl/types.js +2 -2
  18. package/dist/src/index.js +5 -3
  19. package/dist/src/tools/index.js +181 -0
  20. package/dist/src/ui/component-utils.js +107 -0
  21. package/dist/src/ui/generate-page-html.js +36 -0
  22. package/dist/src/ui/generate-ui.js +601 -0
  23. package/dist/src/ui/types.js +165 -0
  24. package/dist/src/ui/validate-form.js +428 -0
  25. package/dist/src/yaml/data-validator.js +302 -0
  26. package/dist/src/yaml/index.js +9 -0
  27. package/dist/src/yaml/parser.js +224 -0
  28. package/dist/src/yaml/schema-extractor.js +330 -0
  29. package/dist/src/yaml/type-inference.js +210 -0
  30. package/dist/src/yaml/types.js +12 -0
  31. package/dist/types/clients/types.d.ts +42 -0
  32. package/dist/types/clients/types.d.ts.map +1 -1
  33. package/dist/types/dsl/agent-messages.d.ts +18 -0
  34. package/dist/types/dsl/agent-messages.d.ts.map +1 -0
  35. package/dist/types/dsl/brain-runner.d.ts +2 -2
  36. package/dist/types/dsl/brain-runner.d.ts.map +1 -1
  37. package/dist/types/dsl/brain-state-machine.d.ts.map +1 -1
  38. package/dist/types/dsl/brain.d.ts +7 -273
  39. package/dist/types/dsl/brain.d.ts.map +1 -1
  40. package/dist/types/dsl/builder/brain.d.ts +200 -0
  41. package/dist/types/dsl/builder/brain.d.ts.map +1 -0
  42. package/dist/types/dsl/builder/step.d.ts +15 -0
  43. package/dist/types/dsl/builder/step.d.ts.map +1 -0
  44. package/dist/types/dsl/constants.d.ts +8 -9
  45. package/dist/types/dsl/constants.d.ts.map +1 -1
  46. package/dist/types/dsl/create-brain.d.ts +80 -0
  47. package/dist/types/dsl/create-brain.d.ts.map +1 -0
  48. package/dist/types/dsl/definitions/blocks.d.ts +62 -0
  49. package/dist/types/dsl/definitions/blocks.d.ts.map +1 -0
  50. package/dist/types/dsl/definitions/brain-types.d.ts +33 -0
  51. package/dist/types/dsl/definitions/brain-types.d.ts.map +1 -0
  52. package/dist/types/dsl/definitions/events.d.ts +129 -0
  53. package/dist/types/dsl/definitions/events.d.ts.map +1 -0
  54. package/dist/types/dsl/definitions/run-params.d.ts +26 -0
  55. package/dist/types/dsl/definitions/run-params.d.ts.map +1 -0
  56. package/dist/types/dsl/definitions/steps.d.ts +20 -0
  57. package/dist/types/dsl/definitions/steps.d.ts.map +1 -0
  58. package/dist/types/dsl/example-webhook.d.ts +1 -1
  59. package/dist/types/dsl/example-webhook.d.ts.map +1 -1
  60. package/dist/types/dsl/execution/constants.d.ts +16 -0
  61. package/dist/types/dsl/execution/constants.d.ts.map +1 -0
  62. package/dist/types/dsl/execution/event-stream.d.ts +44 -0
  63. package/dist/types/dsl/execution/event-stream.d.ts.map +1 -0
  64. package/dist/types/dsl/execution/retry.d.ts +30 -0
  65. package/dist/types/dsl/execution/retry.d.ts.map +1 -0
  66. package/dist/types/dsl/types.d.ts +35 -14
  67. package/dist/types/dsl/types.d.ts.map +1 -1
  68. package/dist/types/index.d.ts +9 -7
  69. package/dist/types/index.d.ts.map +1 -1
  70. package/dist/types/tools/index.d.ts +33 -0
  71. package/dist/types/tools/index.d.ts.map +1 -0
  72. package/dist/types/ui/component-utils.d.ts +19 -0
  73. package/dist/types/ui/component-utils.d.ts.map +1 -0
  74. package/dist/types/ui/generate-page-html.d.ts +39 -0
  75. package/dist/types/ui/generate-page-html.d.ts.map +1 -0
  76. package/dist/types/ui/generate-ui.d.ts +47 -0
  77. package/dist/types/ui/generate-ui.d.ts.map +1 -0
  78. package/dist/types/ui/types.d.ts +138 -0
  79. package/dist/types/ui/types.d.ts.map +1 -0
  80. package/dist/types/ui/validate-form.d.ts +45 -0
  81. package/dist/types/ui/validate-form.d.ts.map +1 -0
  82. package/dist/types/yaml/data-validator.d.ts +35 -0
  83. package/dist/types/yaml/data-validator.d.ts.map +1 -0
  84. package/dist/types/yaml/index.d.ts +11 -0
  85. package/dist/types/yaml/index.d.ts.map +1 -0
  86. package/dist/types/yaml/parser.d.ts +20 -0
  87. package/dist/types/yaml/parser.d.ts.map +1 -0
  88. package/dist/types/yaml/schema-extractor.d.ts +29 -0
  89. package/dist/types/yaml/schema-extractor.d.ts.map +1 -0
  90. package/dist/types/yaml/type-inference.d.ts +50 -0
  91. package/dist/types/yaml/type-inference.d.ts.map +1 -0
  92. package/dist/types/yaml/types.d.ts +89 -0
  93. package/dist/types/yaml/types.d.ts.map +1 -0
  94. package/package.json +4 -2
  95. package/dist/types/dsl/loop-messages.d.ts +0 -18
  96. package/dist/types/dsl/loop-messages.d.ts.map +0 -1
@@ -0,0 +1,1638 @@
1
+ function _array_like_to_array(arr, len) {
2
+ if (len == null || len > arr.length) len = arr.length;
3
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
4
+ return arr2;
5
+ }
6
+ function _array_with_holes(arr) {
7
+ if (Array.isArray(arr)) return arr;
8
+ }
9
+ function _async_generator(gen) {
10
+ var front, back;
11
+ function send(key, arg) {
12
+ return new Promise(function(resolve, reject) {
13
+ var request = {
14
+ key: key,
15
+ arg: arg,
16
+ resolve: resolve,
17
+ reject: reject,
18
+ next: null
19
+ };
20
+ if (back) back = back.next = request;
21
+ else {
22
+ front = back = request;
23
+ resume(key, arg);
24
+ }
25
+ });
26
+ }
27
+ function resume(key, arg) {
28
+ try {
29
+ var result = gen[key](arg);
30
+ var value = result.value;
31
+ var overloaded = value instanceof _overload_yield;
32
+ Promise.resolve(overloaded ? value.v : value).then(function(arg) {
33
+ if (overloaded) {
34
+ var nextKey = key === "return" ? "return" : "next";
35
+ if (!value.k || arg.done) return resume(nextKey, arg);
36
+ else arg = gen[nextKey](arg).value;
37
+ }
38
+ settle(result.done ? "return" : "normal", arg);
39
+ }, function(err) {
40
+ resume("throw", err);
41
+ });
42
+ } catch (err) {
43
+ settle("throw", err);
44
+ }
45
+ }
46
+ function settle(type, value) {
47
+ switch(type){
48
+ case "return":
49
+ front.resolve({
50
+ value: value,
51
+ done: true
52
+ });
53
+ break;
54
+ case "throw":
55
+ front.reject(value);
56
+ break;
57
+ default:
58
+ front.resolve({
59
+ value: value,
60
+ done: false
61
+ });
62
+ break;
63
+ }
64
+ front = front.next;
65
+ if (front) resume(front.key, front.arg);
66
+ else back = null;
67
+ }
68
+ this._invoke = send;
69
+ if (typeof gen.return !== "function") this.return = undefined;
70
+ }
71
+ _async_generator.prototype[typeof Symbol === "function" && Symbol.asyncIterator || "@@asyncIterator"] = function() {
72
+ return this;
73
+ };
74
+ _async_generator.prototype.next = function(arg) {
75
+ return this._invoke("next", arg);
76
+ };
77
+ _async_generator.prototype.throw = function(arg) {
78
+ return this._invoke("throw", arg);
79
+ };
80
+ _async_generator.prototype.return = function(arg) {
81
+ return this._invoke("return", arg);
82
+ };
83
+ function _async_generator_delegate(inner) {
84
+ var iter = {}, waiting = false;
85
+ function pump(key, value) {
86
+ waiting = true;
87
+ value = new Promise(function(resolve) {
88
+ resolve(inner[key](value));
89
+ });
90
+ return {
91
+ done: false,
92
+ value: new _overload_yield(value, 1)
93
+ };
94
+ }
95
+ iter[typeof Symbol !== "undefined" && Symbol.iterator || "@@iterator"] = function() {
96
+ return this;
97
+ };
98
+ iter.next = function(value) {
99
+ if (waiting) {
100
+ waiting = false;
101
+ return value;
102
+ }
103
+ return pump("next", value);
104
+ };
105
+ if (typeof inner.throw === "function") {
106
+ iter.throw = function(value) {
107
+ if (waiting) {
108
+ waiting = false;
109
+ throw value;
110
+ }
111
+ return pump("throw", value);
112
+ };
113
+ }
114
+ if (typeof inner.return === "function") {
115
+ iter.return = function(value) {
116
+ if (waiting) {
117
+ waiting = false;
118
+ return value;
119
+ }
120
+ return pump("return", value);
121
+ };
122
+ }
123
+ return iter;
124
+ }
125
+ function _async_iterator(iterable) {
126
+ var method, async, sync, retry = 2;
127
+ for("undefined" != typeof Symbol && (async = Symbol.asyncIterator, sync = Symbol.iterator); retry--;){
128
+ if (async && null != (method = iterable[async])) return method.call(iterable);
129
+ if (sync && null != (method = iterable[sync])) return new AsyncFromSyncIterator(method.call(iterable));
130
+ async = "@@asyncIterator", sync = "@@iterator";
131
+ }
132
+ throw new TypeError("Object is not async iterable");
133
+ }
134
+ function AsyncFromSyncIterator(s) {
135
+ function AsyncFromSyncIteratorContinuation(r) {
136
+ if (Object(r) !== r) return Promise.reject(new TypeError(r + " is not an object."));
137
+ var done = r.done;
138
+ return Promise.resolve(r.value).then(function(value) {
139
+ return {
140
+ value: value,
141
+ done: done
142
+ };
143
+ });
144
+ }
145
+ return AsyncFromSyncIterator = function(s) {
146
+ this.s = s, this.n = s.next;
147
+ }, AsyncFromSyncIterator.prototype = {
148
+ s: null,
149
+ n: null,
150
+ next: function() {
151
+ return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments));
152
+ },
153
+ return: function(value) {
154
+ var ret = this.s.return;
155
+ return void 0 === ret ? Promise.resolve({
156
+ value: value,
157
+ done: !0
158
+ }) : AsyncFromSyncIteratorContinuation(ret.apply(this.s, arguments));
159
+ },
160
+ throw: function(value) {
161
+ var thr = this.s.return;
162
+ return void 0 === thr ? Promise.reject(value) : AsyncFromSyncIteratorContinuation(thr.apply(this.s, arguments));
163
+ }
164
+ }, new AsyncFromSyncIterator(s);
165
+ }
166
+ function _await_async_generator(value) {
167
+ return new _overload_yield(value, 0);
168
+ }
169
+ function _class_call_check(instance, Constructor) {
170
+ if (!(instance instanceof Constructor)) {
171
+ throw new TypeError("Cannot call a class as a function");
172
+ }
173
+ }
174
+ function _defineProperties(target, props) {
175
+ for(var i = 0; i < props.length; i++){
176
+ var descriptor = props[i];
177
+ descriptor.enumerable = descriptor.enumerable || false;
178
+ descriptor.configurable = true;
179
+ if ("value" in descriptor) descriptor.writable = true;
180
+ Object.defineProperty(target, descriptor.key, descriptor);
181
+ }
182
+ }
183
+ function _create_class(Constructor, protoProps, staticProps) {
184
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
185
+ if (staticProps) _defineProperties(Constructor, staticProps);
186
+ return Constructor;
187
+ }
188
+ function _define_property(obj, key, value) {
189
+ if (key in obj) {
190
+ Object.defineProperty(obj, key, {
191
+ value: value,
192
+ enumerable: true,
193
+ configurable: true,
194
+ writable: true
195
+ });
196
+ } else {
197
+ obj[key] = value;
198
+ }
199
+ return obj;
200
+ }
201
+ function _iterable_to_array_limit(arr, i) {
202
+ var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
203
+ if (_i == null) return;
204
+ var _arr = [];
205
+ var _n = true;
206
+ var _d = false;
207
+ var _s, _e;
208
+ try {
209
+ for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
210
+ _arr.push(_s.value);
211
+ if (i && _arr.length === i) break;
212
+ }
213
+ } catch (err) {
214
+ _d = true;
215
+ _e = err;
216
+ } finally{
217
+ try {
218
+ if (!_n && _i["return"] != null) _i["return"]();
219
+ } finally{
220
+ if (_d) throw _e;
221
+ }
222
+ }
223
+ return _arr;
224
+ }
225
+ function _non_iterable_rest() {
226
+ 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
+ }
228
+ function _object_spread(target) {
229
+ for(var i = 1; i < arguments.length; i++){
230
+ var source = arguments[i] != null ? arguments[i] : {};
231
+ var ownKeys = Object.keys(source);
232
+ if (typeof Object.getOwnPropertySymbols === "function") {
233
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
234
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
235
+ }));
236
+ }
237
+ ownKeys.forEach(function(key) {
238
+ _define_property(target, key, source[key]);
239
+ });
240
+ }
241
+ return target;
242
+ }
243
+ function ownKeys(object, enumerableOnly) {
244
+ var keys = Object.keys(object);
245
+ if (Object.getOwnPropertySymbols) {
246
+ var symbols = Object.getOwnPropertySymbols(object);
247
+ if (enumerableOnly) {
248
+ symbols = symbols.filter(function(sym) {
249
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
250
+ });
251
+ }
252
+ keys.push.apply(keys, symbols);
253
+ }
254
+ return keys;
255
+ }
256
+ function _object_spread_props(target, source) {
257
+ source = source != null ? source : {};
258
+ if (Object.getOwnPropertyDescriptors) {
259
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
260
+ } else {
261
+ ownKeys(Object(source)).forEach(function(key) {
262
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
263
+ });
264
+ }
265
+ return target;
266
+ }
267
+ function _object_without_properties(source, excluded) {
268
+ if (source == null) return {};
269
+ var target = _object_without_properties_loose(source, excluded);
270
+ var key, i;
271
+ if (Object.getOwnPropertySymbols) {
272
+ var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
273
+ for(i = 0; i < sourceSymbolKeys.length; i++){
274
+ key = sourceSymbolKeys[i];
275
+ if (excluded.indexOf(key) >= 0) continue;
276
+ if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
277
+ target[key] = source[key];
278
+ }
279
+ }
280
+ return target;
281
+ }
282
+ function _object_without_properties_loose(source, excluded) {
283
+ if (source == null) return {};
284
+ var target = {};
285
+ var sourceKeys = Object.keys(source);
286
+ var key, i;
287
+ for(i = 0; i < sourceKeys.length; i++){
288
+ key = sourceKeys[i];
289
+ if (excluded.indexOf(key) >= 0) continue;
290
+ target[key] = source[key];
291
+ }
292
+ return target;
293
+ }
294
+ function _overload_yield(value, kind) {
295
+ this.v = value;
296
+ this.k = kind;
297
+ }
298
+ function _sliced_to_array(arr, i) {
299
+ return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
300
+ }
301
+ function _type_of(obj) {
302
+ "@swc/helpers - typeof";
303
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
304
+ }
305
+ function _unsupported_iterable_to_array(o, minLen) {
306
+ if (!o) return;
307
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
308
+ var n = Object.prototype.toString.call(o).slice(8, -1);
309
+ if (n === "Object" && o.constructor) n = o.constructor.name;
310
+ if (n === "Map" || n === "Set") return Array.from(n);
311
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
312
+ }
313
+ function _wrap_async_generator(fn) {
314
+ return function() {
315
+ return new _async_generator(fn.apply(this, arguments));
316
+ };
317
+ }
318
+ function _ts_generator(thisArg, body) {
319
+ var f, y, t, _ = {
320
+ label: 0,
321
+ sent: function() {
322
+ if (t[0] & 1) throw t[1];
323
+ return t[1];
324
+ },
325
+ trys: [],
326
+ ops: []
327
+ }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
328
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
329
+ return this;
330
+ }), g;
331
+ function verb(n) {
332
+ return function(v) {
333
+ return step([
334
+ n,
335
+ v
336
+ ]);
337
+ };
338
+ }
339
+ function step(op) {
340
+ if (f) throw new TypeError("Generator is already executing.");
341
+ while(g && (g = 0, op[0] && (_ = 0)), _)try {
342
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
343
+ if (y = 0, t) op = [
344
+ op[0] & 2,
345
+ t.value
346
+ ];
347
+ switch(op[0]){
348
+ case 0:
349
+ case 1:
350
+ t = op;
351
+ break;
352
+ case 4:
353
+ _.label++;
354
+ return {
355
+ value: op[1],
356
+ done: false
357
+ };
358
+ case 5:
359
+ _.label++;
360
+ y = op[1];
361
+ op = [
362
+ 0
363
+ ];
364
+ continue;
365
+ case 7:
366
+ op = _.ops.pop();
367
+ _.trys.pop();
368
+ continue;
369
+ default:
370
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
371
+ _ = 0;
372
+ continue;
373
+ }
374
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
375
+ _.label = op[1];
376
+ break;
377
+ }
378
+ if (op[0] === 6 && _.label < t[1]) {
379
+ _.label = t[1];
380
+ t = op;
381
+ break;
382
+ }
383
+ if (t && _.label < t[2]) {
384
+ _.label = t[2];
385
+ _.ops.push(op);
386
+ break;
387
+ }
388
+ if (t[2]) _.ops.pop();
389
+ _.trys.pop();
390
+ continue;
391
+ }
392
+ op = body.call(thisArg, _);
393
+ } catch (e) {
394
+ op = [
395
+ 6,
396
+ e
397
+ ];
398
+ y = 0;
399
+ } finally{
400
+ f = t = 0;
401
+ }
402
+ if (op[0] & 5) throw op[1];
403
+ return {
404
+ value: op[0] ? op[1] : void 0,
405
+ done: true
406
+ };
407
+ }
408
+ }
409
+ function _ts_values(o) {
410
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
411
+ if (m) return m.call(o);
412
+ if (o && typeof o.length === "number") return {
413
+ next: function() {
414
+ if (o && i >= o.length) o = void 0;
415
+ return {
416
+ value: o && o[i++],
417
+ done: !o
418
+ };
419
+ }
420
+ };
421
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
422
+ }
423
+ import { z } from 'zod';
424
+ import { v4 as uuidv4 } from 'uuid';
425
+ import { STATUS, BRAIN_EVENTS } from '../constants.js';
426
+ import { createPatch, applyPatches } from '../json-patch.js';
427
+ import { generateUI } from '../../ui/generate-ui.js';
428
+ import { generatePageHtml } from '../../ui/generate-page-html.js';
429
+ import { Step } from '../builder/step.js';
430
+ import { DEFAULT_ENV, DEFAULT_AGENT_SYSTEM_PROMPT, MAX_RETRIES } from './constants.js';
431
+ var clone = function(value) {
432
+ return structuredClone(value);
433
+ };
434
+ export var BrainEventStream = /*#__PURE__*/ function() {
435
+ "use strict";
436
+ function BrainEventStream(params) {
437
+ _class_call_check(this, BrainEventStream);
438
+ _define_property(this, "currentState", void 0);
439
+ _define_property(this, "steps", void 0);
440
+ _define_property(this, "currentStepIndex", 0);
441
+ _define_property(this, "initialState", void 0);
442
+ _define_property(this, "brainRunId", void 0);
443
+ _define_property(this, "title", void 0);
444
+ _define_property(this, "description", void 0);
445
+ _define_property(this, "client", void 0);
446
+ _define_property(this, "options", void 0);
447
+ _define_property(this, "services", void 0);
448
+ _define_property(this, "resources", void 0);
449
+ _define_property(this, "pages", void 0);
450
+ _define_property(this, "env", void 0);
451
+ _define_property(this, "currentResponse", undefined);
452
+ _define_property(this, "currentPage", undefined);
453
+ _define_property(this, "agentResumeContext", undefined);
454
+ _define_property(this, "initialCompletedSteps", void 0);
455
+ _define_property(this, "components", void 0);
456
+ _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;
459
+ this.title = title;
460
+ this.description = description;
461
+ this.client = client;
462
+ this.options = options;
463
+ this.services = services;
464
+ this.resources = resources;
465
+ this.pages = pages;
466
+ this.env = env !== null && env !== void 0 ? env : DEFAULT_ENV;
467
+ this.initialCompletedSteps = initialCompletedSteps;
468
+ this.components = components;
469
+ 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
+ }
476
+ return new Step(block);
477
+ });
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
+ }
488
+ }
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
+ }
501
+ }
502
+ }
503
+ // Use provided ID if available, otherwise generate one
504
+ 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
+ }
518
+ _create_class(BrainEventStream, [
519
+ {
520
+ key: "next",
521
+ value: function next() {
522
+ return _wrap_async_generator(function() {
523
+ var _this, steps, brainTitle, brainDescription, currentState, options, brainRunId, hasCompletedSteps, step, err, error, currentStep;
524
+ return _ts_generator(this, function(_state) {
525
+ switch(_state.label){
526
+ case 0:
527
+ _this = this, steps = _this.steps, brainTitle = _this.title, brainDescription = _this.description, currentState = _this.currentState, options = _this.options, brainRunId = _this.brainRunId;
528
+ _state.label = 1;
529
+ case 1:
530
+ _state.trys.push([
531
+ 1,
532
+ 11,
533
+ ,
534
+ 14
535
+ ]);
536
+ hasCompletedSteps = steps.some(function(step) {
537
+ return step.serialized.status !== STATUS.PENDING;
538
+ });
539
+ return [
540
+ 4,
541
+ _object_spread_props(_object_spread({
542
+ type: hasCompletedSteps ? BRAIN_EVENTS.RESTART : BRAIN_EVENTS.START,
543
+ status: STATUS.RUNNING,
544
+ brainTitle: brainTitle,
545
+ brainDescription: brainDescription
546
+ }, hasCompletedSteps ? {} : {
547
+ initialState: currentState
548
+ }), {
549
+ options: options,
550
+ brainRunId: brainRunId
551
+ })
552
+ ];
553
+ case 2:
554
+ _state.sent();
555
+ // Emit initial step status after brain starts
556
+ return [
557
+ 4,
558
+ {
559
+ type: BRAIN_EVENTS.STEP_STATUS,
560
+ steps: steps.map(function(step) {
561
+ var _step_serialized = step.serialized, patch = _step_serialized.patch, rest = _object_without_properties(_step_serialized, [
562
+ "patch"
563
+ ]);
564
+ return rest;
565
+ }),
566
+ options: options,
567
+ brainRunId: brainRunId
568
+ }
569
+ ];
570
+ case 3:
571
+ _state.sent();
572
+ _state.label = 4;
573
+ case 4:
574
+ if (!(this.currentStepIndex < steps.length)) return [
575
+ 3,
576
+ 9
577
+ ];
578
+ step = steps[this.currentStepIndex];
579
+ // Skip completed steps
580
+ if (step.serialized.status === STATUS.COMPLETE) {
581
+ this.currentStepIndex++;
582
+ return [
583
+ 3,
584
+ 4
585
+ ];
586
+ }
587
+ // Step start event
588
+ return [
589
+ 4,
590
+ {
591
+ type: BRAIN_EVENTS.STEP_START,
592
+ status: STATUS.RUNNING,
593
+ stepTitle: step.block.title,
594
+ stepId: step.id,
595
+ options: options,
596
+ brainRunId: brainRunId
597
+ }
598
+ ];
599
+ case 5:
600
+ _state.sent();
601
+ step.withStatus(STATUS.RUNNING);
602
+ // Step Status Event to indicate that the step is running
603
+ return [
604
+ 4,
605
+ {
606
+ type: BRAIN_EVENTS.STEP_STATUS,
607
+ steps: steps.map(function(step) {
608
+ var _step_serialized = step.serialized, patch = _step_serialized.patch, rest = _object_without_properties(_step_serialized, [
609
+ "patch"
610
+ ]);
611
+ return rest;
612
+ }),
613
+ options: options,
614
+ brainRunId: brainRunId
615
+ }
616
+ ];
617
+ case 6:
618
+ _state.sent();
619
+ // Execute step and yield the STEP_COMPLETE event and
620
+ // all events from inner brains if any
621
+ return [
622
+ 5,
623
+ _ts_values(_async_generator_delegate(_async_iterator(this.executeStep(step))))
624
+ ];
625
+ case 7:
626
+ _state.sent();
627
+ // Step Status Event
628
+ return [
629
+ 4,
630
+ {
631
+ type: BRAIN_EVENTS.STEP_STATUS,
632
+ steps: steps.map(function(step) {
633
+ var _step_serialized = step.serialized, patch = _step_serialized.patch, rest = _object_without_properties(_step_serialized, [
634
+ "patch"
635
+ ]);
636
+ return rest;
637
+ }),
638
+ options: options,
639
+ brainRunId: brainRunId
640
+ }
641
+ ];
642
+ case 8:
643
+ _state.sent();
644
+ this.currentStepIndex++;
645
+ return [
646
+ 3,
647
+ 4
648
+ ];
649
+ case 9:
650
+ return [
651
+ 4,
652
+ {
653
+ type: BRAIN_EVENTS.COMPLETE,
654
+ status: STATUS.COMPLETE,
655
+ brainTitle: brainTitle,
656
+ brainDescription: brainDescription,
657
+ brainRunId: brainRunId,
658
+ options: options
659
+ }
660
+ ];
661
+ case 10:
662
+ _state.sent();
663
+ return [
664
+ 3,
665
+ 14
666
+ ];
667
+ case 11:
668
+ err = _state.sent();
669
+ error = err;
670
+ currentStep = steps[this.currentStepIndex];
671
+ currentStep === null || currentStep === void 0 ? void 0 : currentStep.withStatus(STATUS.ERROR);
672
+ return [
673
+ 4,
674
+ {
675
+ type: BRAIN_EVENTS.ERROR,
676
+ status: STATUS.ERROR,
677
+ brainTitle: brainTitle,
678
+ brainDescription: brainDescription,
679
+ brainRunId: brainRunId,
680
+ error: {
681
+ name: error.name,
682
+ message: error.message,
683
+ stack: error.stack
684
+ },
685
+ options: options
686
+ }
687
+ ];
688
+ case 12:
689
+ _state.sent();
690
+ // Step Status Event
691
+ return [
692
+ 4,
693
+ {
694
+ type: BRAIN_EVENTS.STEP_STATUS,
695
+ steps: steps.map(function(step) {
696
+ var _step_serialized = step.serialized, patch = _step_serialized.patch, rest = _object_without_properties(_step_serialized, [
697
+ "patch"
698
+ ]);
699
+ return rest;
700
+ }),
701
+ options: options,
702
+ brainRunId: brainRunId
703
+ }
704
+ ];
705
+ case 13:
706
+ _state.sent();
707
+ throw error;
708
+ case 14:
709
+ return [
710
+ 2
711
+ ];
712
+ }
713
+ });
714
+ }).call(this);
715
+ }
716
+ },
717
+ {
718
+ key: "executeStep",
719
+ value: function executeStep(step) {
720
+ 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;
722
+ return _ts_generator(this, function(_state) {
723
+ switch(_state.label){
724
+ case 0:
725
+ block = step.block;
726
+ if (!(block.type === 'step')) return [
727
+ 3,
728
+ 2
729
+ ];
730
+ stepBlock = block;
731
+ if (!stepBlock.isUIStep) return [
732
+ 3,
733
+ 2
734
+ ];
735
+ return [
736
+ 5,
737
+ _ts_values(_async_generator_delegate(_async_iterator(this.executeUIStep(step, stepBlock))))
738
+ ];
739
+ case 1:
740
+ _state.sent();
741
+ return [
742
+ 2
743
+ ];
744
+ case 2:
745
+ if (!(block.type === 'brain')) return [
746
+ 3,
747
+ 18
748
+ ];
749
+ brainBlock = block;
750
+ 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;
755
+ // Run inner brain and yield all its events
756
+ // Pass brainRunId so inner brain shares outer brain's run ID
757
+ // Pass innerSteps and response for resume scenarios
758
+ 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
+ innerBrainPaused = false;
786
+ innerRun = innerCompletedSteps ? brainBlock.innerBrain.run({
787
+ resources: this.resources,
788
+ client: this.client,
789
+ initialState: initialState,
790
+ initialCompletedSteps: innerCompletedSteps,
791
+ options: (_this_options = this.options) !== null && _this_options !== void 0 ? _this_options : {},
792
+ pages: this.pages,
793
+ env: this.env,
794
+ brainRunId: this.brainRunId,
795
+ response: this.currentResponse
796
+ }) : brainBlock.innerBrain.run({
797
+ resources: this.resources,
798
+ client: this.client,
799
+ initialState: initialState,
800
+ options: (_this_options1 = this.options) !== null && _this_options1 !== void 0 ? _this_options1 : {},
801
+ pages: this.pages,
802
+ env: this.env,
803
+ brainRunId: this.brainRunId
804
+ });
805
+ _iteratorAbruptCompletion = false, _didIteratorError1 = false;
806
+ _state.label = 3;
807
+ case 3:
808
+ _state.trys.push([
809
+ 3,
810
+ 9,
811
+ 10,
812
+ 15
813
+ ]);
814
+ _iterator1 = _async_iterator(innerRun);
815
+ _state.label = 4;
816
+ case 4:
817
+ return [
818
+ 4,
819
+ _await_async_generator(_iterator1.next())
820
+ ];
821
+ case 5:
822
+ if (!(_iteratorAbruptCompletion = !(_step1 = _state.sent()).done)) return [
823
+ 3,
824
+ 8
825
+ ];
826
+ _value = _step1.value;
827
+ event = _value;
828
+ return [
829
+ 4,
830
+ event
831
+ ];
832
+ case 6:
833
+ _state.sent(); // Forward all inner brain events
834
+ if (event.type === BRAIN_EVENTS.STEP_COMPLETE) {
835
+ patches.push(event.patch);
836
+ }
837
+ // If inner brain yielded a WEBHOOK event, it's pausing
838
+ if (event.type === BRAIN_EVENTS.WEBHOOK) {
839
+ innerBrainPaused = true;
840
+ }
841
+ // If inner brain completed, break immediately to prevent hanging
842
+ if (event.type === BRAIN_EVENTS.COMPLETE) {
843
+ return [
844
+ 3,
845
+ 8
846
+ ];
847
+ }
848
+ _state.label = 7;
849
+ case 7:
850
+ _iteratorAbruptCompletion = false;
851
+ return [
852
+ 3,
853
+ 4
854
+ ];
855
+ case 8:
856
+ return [
857
+ 3,
858
+ 15
859
+ ];
860
+ case 9:
861
+ err1 = _state.sent();
862
+ _didIteratorError1 = true;
863
+ _iteratorError1 = err1;
864
+ return [
865
+ 3,
866
+ 15
867
+ ];
868
+ case 10:
869
+ _state.trys.push([
870
+ 10,
871
+ ,
872
+ 13,
873
+ 14
874
+ ]);
875
+ if (!(_iteratorAbruptCompletion && _iterator1.return != null)) return [
876
+ 3,
877
+ 12
878
+ ];
879
+ return [
880
+ 4,
881
+ _await_async_generator(_iterator1.return())
882
+ ];
883
+ case 11:
884
+ _state.sent();
885
+ _state.label = 12;
886
+ case 12:
887
+ return [
888
+ 3,
889
+ 14
890
+ ];
891
+ case 13:
892
+ if (_didIteratorError1) {
893
+ throw _iteratorError1;
894
+ }
895
+ return [
896
+ 7
897
+ ];
898
+ case 14:
899
+ return [
900
+ 7
901
+ ];
902
+ case 15:
903
+ // If inner brain paused for webhook, don't complete the outer brain step
904
+ // The outer brain should also pause
905
+ if (innerBrainPaused) {
906
+ return [
907
+ 2
908
+ ];
909
+ }
910
+ // Apply collected patches to get final inner state
911
+ innerState = applyPatches(initialState, patches);
912
+ // Get previous state before action
913
+ prevState = this.currentState;
914
+ // Update state with inner brain results
915
+ _ = this;
916
+ return [
917
+ 4,
918
+ _await_async_generator(brainBlock.action(this.currentState, innerState, this.services))
919
+ ];
920
+ case 16:
921
+ _.currentState = _state.sent();
922
+ return [
923
+ 5,
924
+ _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState))))
925
+ ];
926
+ case 17:
927
+ _state.sent();
928
+ return [
929
+ 3,
930
+ 33
931
+ ];
932
+ case 18:
933
+ if (!(block.type === 'agent')) return [
934
+ 3,
935
+ 20
936
+ ];
937
+ return [
938
+ 5,
939
+ _ts_values(_async_generator_delegate(_async_iterator(this.executeAgent(step))))
940
+ ];
941
+ case 19:
942
+ _state.sent();
943
+ return [
944
+ 3,
945
+ 33
946
+ ];
947
+ case 20:
948
+ // Get previous state before action
949
+ prevState1 = this.currentState;
950
+ stepBlock1 = block;
951
+ // Execute step with automatic retry on failure
952
+ retries = 0;
953
+ _state.label = 21;
954
+ case 21:
955
+ if (!true) return [
956
+ 3,
957
+ 29
958
+ ];
959
+ _state.label = 22;
960
+ case 22:
961
+ _state.trys.push([
962
+ 22,
963
+ 24,
964
+ ,
965
+ 28
966
+ ]);
967
+ actionPromise = Promise.resolve(stepBlock1.action(_object_spread({
968
+ state: this.currentState,
969
+ options: (_this_options2 = this.options) !== null && _this_options2 !== void 0 ? _this_options2 : {},
970
+ client: this.client,
971
+ resources: this.resources,
972
+ response: this.currentResponse,
973
+ page: this.currentPage,
974
+ pages: this.pages,
975
+ env: this.env
976
+ }, this.services)));
977
+ return [
978
+ 4,
979
+ _await_async_generator(actionPromise)
980
+ ];
981
+ case 23:
982
+ result = _state.sent();
983
+ return [
984
+ 3,
985
+ 29
986
+ ]; // Success
987
+ case 24:
988
+ error = _state.sent();
989
+ if (!(retries < MAX_RETRIES)) return [
990
+ 3,
991
+ 26
992
+ ];
993
+ retries++;
994
+ return [
995
+ 4,
996
+ {
997
+ type: BRAIN_EVENTS.STEP_RETRY,
998
+ stepTitle: step.block.title,
999
+ stepId: step.id,
1000
+ error: {
1001
+ name: error.name,
1002
+ message: error.message,
1003
+ stack: error.stack
1004
+ },
1005
+ attempt: retries,
1006
+ options: (_this_options3 = this.options) !== null && _this_options3 !== void 0 ? _this_options3 : {},
1007
+ brainRunId: this.brainRunId
1008
+ }
1009
+ ];
1010
+ case 25:
1011
+ _state.sent();
1012
+ return [
1013
+ 3,
1014
+ 27
1015
+ ];
1016
+ case 26:
1017
+ throw error;
1018
+ case 27:
1019
+ return [
1020
+ 3,
1021
+ 28
1022
+ ];
1023
+ case 28:
1024
+ return [
1025
+ 3,
1026
+ 21
1027
+ ];
1028
+ case 29:
1029
+ // Extract state from result (handles waitFor and promptResponse cases)
1030
+ if (result && (typeof result === "undefined" ? "undefined" : _type_of(result)) === 'object' && ('waitFor' in result || 'promptResponse' in result)) {
1031
+ this.currentState = result.state;
1032
+ } else {
1033
+ this.currentState = result;
1034
+ }
1035
+ return [
1036
+ 5,
1037
+ _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState1))))
1038
+ ];
1039
+ case 30:
1040
+ _state.sent();
1041
+ if (!(result && (typeof result === "undefined" ? "undefined" : _type_of(result)) === 'object' && 'waitFor' in result)) return [
1042
+ 3,
1043
+ 32
1044
+ ];
1045
+ // Serialize webhook registrations (remove Zod schemas for event serializability)
1046
+ serializedWaitFor = result.waitFor.map(function(registration) {
1047
+ return {
1048
+ slug: registration.slug,
1049
+ identifier: registration.identifier
1050
+ };
1051
+ });
1052
+ return [
1053
+ 4,
1054
+ {
1055
+ type: BRAIN_EVENTS.WEBHOOK,
1056
+ waitFor: serializedWaitFor,
1057
+ options: this.options,
1058
+ brainRunId: this.brainRunId
1059
+ }
1060
+ ];
1061
+ case 31:
1062
+ _state.sent();
1063
+ _state.label = 32;
1064
+ case 32:
1065
+ // Handle promptResponse - set currentResponse for next step
1066
+ if (result && (typeof result === "undefined" ? "undefined" : _type_of(result)) === 'object' && 'promptResponse' in result) {
1067
+ this.currentResponse = result.promptResponse;
1068
+ }
1069
+ // Reset currentPage after step consumes it (page is ephemeral)
1070
+ this.currentPage = undefined;
1071
+ _state.label = 33;
1072
+ case 33:
1073
+ return [
1074
+ 2
1075
+ ];
1076
+ }
1077
+ });
1078
+ }).call(this);
1079
+ }
1080
+ },
1081
+ {
1082
+ key: "executeAgent",
1083
+ value: function executeAgent(step) {
1084
+ 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, _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;
1086
+ return _ts_generator(this, function(_state) {
1087
+ switch(_state.label){
1088
+ case 0:
1089
+ block = step.block;
1090
+ prevState = this.currentState;
1091
+ // Get default tools and components for injection into configFn
1092
+ defaultTools = (_this_defaultTools = this.defaultTools) !== null && _this_defaultTools !== void 0 ? _this_defaultTools : {};
1093
+ components = (_this_components = this.components) !== null && _this_components !== void 0 ? _this_components : {};
1094
+ return [
1095
+ 4,
1096
+ _await_async_generator(block.configFn(_object_spread({
1097
+ state: this.currentState,
1098
+ options: (_this_options = this.options) !== null && _this_options !== void 0 ? _this_options : {},
1099
+ tools: defaultTools,
1100
+ components: components,
1101
+ client: this.client,
1102
+ resources: this.resources,
1103
+ response: this.currentResponse,
1104
+ page: this.currentPage,
1105
+ pages: this.pages,
1106
+ env: this.env
1107
+ }, this.services)))
1108
+ ];
1109
+ case 1:
1110
+ config = _state.sent();
1111
+ // Reset currentPage after configFn consumes it (page is ephemeral)
1112
+ this.currentPage = undefined;
1113
+ // Merge tools: step tools override defaults
1114
+ mergedTools = _object_spread({}, defaultTools, (_config_tools = config.tools) !== null && _config_tools !== void 0 ? _config_tools : {});
1115
+ if (!this.agentResumeContext) return [
1116
+ 3,
1117
+ 4
1118
+ ];
1119
+ resumeContext = this.agentResumeContext;
1120
+ // Emit WEBHOOK_RESPONSE event to record the response
1121
+ return [
1122
+ 4,
1123
+ {
1124
+ type: BRAIN_EVENTS.WEBHOOK_RESPONSE,
1125
+ response: resumeContext.webhookResponse,
1126
+ options: (_this_options1 = this.options) !== null && _this_options1 !== void 0 ? _this_options1 : {},
1127
+ brainRunId: this.brainRunId
1128
+ }
1129
+ ];
1130
+ case 2:
1131
+ _state.sent();
1132
+ // Emit AGENT_TOOL_RESULT for the pending tool (webhook response injected as tool result)
1133
+ return [
1134
+ 4,
1135
+ {
1136
+ type: BRAIN_EVENTS.AGENT_TOOL_RESULT,
1137
+ stepTitle: step.block.title,
1138
+ stepId: step.id,
1139
+ toolCallId: resumeContext.pendingToolCallId,
1140
+ toolName: resumeContext.pendingToolName,
1141
+ result: resumeContext.webhookResponse,
1142
+ options: (_this_options2 = this.options) !== null && _this_options2 !== void 0 ? _this_options2 : {},
1143
+ brainRunId: this.brainRunId
1144
+ }
1145
+ ];
1146
+ case 3:
1147
+ _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;
1152
+ return [
1153
+ 3,
1154
+ 6
1155
+ ];
1156
+ case 4:
1157
+ // Emit agent start event (only for fresh starts)
1158
+ return [
1159
+ 4,
1160
+ {
1161
+ type: BRAIN_EVENTS.AGENT_START,
1162
+ stepTitle: step.block.title,
1163
+ stepId: step.id,
1164
+ prompt: config.prompt,
1165
+ system: config.system,
1166
+ options: (_this_options3 = this.options) !== null && _this_options3 !== void 0 ? _this_options3 : {},
1167
+ brainRunId: this.brainRunId
1168
+ }
1169
+ ];
1170
+ case 5:
1171
+ _state.sent();
1172
+ // Initialize messages for fresh start
1173
+ messages = [
1174
+ {
1175
+ role: 'user',
1176
+ content: config.prompt
1177
+ }
1178
+ ];
1179
+ _state.label = 6;
1180
+ case 6:
1181
+ // Initialize token tracking
1182
+ totalTokens = 0;
1183
+ iteration = 0;
1184
+ _state.label = 7;
1185
+ case 7:
1186
+ if (!true) return [
1187
+ 3,
1188
+ 33
1189
+ ];
1190
+ iteration++;
1191
+ // Emit iteration event
1192
+ return [
1193
+ 4,
1194
+ {
1195
+ type: BRAIN_EVENTS.AGENT_ITERATION,
1196
+ stepTitle: step.block.title,
1197
+ stepId: step.id,
1198
+ iteration: iteration,
1199
+ options: (_this_options4 = this.options) !== null && _this_options4 !== void 0 ? _this_options4 : {},
1200
+ brainRunId: this.brainRunId
1201
+ }
1202
+ ];
1203
+ case 8:
1204
+ _state.sent();
1205
+ // Check if client supports generateText
1206
+ if (!this.client.generateText) {
1207
+ throw new Error('Client does not support generateText. Use a client that implements generateText for agent steps.');
1208
+ }
1209
+ // Build tools object for the client (description and inputSchema only)
1210
+ toolsForClient = {};
1211
+ _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1212
+ try {
1213
+ for(_iterator = Object.entries(mergedTools)[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1214
+ _step_value = _sliced_to_array(_step.value, 2), name = _step_value[0], toolDef = _step_value[1];
1215
+ tool = toolDef;
1216
+ toolsForClient[name] = {
1217
+ description: tool.description,
1218
+ inputSchema: tool.inputSchema
1219
+ };
1220
+ }
1221
+ } catch (err) {
1222
+ _didIteratorError = true;
1223
+ _iteratorError = err;
1224
+ } finally{
1225
+ try {
1226
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
1227
+ _iterator.return();
1228
+ }
1229
+ } finally{
1230
+ if (_didIteratorError) {
1231
+ throw _iteratorError;
1232
+ }
1233
+ }
1234
+ }
1235
+ // Prepend default system prompt to user's system prompt
1236
+ systemPrompt = config.system ? "".concat(DEFAULT_AGENT_SYSTEM_PROMPT, "\n\n").concat(config.system) : DEFAULT_AGENT_SYSTEM_PROMPT;
1237
+ return [
1238
+ 4,
1239
+ _await_async_generator(this.client.generateText({
1240
+ system: systemPrompt,
1241
+ messages: messages,
1242
+ tools: toolsForClient
1243
+ }))
1244
+ ];
1245
+ case 9:
1246
+ response = _state.sent();
1247
+ // Track tokens
1248
+ totalTokens += response.usage.totalTokens;
1249
+ if (!(config.maxTokens && totalTokens > config.maxTokens)) return [
1250
+ 3,
1251
+ 12
1252
+ ];
1253
+ return [
1254
+ 4,
1255
+ {
1256
+ type: BRAIN_EVENTS.AGENT_TOKEN_LIMIT,
1257
+ stepTitle: step.block.title,
1258
+ stepId: step.id,
1259
+ totalTokens: totalTokens,
1260
+ maxTokens: config.maxTokens,
1261
+ options: (_this_options5 = this.options) !== null && _this_options5 !== void 0 ? _this_options5 : {},
1262
+ brainRunId: this.brainRunId
1263
+ }
1264
+ ];
1265
+ case 10:
1266
+ _state.sent();
1267
+ return [
1268
+ 5,
1269
+ _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState))))
1270
+ ];
1271
+ case 11:
1272
+ _state.sent();
1273
+ return [
1274
+ 2
1275
+ ];
1276
+ case 12:
1277
+ if (!response.text) return [
1278
+ 3,
1279
+ 14
1280
+ ];
1281
+ return [
1282
+ 4,
1283
+ {
1284
+ type: BRAIN_EVENTS.AGENT_ASSISTANT_MESSAGE,
1285
+ stepTitle: step.block.title,
1286
+ stepId: step.id,
1287
+ content: response.text,
1288
+ options: (_this_options6 = this.options) !== null && _this_options6 !== void 0 ? _this_options6 : {},
1289
+ brainRunId: this.brainRunId
1290
+ }
1291
+ ];
1292
+ case 13:
1293
+ _state.sent();
1294
+ messages.push({
1295
+ role: 'assistant',
1296
+ content: response.text
1297
+ });
1298
+ _state.label = 14;
1299
+ case 14:
1300
+ if (!(!response.toolCalls || response.toolCalls.length === 0)) return [
1301
+ 3,
1302
+ 16
1303
+ ];
1304
+ return [
1305
+ 5,
1306
+ _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState))))
1307
+ ];
1308
+ case 15:
1309
+ _state.sent();
1310
+ return [
1311
+ 2
1312
+ ];
1313
+ case 16:
1314
+ _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
1315
+ _state.label = 17;
1316
+ case 17:
1317
+ _state.trys.push([
1318
+ 17,
1319
+ 30,
1320
+ 31,
1321
+ 32
1322
+ ]);
1323
+ _iterator1 = response.toolCalls[Symbol.iterator]();
1324
+ _state.label = 18;
1325
+ case 18:
1326
+ if (!!(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done)) return [
1327
+ 3,
1328
+ 29
1329
+ ];
1330
+ toolCall = _step1.value;
1331
+ return [
1332
+ 4,
1333
+ {
1334
+ type: BRAIN_EVENTS.AGENT_TOOL_CALL,
1335
+ stepTitle: step.block.title,
1336
+ stepId: step.id,
1337
+ toolName: toolCall.toolName,
1338
+ toolCallId: toolCall.toolCallId,
1339
+ input: toolCall.args,
1340
+ options: (_this_options7 = this.options) !== null && _this_options7 !== void 0 ? _this_options7 : {},
1341
+ brainRunId: this.brainRunId
1342
+ }
1343
+ ];
1344
+ case 19:
1345
+ _state.sent();
1346
+ tool1 = mergedTools[toolCall.toolName];
1347
+ if (!tool1) {
1348
+ throw new Error("Unknown tool: ".concat(toolCall.toolName));
1349
+ }
1350
+ if (!tool1.terminal) return [
1351
+ 3,
1352
+ 22
1353
+ ];
1354
+ return [
1355
+ 4,
1356
+ {
1357
+ type: BRAIN_EVENTS.AGENT_COMPLETE,
1358
+ stepTitle: step.block.title,
1359
+ stepId: step.id,
1360
+ terminalToolName: toolCall.toolName,
1361
+ result: toolCall.args,
1362
+ totalIterations: iteration,
1363
+ options: (_this_options8 = this.options) !== null && _this_options8 !== void 0 ? _this_options8 : {},
1364
+ brainRunId: this.brainRunId
1365
+ }
1366
+ ];
1367
+ case 20:
1368
+ _state.sent();
1369
+ // Merge terminal result into state
1370
+ this.currentState = _object_spread({}, this.currentState, toolCall.args);
1371
+ return [
1372
+ 5,
1373
+ _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState))))
1374
+ ];
1375
+ case 21:
1376
+ _state.sent();
1377
+ return [
1378
+ 2
1379
+ ];
1380
+ case 22:
1381
+ if (!tool1.execute) return [
1382
+ 3,
1383
+ 28
1384
+ ];
1385
+ return [
1386
+ 4,
1387
+ _await_async_generator(tool1.execute(toolCall.args))
1388
+ ];
1389
+ case 23:
1390
+ toolResult = _state.sent();
1391
+ if (!(toolResult && (typeof toolResult === "undefined" ? "undefined" : _type_of(toolResult)) === 'object' && 'waitFor' in toolResult)) return [
1392
+ 3,
1393
+ 26
1394
+ ];
1395
+ waitForResult = toolResult;
1396
+ // Normalize waitFor to array (supports single or multiple webhooks)
1397
+ webhooks = Array.isArray(waitForResult.waitFor) ? waitForResult.waitFor : [
1398
+ waitForResult.waitFor
1399
+ ];
1400
+ // Emit agent webhook event first (captures pending tool context)
1401
+ return [
1402
+ 4,
1403
+ {
1404
+ type: BRAIN_EVENTS.AGENT_WEBHOOK,
1405
+ stepTitle: step.block.title,
1406
+ stepId: step.id,
1407
+ toolCallId: toolCall.toolCallId,
1408
+ toolName: toolCall.toolName,
1409
+ input: toolCall.args,
1410
+ options: (_this_options9 = this.options) !== null && _this_options9 !== void 0 ? _this_options9 : {},
1411
+ brainRunId: this.brainRunId
1412
+ }
1413
+ ];
1414
+ case 24:
1415
+ _state.sent();
1416
+ // Then emit webhook event with all webhooks (first response wins)
1417
+ return [
1418
+ 4,
1419
+ {
1420
+ type: BRAIN_EVENTS.WEBHOOK,
1421
+ waitFor: webhooks.map(function(w) {
1422
+ return {
1423
+ slug: w.slug,
1424
+ identifier: w.identifier
1425
+ };
1426
+ }),
1427
+ options: (_this_options10 = this.options) !== null && _this_options10 !== void 0 ? _this_options10 : {},
1428
+ brainRunId: this.brainRunId
1429
+ }
1430
+ ];
1431
+ case 25:
1432
+ _state.sent();
1433
+ return [
1434
+ 2
1435
+ ];
1436
+ case 26:
1437
+ // Normal tool result
1438
+ return [
1439
+ 4,
1440
+ {
1441
+ type: BRAIN_EVENTS.AGENT_TOOL_RESULT,
1442
+ stepTitle: step.block.title,
1443
+ stepId: step.id,
1444
+ toolName: toolCall.toolName,
1445
+ toolCallId: toolCall.toolCallId,
1446
+ result: toolResult,
1447
+ options: (_this_options11 = this.options) !== null && _this_options11 !== void 0 ? _this_options11 : {},
1448
+ brainRunId: this.brainRunId
1449
+ }
1450
+ ];
1451
+ case 27:
1452
+ _state.sent();
1453
+ messages.push({
1454
+ role: 'tool',
1455
+ content: JSON.stringify(toolResult),
1456
+ toolCallId: toolCall.toolCallId,
1457
+ toolName: toolCall.toolName
1458
+ });
1459
+ _state.label = 28;
1460
+ case 28:
1461
+ _iteratorNormalCompletion1 = true;
1462
+ return [
1463
+ 3,
1464
+ 18
1465
+ ];
1466
+ case 29:
1467
+ return [
1468
+ 3,
1469
+ 32
1470
+ ];
1471
+ case 30:
1472
+ err = _state.sent();
1473
+ _didIteratorError1 = true;
1474
+ _iteratorError1 = err;
1475
+ return [
1476
+ 3,
1477
+ 32
1478
+ ];
1479
+ case 31:
1480
+ try {
1481
+ if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
1482
+ _iterator1.return();
1483
+ }
1484
+ } finally{
1485
+ if (_didIteratorError1) {
1486
+ throw _iteratorError1;
1487
+ }
1488
+ }
1489
+ return [
1490
+ 7
1491
+ ];
1492
+ case 32:
1493
+ return [
1494
+ 3,
1495
+ 7
1496
+ ];
1497
+ case 33:
1498
+ return [
1499
+ 2
1500
+ ];
1501
+ }
1502
+ });
1503
+ }).call(this);
1504
+ }
1505
+ },
1506
+ {
1507
+ key: "executeUIStep",
1508
+ value: /**
1509
+ * Execute a UI generation step.
1510
+ * Generates UI components, renders to HTML, creates page, and sets up webhook.
1511
+ */ function executeUIStep(step, stepBlock) {
1512
+ return _wrap_async_generator(function() {
1513
+ var prevState, uiConfig, prompt, uiResult, placementCount, placementInfo, _uiResult_text, webhookIdentifier, formAction, html, page, _uiConfig_responseSchema, webhook;
1514
+ return _ts_generator(this, function(_state) {
1515
+ switch(_state.label){
1516
+ case 0:
1517
+ prevState = this.currentState;
1518
+ // Validate required configuration
1519
+ if (!this.components) {
1520
+ throw new Error('UI step "'.concat(stepBlock.title, '" requires components to be configured via brain.withComponents()'));
1521
+ }
1522
+ if (!this.pages) {
1523
+ throw new Error('UI step "'.concat(stepBlock.title, '" requires pages service to be configured'));
1524
+ }
1525
+ uiConfig = stepBlock.uiConfig;
1526
+ return [
1527
+ 4,
1528
+ _await_async_generator(uiConfig.template(this.currentState, this.resources))
1529
+ ];
1530
+ case 1:
1531
+ prompt = _state.sent();
1532
+ return [
1533
+ 4,
1534
+ _await_async_generator(generateUI({
1535
+ client: this.client,
1536
+ prompt: prompt,
1537
+ components: this.components,
1538
+ schema: uiConfig.responseSchema,
1539
+ data: this.currentState
1540
+ }))
1541
+ ];
1542
+ case 2:
1543
+ uiResult = _state.sent();
1544
+ if (!uiResult.rootId) {
1545
+ // Provide detailed debug information
1546
+ placementCount = uiResult.placements.length;
1547
+ placementInfo = uiResult.placements.map(function(p) {
1548
+ var _p_parentId;
1549
+ return "".concat(p.component, "(parentId: ").concat((_p_parentId = p.parentId) !== null && _p_parentId !== void 0 ? _p_parentId : 'null', ")");
1550
+ }).join(', ');
1551
+ if (placementCount === 0) {
1552
+ ;
1553
+ 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)'));
1554
+ } else {
1555
+ 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.");
1556
+ }
1557
+ }
1558
+ // Create unique identifier for this form submission webhook
1559
+ webhookIdentifier = "".concat(this.brainRunId, "-").concat(step.id);
1560
+ // Construct form action URL for the webhook
1561
+ formAction = "".concat(this.env.origin, "/webhooks/system/ui-form?identifier=").concat(encodeURIComponent(webhookIdentifier));
1562
+ // Generate HTML page
1563
+ html = generatePageHtml({
1564
+ placements: uiResult.placements,
1565
+ rootId: uiResult.rootId,
1566
+ data: this.currentState,
1567
+ title: stepBlock.title,
1568
+ formAction: formAction
1569
+ });
1570
+ return [
1571
+ 4,
1572
+ _await_async_generator(this.pages.create(html))
1573
+ ];
1574
+ case 3:
1575
+ page = _state.sent();
1576
+ // Create webhook registration for form submissions
1577
+ // Uses a built-in 'ui-form' webhook slug that the backend knows how to handle
1578
+ webhook = {
1579
+ slug: 'ui-form',
1580
+ identifier: webhookIdentifier,
1581
+ schema: (_uiConfig_responseSchema = uiConfig.responseSchema) !== null && _uiConfig_responseSchema !== void 0 ? _uiConfig_responseSchema : z.record(z.unknown())
1582
+ };
1583
+ // Set currentPage for the next step to access
1584
+ this.currentPage = {
1585
+ url: page.url,
1586
+ webhook: webhook
1587
+ };
1588
+ // State doesn't change from UI step - it just sets up the page
1589
+ // The next step will receive the page object and can use waitFor
1590
+ return [
1591
+ 5,
1592
+ _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState))))
1593
+ ];
1594
+ case 4:
1595
+ _state.sent();
1596
+ return [
1597
+ 2
1598
+ ];
1599
+ }
1600
+ });
1601
+ }).call(this);
1602
+ }
1603
+ },
1604
+ {
1605
+ key: "completeStep",
1606
+ value: function completeStep(step, prevState) {
1607
+ var patch, _this_options;
1608
+ return _ts_generator(this, function(_state) {
1609
+ switch(_state.label){
1610
+ case 0:
1611
+ step.withStatus(STATUS.COMPLETE);
1612
+ // Create patch for the state change
1613
+ patch = createPatch(prevState, this.currentState);
1614
+ step.withPatch(patch);
1615
+ return [
1616
+ 4,
1617
+ {
1618
+ type: BRAIN_EVENTS.STEP_COMPLETE,
1619
+ status: STATUS.RUNNING,
1620
+ stepTitle: step.block.title,
1621
+ stepId: step.id,
1622
+ patch: patch,
1623
+ options: (_this_options = this.options) !== null && _this_options !== void 0 ? _this_options : {},
1624
+ brainRunId: this.brainRunId
1625
+ }
1626
+ ];
1627
+ case 1:
1628
+ _state.sent();
1629
+ return [
1630
+ 2
1631
+ ];
1632
+ }
1633
+ });
1634
+ }
1635
+ }
1636
+ ]);
1637
+ return BrainEventStream;
1638
+ }();