@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
@@ -1,1912 +1,5 @@
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 asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
167
- try {
168
- var info = gen[key](arg);
169
- var value = info.value;
170
- } catch (error) {
171
- reject(error);
172
- return;
173
- }
174
- if (info.done) {
175
- resolve(value);
176
- } else {
177
- Promise.resolve(value).then(_next, _throw);
178
- }
179
- }
180
- function _async_to_generator(fn) {
181
- return function() {
182
- var self = this, args = arguments;
183
- return new Promise(function(resolve, reject) {
184
- var gen = fn.apply(self, args);
185
- function _next(value) {
186
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
187
- }
188
- function _throw(err) {
189
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
190
- }
191
- _next(undefined);
192
- });
193
- };
194
- }
195
- function _await_async_generator(value) {
196
- return new _overload_yield(value, 0);
197
- }
198
- function _class_call_check(instance, Constructor) {
199
- if (!(instance instanceof Constructor)) {
200
- throw new TypeError("Cannot call a class as a function");
201
- }
202
- }
203
- function _defineProperties(target, props) {
204
- for(var i = 0; i < props.length; i++){
205
- var descriptor = props[i];
206
- descriptor.enumerable = descriptor.enumerable || false;
207
- descriptor.configurable = true;
208
- if ("value" in descriptor) descriptor.writable = true;
209
- Object.defineProperty(target, descriptor.key, descriptor);
210
- }
211
- }
212
- function _create_class(Constructor, protoProps, staticProps) {
213
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
214
- if (staticProps) _defineProperties(Constructor, staticProps);
215
- return Constructor;
216
- }
217
- function _define_property(obj, key, value) {
218
- if (key in obj) {
219
- Object.defineProperty(obj, key, {
220
- value: value,
221
- enumerable: true,
222
- configurable: true,
223
- writable: true
224
- });
225
- } else {
226
- obj[key] = value;
227
- }
228
- return obj;
229
- }
230
- function _iterable_to_array_limit(arr, i) {
231
- var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
232
- if (_i == null) return;
233
- var _arr = [];
234
- var _n = true;
235
- var _d = false;
236
- var _s, _e;
237
- try {
238
- for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
239
- _arr.push(_s.value);
240
- if (i && _arr.length === i) break;
241
- }
242
- } catch (err) {
243
- _d = true;
244
- _e = err;
245
- } finally{
246
- try {
247
- if (!_n && _i["return"] != null) _i["return"]();
248
- } finally{
249
- if (_d) throw _e;
250
- }
251
- }
252
- return _arr;
253
- }
254
- function _non_iterable_rest() {
255
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
256
- }
257
- function _object_spread(target) {
258
- for(var i = 1; i < arguments.length; i++){
259
- var source = arguments[i] != null ? arguments[i] : {};
260
- var ownKeys = Object.keys(source);
261
- if (typeof Object.getOwnPropertySymbols === "function") {
262
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
263
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
264
- }));
265
- }
266
- ownKeys.forEach(function(key) {
267
- _define_property(target, key, source[key]);
268
- });
269
- }
270
- return target;
271
- }
272
- function ownKeys(object, enumerableOnly) {
273
- var keys = Object.keys(object);
274
- if (Object.getOwnPropertySymbols) {
275
- var symbols = Object.getOwnPropertySymbols(object);
276
- if (enumerableOnly) {
277
- symbols = symbols.filter(function(sym) {
278
- return Object.getOwnPropertyDescriptor(object, sym).enumerable;
279
- });
280
- }
281
- keys.push.apply(keys, symbols);
282
- }
283
- return keys;
284
- }
285
- function _object_spread_props(target, source) {
286
- source = source != null ? source : {};
287
- if (Object.getOwnPropertyDescriptors) {
288
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
289
- } else {
290
- ownKeys(Object(source)).forEach(function(key) {
291
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
292
- });
293
- }
294
- return target;
295
- }
296
- function _object_without_properties(source, excluded) {
297
- if (source == null) return {};
298
- var target = _object_without_properties_loose(source, excluded);
299
- var key, i;
300
- if (Object.getOwnPropertySymbols) {
301
- var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
302
- for(i = 0; i < sourceSymbolKeys.length; i++){
303
- key = sourceSymbolKeys[i];
304
- if (excluded.indexOf(key) >= 0) continue;
305
- if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
306
- target[key] = source[key];
307
- }
308
- }
309
- return target;
310
- }
311
- function _object_without_properties_loose(source, excluded) {
312
- if (source == null) return {};
313
- var target = {};
314
- var sourceKeys = Object.keys(source);
315
- var key, i;
316
- for(i = 0; i < sourceKeys.length; i++){
317
- key = sourceKeys[i];
318
- if (excluded.indexOf(key) >= 0) continue;
319
- target[key] = source[key];
320
- }
321
- return target;
322
- }
323
- function _overload_yield(value, kind) {
324
- this.v = value;
325
- this.k = kind;
326
- }
327
- function _sliced_to_array(arr, i) {
328
- return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
329
- }
330
- function _type_of(obj) {
331
- "@swc/helpers - typeof";
332
- return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
333
- }
334
- function _unsupported_iterable_to_array(o, minLen) {
335
- if (!o) return;
336
- if (typeof o === "string") return _array_like_to_array(o, minLen);
337
- var n = Object.prototype.toString.call(o).slice(8, -1);
338
- if (n === "Object" && o.constructor) n = o.constructor.name;
339
- if (n === "Map" || n === "Set") return Array.from(n);
340
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
341
- }
342
- function _wrap_async_generator(fn) {
343
- return function() {
344
- return new _async_generator(fn.apply(this, arguments));
345
- };
346
- }
347
- function _ts_generator(thisArg, body) {
348
- var f, y, t, _ = {
349
- label: 0,
350
- sent: function() {
351
- if (t[0] & 1) throw t[1];
352
- return t[1];
353
- },
354
- trys: [],
355
- ops: []
356
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
357
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
358
- return this;
359
- }), g;
360
- function verb(n) {
361
- return function(v) {
362
- return step([
363
- n,
364
- v
365
- ]);
366
- };
367
- }
368
- function step(op) {
369
- if (f) throw new TypeError("Generator is already executing.");
370
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
371
- 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;
372
- if (y = 0, t) op = [
373
- op[0] & 2,
374
- t.value
375
- ];
376
- switch(op[0]){
377
- case 0:
378
- case 1:
379
- t = op;
380
- break;
381
- case 4:
382
- _.label++;
383
- return {
384
- value: op[1],
385
- done: false
386
- };
387
- case 5:
388
- _.label++;
389
- y = op[1];
390
- op = [
391
- 0
392
- ];
393
- continue;
394
- case 7:
395
- op = _.ops.pop();
396
- _.trys.pop();
397
- continue;
398
- default:
399
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
400
- _ = 0;
401
- continue;
402
- }
403
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
404
- _.label = op[1];
405
- break;
406
- }
407
- if (op[0] === 6 && _.label < t[1]) {
408
- _.label = t[1];
409
- t = op;
410
- break;
411
- }
412
- if (t && _.label < t[2]) {
413
- _.label = t[2];
414
- _.ops.push(op);
415
- break;
416
- }
417
- if (t[2]) _.ops.pop();
418
- _.trys.pop();
419
- continue;
420
- }
421
- op = body.call(thisArg, _);
422
- } catch (e) {
423
- op = [
424
- 6,
425
- e
426
- ];
427
- y = 0;
428
- } finally{
429
- f = t = 0;
430
- }
431
- if (op[0] & 5) throw op[1];
432
- return {
433
- value: op[0] ? op[1] : void 0,
434
- done: true
435
- };
436
- }
437
- }
438
- function _ts_values(o) {
439
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
440
- if (m) return m.call(o);
441
- if (o && typeof o.length === "number") return {
442
- next: function() {
443
- if (o && i >= o.length) o = void 0;
444
- return {
445
- value: o && o[i++],
446
- done: !o
447
- };
448
- }
449
- };
450
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
451
- }
452
- import { v4 as uuidv4 } from 'uuid';
453
- import { STATUS, BRAIN_EVENTS } from './constants.js';
454
- import { createPatch, applyPatches } from './json-patch.js';
455
- /**
456
- * Default runtime environment used when env is not provided.
457
- * This ensures backward compatibility with existing code.
458
- */ export var DEFAULT_ENV = {
459
- origin: 'http://localhost:3000',
460
- secrets: {}
461
- };
462
- /**
463
- * Heartbeat interval in milliseconds.
464
- * Emits heartbeat events during long-running operations to keep Durable Objects alive.
465
- */ export var HEARTBEAT_INTERVAL_MS = 5000;
466
- /**
467
- * Default system prompt prepended to all loop steps.
468
- * Explains tool execution quirks to the LLM.
469
- */ var DEFAULT_LOOP_SYSTEM_PROMPT = "## Tool Execution Behavior\n- Tools are executed sequentially in the order you call them\n- If a tool triggers a webhook (e.g., human approval), remaining tools in your response will NOT execute - you'll need to call them again after resuming\n- When waiting on multiple webhooks (e.g., Slack + email), the first webhook response received will resume execution\n- Terminal tools end the loop immediately - no further tools or iterations will run\n\n## Resumption Context\nWhen resuming after a webhook response, that response appears as the tool result in your conversation history.";
470
- /**
471
- * Simple sleep helper that returns a promise resolving after the specified delay.
472
- */ var sleep = function(ms) {
473
- return new Promise(function(resolve) {
474
- return setTimeout(resolve, ms);
475
- });
476
- };
477
- export var Brain = /*#__PURE__*/ function() {
478
- "use strict";
479
- function Brain(title, description) {
480
- _class_call_check(this, Brain);
481
- _define_property(this, "title", void 0);
482
- _define_property(this, "description", void 0);
483
- _define_property(this, "blocks", void 0);
484
- _define_property(this, "type", void 0);
485
- _define_property(this, "services", void 0);
486
- _define_property(this, "optionsSchema", void 0);
487
- this.title = title;
488
- this.description = description;
489
- this.blocks = [];
490
- this.type = 'brain';
491
- this.services = {};
492
- }
493
- _create_class(Brain, [
494
- {
495
- key: "structure",
496
- get: function get() {
497
- return {
498
- title: this.title,
499
- description: this.description,
500
- steps: this.blocks.map(function(block) {
501
- if (block.type === 'step') {
502
- return {
503
- type: 'step',
504
- title: block.title
505
- };
506
- } else if (block.type === 'loop') {
507
- return {
508
- type: 'loop',
509
- title: block.title
510
- };
511
- } else {
512
- // block.type === 'brain'
513
- return {
514
- type: 'brain',
515
- title: block.title,
516
- innerBrain: block.innerBrain.structure
517
- };
518
- }
519
- })
520
- };
521
- }
522
- },
523
- {
524
- // New method to add services
525
- key: "withServices",
526
- value: function withServices(services) {
527
- var nextBrain = new Brain(this.title, this.description).withBlocks(this.blocks);
528
- // Set services
529
- nextBrain.services = services;
530
- // Copy optionsSchema to maintain it through the chain
531
- nextBrain.optionsSchema = this.optionsSchema;
532
- return nextBrain;
533
- }
534
- },
535
- {
536
- key: "withOptionsSchema",
537
- value: function withOptionsSchema(schema) {
538
- var nextBrain = new Brain(this.title, this.description).withBlocks(this.blocks);
539
- nextBrain.optionsSchema = schema;
540
- nextBrain.services = this.services;
541
- return nextBrain;
542
- }
543
- },
544
- {
545
- key: "step",
546
- value: function step(title, action) {
547
- var stepBlock = {
548
- type: 'step',
549
- title: title,
550
- action: action
551
- };
552
- this.blocks.push(stepBlock);
553
- // Create next brain with inferred response type
554
- var nextBrain = new Brain(this.title, this.description).withBlocks(this.blocks);
555
- nextBrain.services = this.services;
556
- nextBrain.optionsSchema = this.optionsSchema;
557
- return nextBrain;
558
- }
559
- },
560
- {
561
- key: "brain",
562
- value: function brain(title, innerBrain, action, initialState) {
563
- var nestedBlock = {
564
- type: 'brain',
565
- title: title,
566
- innerBrain: innerBrain,
567
- initialState: initialState || function() {
568
- return {};
569
- },
570
- action: function(outerState, innerState, services) {
571
- return action({
572
- state: outerState,
573
- brainState: innerState,
574
- services: services
575
- });
576
- }
577
- };
578
- this.blocks.push(nestedBlock);
579
- return this.nextBrain();
580
- }
581
- },
582
- {
583
- /**
584
- * Add an agentic loop step that runs an LLM with tools.
585
- * The loop continues until a terminal tool is called, no tool calls are returned,
586
- * or maxTokens is exceeded.
587
- */ key: "loop",
588
- value: function loop(title, configFn) {
589
- var loopBlock = {
590
- type: 'loop',
591
- title: title,
592
- configFn: configFn
593
- };
594
- this.blocks.push(loopBlock);
595
- var nextBrain = new Brain(this.title, this.description).withBlocks(this.blocks);
596
- nextBrain.services = this.services;
597
- nextBrain.optionsSchema = this.optionsSchema;
598
- return nextBrain;
599
- }
600
- },
601
- {
602
- // TResponseKey:
603
- // The response key must be a string literal, so if defining a response model
604
- // a consumer of this brain must use "as const" to ensure the key is a string literal
605
- // this type makes sure that the will get a ts error if they don't.
606
- key: "prompt",
607
- value: function prompt(title, config, reduce) {
608
- var promptBlock = {
609
- type: 'step',
610
- title: title,
611
- action: function(_param) {
612
- return _async_to_generator(function() {
613
- var state, runClient, options, resources, webhookResponse, services, template, outputSchema, stepClient, schema, schemaName, client, prompt, response, stateWithResponse;
614
- return _ts_generator(this, function(_state) {
615
- switch(_state.label){
616
- case 0:
617
- state = _param.state, runClient = _param.client, options = _param.options, resources = _param.resources, webhookResponse = _param.response, services = _object_without_properties(_param, [
618
- "state",
619
- "client",
620
- "options",
621
- "resources",
622
- "response"
623
- ]);
624
- template = config.template, outputSchema = config.outputSchema, stepClient = config.client;
625
- schema = outputSchema.schema, schemaName = outputSchema.name;
626
- client = stepClient !== null && stepClient !== void 0 ? stepClient : runClient;
627
- return [
628
- 4,
629
- template(state, resources)
630
- ];
631
- case 1:
632
- prompt = _state.sent();
633
- return [
634
- 4,
635
- client.generateObject({
636
- schema: schema,
637
- schemaName: schemaName,
638
- prompt: prompt
639
- })
640
- ];
641
- case 2:
642
- response = _state.sent();
643
- stateWithResponse = _object_spread_props(_object_spread({}, state), _define_property({}, config.outputSchema.name, response));
644
- return [
645
- 2,
646
- reduce ? reduce(_object_spread({
647
- state: state,
648
- response: response,
649
- options: options,
650
- prompt: prompt,
651
- resources: resources
652
- }, services)) : stateWithResponse
653
- ];
654
- }
655
- });
656
- })();
657
- }
658
- };
659
- this.blocks.push(promptBlock);
660
- return this.nextBrain();
661
- }
662
- },
663
- {
664
- key: "run",
665
- value: // Implementation signature
666
- function run(params) {
667
- return _wrap_async_generator(function() {
668
- var _this, title, description, blocks, validatedOptions, stream;
669
- return _ts_generator(this, function(_state) {
670
- switch(_state.label){
671
- case 0:
672
- _this = this, title = _this.title, description = _this.description, blocks = _this.blocks;
673
- if (this.optionsSchema) {
674
- // Just call parse - Zod handles defaults automatically
675
- validatedOptions = this.optionsSchema.parse(params.options || {});
676
- } else {
677
- // If no schema is defined but options are provided, throw error
678
- if (params.options && Object.keys(params.options).length > 0) {
679
- throw new Error("Brain '".concat(this.title, "' received options but no schema was defined. Use withOptionsSchema() to define a schema for options."));
680
- }
681
- validatedOptions = {};
682
- }
683
- stream = new BrainEventStream(_object_spread_props(_object_spread({
684
- title: title,
685
- description: description,
686
- blocks: blocks
687
- }, params), {
688
- options: validatedOptions,
689
- services: this.services
690
- }));
691
- return [
692
- 5,
693
- _ts_values(_async_generator_delegate(_async_iterator(stream.next())))
694
- ];
695
- case 1:
696
- _state.sent();
697
- return [
698
- 2
699
- ];
700
- }
701
- });
702
- }).call(this);
703
- }
704
- },
705
- {
706
- key: "withBlocks",
707
- value: function withBlocks(blocks) {
708
- this.blocks = blocks;
709
- return this;
710
- }
711
- },
712
- {
713
- key: "nextBrain",
714
- value: function nextBrain() {
715
- // Pass default options to the next brain
716
- var nextBrain = new Brain(this.title, this.description).withBlocks(this.blocks);
717
- // Copy services to the next brain
718
- nextBrain.services = this.services;
719
- // Copy optionsSchema to the next brain
720
- nextBrain.optionsSchema = this.optionsSchema;
721
- return nextBrain;
722
- }
723
- }
724
- ]);
725
- return Brain;
726
- }();
727
- var MAX_RETRIES = 1;
728
- var Step = /*#__PURE__*/ function() {
729
- "use strict";
730
- function Step(block, id) {
731
- _class_call_check(this, Step);
732
- _define_property(this, "block", void 0);
733
- _define_property(this, "id", void 0);
734
- _define_property(this, "patch", void 0);
735
- _define_property(this, "status", void 0);
736
- this.block = block;
737
- this.status = STATUS.PENDING;
738
- this.id = id || uuidv4();
739
- }
740
- _create_class(Step, [
741
- {
742
- key: "withPatch",
743
- value: function withPatch(patch) {
744
- this.patch = patch;
745
- return this;
746
- }
747
- },
748
- {
749
- key: "withStatus",
750
- value: function withStatus(status) {
751
- this.status = status;
752
- return this;
753
- }
754
- },
755
- {
756
- key: "serialized",
757
- get: function get() {
758
- return {
759
- id: this.id,
760
- title: this.block.title,
761
- status: this.status,
762
- patch: typeof this.patch === 'string' ? JSON.parse(this.patch) : this.patch
763
- };
764
- }
765
- }
766
- ]);
767
- return Step;
768
- }();
769
- var BrainEventStream = /*#__PURE__*/ function() {
770
- "use strict";
771
- function BrainEventStream(params) {
772
- _class_call_check(this, BrainEventStream);
773
- _define_property(this, "currentState", void 0);
774
- _define_property(this, "steps", void 0);
775
- _define_property(this, "currentStepIndex", 0);
776
- _define_property(this, "initialState", void 0);
777
- _define_property(this, "brainRunId", void 0);
778
- _define_property(this, "title", void 0);
779
- _define_property(this, "description", void 0);
780
- _define_property(this, "client", void 0);
781
- _define_property(this, "options", void 0);
782
- _define_property(this, "services", void 0);
783
- _define_property(this, "resources", void 0);
784
- _define_property(this, "pages", void 0);
785
- _define_property(this, "env", void 0);
786
- _define_property(this, "currentResponse", undefined);
787
- _define_property(this, "loopResumeContext", undefined);
788
- _define_property(this, "initialCompletedSteps", void 0);
789
- 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, loopResumeContext = params.loopResumeContext;
790
- this.initialState = initialState;
791
- this.title = title;
792
- this.description = description;
793
- this.client = client;
794
- this.options = options;
795
- this.services = services;
796
- this.resources = resources;
797
- this.pages = pages;
798
- this.env = env !== null && env !== void 0 ? env : DEFAULT_ENV;
799
- this.initialCompletedSteps = initialCompletedSteps;
800
- // Initialize steps array with UUIDs and pending status
801
- this.steps = blocks.map(function(block, index) {
802
- var completedStep = initialCompletedSteps === null || initialCompletedSteps === void 0 ? void 0 : initialCompletedSteps[index];
803
- if (completedStep) {
804
- return new Step(block, completedStep.id).withStatus(completedStep.status).withPatch(completedStep.patch);
805
- }
806
- return new Step(block);
807
- });
808
- this.currentState = clone(this.initialState);
809
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
810
- try {
811
- for(var _iterator = this.steps[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
812
- var step = _step.value;
813
- if (step.serialized.status === STATUS.COMPLETE && step.serialized.patch) {
814
- this.currentState = applyPatches(this.currentState, [
815
- step.serialized.patch
816
- ]);
817
- }
818
- }
819
- } catch (err) {
820
- _didIteratorError = true;
821
- _iteratorError = err;
822
- } finally{
823
- try {
824
- if (!_iteratorNormalCompletion && _iterator.return != null) {
825
- _iterator.return();
826
- }
827
- } finally{
828
- if (_didIteratorError) {
829
- throw _iteratorError;
830
- }
831
- }
832
- }
833
- // Use provided ID if available, otherwise generate one
834
- this.brainRunId = providedBrainRunId !== null && providedBrainRunId !== void 0 ? providedBrainRunId : uuidv4();
835
- // Set loop resume context if provided (for loop webhook restarts)
836
- if (loopResumeContext) {
837
- this.loopResumeContext = loopResumeContext;
838
- // Note: We intentionally do NOT set currentResponse here.
839
- // For loop resumption, the webhook response should flow through
840
- // the messages array (via loopResumeContext), not through the
841
- // config function's response parameter. The config function is
842
- // for loop setup, not for processing webhook responses.
843
- } else if (response) {
844
- // Set initial response only for non-loop webhook restarts
845
- this.currentResponse = response;
846
- }
847
- }
848
- _create_class(BrainEventStream, [
849
- {
850
- key: "next",
851
- value: function next() {
852
- return _wrap_async_generator(function() {
853
- var _this, steps, brainTitle, brainDescription, currentState, options, brainRunId, hasCompletedSteps, step, err, error, currentStep;
854
- return _ts_generator(this, function(_state) {
855
- switch(_state.label){
856
- case 0:
857
- _this = this, steps = _this.steps, brainTitle = _this.title, brainDescription = _this.description, currentState = _this.currentState, options = _this.options, brainRunId = _this.brainRunId;
858
- _state.label = 1;
859
- case 1:
860
- _state.trys.push([
861
- 1,
862
- 11,
863
- ,
864
- 14
865
- ]);
866
- hasCompletedSteps = steps.some(function(step) {
867
- return step.serialized.status !== STATUS.PENDING;
868
- });
869
- return [
870
- 4,
871
- {
872
- type: hasCompletedSteps ? BRAIN_EVENTS.RESTART : BRAIN_EVENTS.START,
873
- status: STATUS.RUNNING,
874
- brainTitle: brainTitle,
875
- brainDescription: brainDescription,
876
- initialState: currentState,
877
- options: options,
878
- brainRunId: brainRunId
879
- }
880
- ];
881
- case 2:
882
- _state.sent();
883
- // Emit initial step status after brain starts
884
- return [
885
- 4,
886
- {
887
- type: BRAIN_EVENTS.STEP_STATUS,
888
- steps: steps.map(function(step) {
889
- var _step_serialized = step.serialized, patch = _step_serialized.patch, rest = _object_without_properties(_step_serialized, [
890
- "patch"
891
- ]);
892
- return rest;
893
- }),
894
- options: options,
895
- brainRunId: brainRunId
896
- }
897
- ];
898
- case 3:
899
- _state.sent();
900
- _state.label = 4;
901
- case 4:
902
- if (!(this.currentStepIndex < steps.length)) return [
903
- 3,
904
- 9
905
- ];
906
- step = steps[this.currentStepIndex];
907
- // Skip completed steps
908
- if (step.serialized.status === STATUS.COMPLETE) {
909
- this.currentStepIndex++;
910
- return [
911
- 3,
912
- 4
913
- ];
914
- }
915
- // Step start event
916
- return [
917
- 4,
918
- {
919
- type: BRAIN_EVENTS.STEP_START,
920
- status: STATUS.RUNNING,
921
- stepTitle: step.block.title,
922
- stepId: step.id,
923
- options: options,
924
- brainRunId: brainRunId
925
- }
926
- ];
927
- case 5:
928
- _state.sent();
929
- step.withStatus(STATUS.RUNNING);
930
- // Step Status Event to indicate that the step is running
931
- return [
932
- 4,
933
- {
934
- type: BRAIN_EVENTS.STEP_STATUS,
935
- steps: steps.map(function(step) {
936
- var _step_serialized = step.serialized, patch = _step_serialized.patch, rest = _object_without_properties(_step_serialized, [
937
- "patch"
938
- ]);
939
- return rest;
940
- }),
941
- options: options,
942
- brainRunId: brainRunId
943
- }
944
- ];
945
- case 6:
946
- _state.sent();
947
- // Execute step and yield the STEP_COMPLETE event and
948
- // all events from inner brains if any
949
- return [
950
- 5,
951
- _ts_values(_async_generator_delegate(_async_iterator(this.executeStep(step))))
952
- ];
953
- case 7:
954
- _state.sent();
955
- // Step Status Event
956
- return [
957
- 4,
958
- {
959
- type: BRAIN_EVENTS.STEP_STATUS,
960
- steps: steps.map(function(step) {
961
- var _step_serialized = step.serialized, patch = _step_serialized.patch, rest = _object_without_properties(_step_serialized, [
962
- "patch"
963
- ]);
964
- return rest;
965
- }),
966
- options: options,
967
- brainRunId: brainRunId
968
- }
969
- ];
970
- case 8:
971
- _state.sent();
972
- this.currentStepIndex++;
973
- return [
974
- 3,
975
- 4
976
- ];
977
- case 9:
978
- return [
979
- 4,
980
- {
981
- type: BRAIN_EVENTS.COMPLETE,
982
- status: STATUS.COMPLETE,
983
- brainTitle: brainTitle,
984
- brainDescription: brainDescription,
985
- brainRunId: brainRunId,
986
- options: options
987
- }
988
- ];
989
- case 10:
990
- _state.sent();
991
- return [
992
- 3,
993
- 14
994
- ];
995
- case 11:
996
- err = _state.sent();
997
- error = err;
998
- currentStep = steps[this.currentStepIndex];
999
- currentStep === null || currentStep === void 0 ? void 0 : currentStep.withStatus(STATUS.ERROR);
1000
- return [
1001
- 4,
1002
- {
1003
- type: BRAIN_EVENTS.ERROR,
1004
- status: STATUS.ERROR,
1005
- brainTitle: brainTitle,
1006
- brainDescription: brainDescription,
1007
- brainRunId: brainRunId,
1008
- error: {
1009
- name: error.name,
1010
- message: error.message,
1011
- stack: error.stack
1012
- },
1013
- options: options
1014
- }
1015
- ];
1016
- case 12:
1017
- _state.sent();
1018
- // Step Status Event
1019
- return [
1020
- 4,
1021
- {
1022
- type: BRAIN_EVENTS.STEP_STATUS,
1023
- steps: steps.map(function(step) {
1024
- var _step_serialized = step.serialized, patch = _step_serialized.patch, rest = _object_without_properties(_step_serialized, [
1025
- "patch"
1026
- ]);
1027
- return rest;
1028
- }),
1029
- options: options,
1030
- brainRunId: brainRunId
1031
- }
1032
- ];
1033
- case 13:
1034
- _state.sent();
1035
- throw error;
1036
- case 14:
1037
- return [
1038
- 2
1039
- ];
1040
- }
1041
- });
1042
- }).call(this);
1043
- }
1044
- },
1045
- {
1046
- key: "executeStep",
1047
- value: function executeStep(step) {
1048
- return _wrap_async_generator(function() {
1049
- var block, _this_initialCompletedSteps, 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, stepBlock, retries, result, _this_options2, actionPromise, error, _this_options3, serializedWaitFor;
1050
- return _ts_generator(this, function(_state) {
1051
- switch(_state.label){
1052
- case 0:
1053
- block = step.block;
1054
- if (!(block.type === 'brain')) return [
1055
- 3,
1056
- 16
1057
- ];
1058
- initialState = typeof block.initialState === 'function' ? block.initialState(this.currentState) : block.initialState;
1059
- // Check if this inner brain step has completed inner steps (for resume)
1060
- stepIndex = this.steps.indexOf(step);
1061
- completedStepEntry = (_this_initialCompletedSteps = this.initialCompletedSteps) === null || _this_initialCompletedSteps === void 0 ? void 0 : _this_initialCompletedSteps[stepIndex];
1062
- innerCompletedSteps = completedStepEntry === null || completedStepEntry === void 0 ? void 0 : completedStepEntry.innerSteps;
1063
- // Run inner brain and yield all its events
1064
- // Pass brainRunId so inner brain shares outer brain's run ID
1065
- // Pass innerSteps and response for resume scenarios
1066
- patches = [];
1067
- // If resuming, include patches from already-completed inner steps
1068
- // These won't be re-emitted as STEP_COMPLETE events
1069
- if (innerCompletedSteps) {
1070
- _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1071
- try {
1072
- for(_iterator = innerCompletedSteps[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1073
- completedStep = _step.value;
1074
- if (completedStep.patch) {
1075
- patches.push(completedStep.patch);
1076
- }
1077
- }
1078
- } catch (err) {
1079
- _didIteratorError = true;
1080
- _iteratorError = err;
1081
- } finally{
1082
- try {
1083
- if (!_iteratorNormalCompletion && _iterator.return != null) {
1084
- _iterator.return();
1085
- }
1086
- } finally{
1087
- if (_didIteratorError) {
1088
- throw _iteratorError;
1089
- }
1090
- }
1091
- }
1092
- }
1093
- innerBrainPaused = false;
1094
- innerRun = innerCompletedSteps ? block.innerBrain.run({
1095
- resources: this.resources,
1096
- client: this.client,
1097
- initialState: initialState,
1098
- initialCompletedSteps: innerCompletedSteps,
1099
- options: (_this_options = this.options) !== null && _this_options !== void 0 ? _this_options : {},
1100
- pages: this.pages,
1101
- env: this.env,
1102
- brainRunId: this.brainRunId,
1103
- response: this.currentResponse
1104
- }) : block.innerBrain.run({
1105
- resources: this.resources,
1106
- client: this.client,
1107
- initialState: initialState,
1108
- options: (_this_options1 = this.options) !== null && _this_options1 !== void 0 ? _this_options1 : {},
1109
- pages: this.pages,
1110
- env: this.env,
1111
- brainRunId: this.brainRunId
1112
- });
1113
- _iteratorAbruptCompletion = false, _didIteratorError1 = false;
1114
- _state.label = 1;
1115
- case 1:
1116
- _state.trys.push([
1117
- 1,
1118
- 7,
1119
- 8,
1120
- 13
1121
- ]);
1122
- _iterator1 = _async_iterator(innerRun);
1123
- _state.label = 2;
1124
- case 2:
1125
- return [
1126
- 4,
1127
- _await_async_generator(_iterator1.next())
1128
- ];
1129
- case 3:
1130
- if (!(_iteratorAbruptCompletion = !(_step1 = _state.sent()).done)) return [
1131
- 3,
1132
- 6
1133
- ];
1134
- _value = _step1.value;
1135
- event = _value;
1136
- return [
1137
- 4,
1138
- event
1139
- ];
1140
- case 4:
1141
- _state.sent(); // Forward all inner brain events
1142
- if (event.type === BRAIN_EVENTS.STEP_COMPLETE) {
1143
- patches.push(event.patch);
1144
- }
1145
- // If inner brain yielded a WEBHOOK event, it's pausing
1146
- if (event.type === BRAIN_EVENTS.WEBHOOK) {
1147
- innerBrainPaused = true;
1148
- }
1149
- // If inner brain completed, break immediately to prevent hanging
1150
- if (event.type === BRAIN_EVENTS.COMPLETE) {
1151
- return [
1152
- 3,
1153
- 6
1154
- ];
1155
- }
1156
- _state.label = 5;
1157
- case 5:
1158
- _iteratorAbruptCompletion = false;
1159
- return [
1160
- 3,
1161
- 2
1162
- ];
1163
- case 6:
1164
- return [
1165
- 3,
1166
- 13
1167
- ];
1168
- case 7:
1169
- err1 = _state.sent();
1170
- _didIteratorError1 = true;
1171
- _iteratorError1 = err1;
1172
- return [
1173
- 3,
1174
- 13
1175
- ];
1176
- case 8:
1177
- _state.trys.push([
1178
- 8,
1179
- ,
1180
- 11,
1181
- 12
1182
- ]);
1183
- if (!(_iteratorAbruptCompletion && _iterator1.return != null)) return [
1184
- 3,
1185
- 10
1186
- ];
1187
- return [
1188
- 4,
1189
- _await_async_generator(_iterator1.return())
1190
- ];
1191
- case 9:
1192
- _state.sent();
1193
- _state.label = 10;
1194
- case 10:
1195
- return [
1196
- 3,
1197
- 12
1198
- ];
1199
- case 11:
1200
- if (_didIteratorError1) {
1201
- throw _iteratorError1;
1202
- }
1203
- return [
1204
- 7
1205
- ];
1206
- case 12:
1207
- return [
1208
- 7
1209
- ];
1210
- case 13:
1211
- // If inner brain paused for webhook, don't complete the outer brain step
1212
- // The outer brain should also pause
1213
- if (innerBrainPaused) {
1214
- return [
1215
- 2
1216
- ];
1217
- }
1218
- // Apply collected patches to get final inner state
1219
- innerState = applyPatches(initialState, patches);
1220
- // Get previous state before action
1221
- prevState = this.currentState;
1222
- // Update state with inner brain results
1223
- _ = this;
1224
- return [
1225
- 4,
1226
- _await_async_generator(block.action(this.currentState, innerState, this.services))
1227
- ];
1228
- case 14:
1229
- _.currentState = _state.sent();
1230
- return [
1231
- 5,
1232
- _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState))))
1233
- ];
1234
- case 15:
1235
- _state.sent();
1236
- return [
1237
- 3,
1238
- 30
1239
- ];
1240
- case 16:
1241
- if (!(block.type === 'loop')) return [
1242
- 3,
1243
- 18
1244
- ];
1245
- return [
1246
- 5,
1247
- _ts_values(_async_generator_delegate(_async_iterator(this.executeLoop(step))))
1248
- ];
1249
- case 17:
1250
- _state.sent();
1251
- return [
1252
- 3,
1253
- 30
1254
- ];
1255
- case 18:
1256
- // Get previous state before action
1257
- prevState1 = this.currentState;
1258
- stepBlock = block;
1259
- // Execute step with automatic retry on failure
1260
- retries = 0;
1261
- _state.label = 19;
1262
- case 19:
1263
- if (!true) return [
1264
- 3,
1265
- 27
1266
- ];
1267
- _state.label = 20;
1268
- case 20:
1269
- _state.trys.push([
1270
- 20,
1271
- 22,
1272
- ,
1273
- 26
1274
- ]);
1275
- actionPromise = Promise.resolve(stepBlock.action(_object_spread({
1276
- state: this.currentState,
1277
- options: (_this_options2 = this.options) !== null && _this_options2 !== void 0 ? _this_options2 : {},
1278
- client: this.client,
1279
- resources: this.resources,
1280
- response: this.currentResponse,
1281
- pages: this.pages,
1282
- env: this.env
1283
- }, this.services)));
1284
- return [
1285
- 5,
1286
- _ts_values(_async_generator_delegate(_async_iterator(this.withHeartbeat(actionPromise, step))))
1287
- ];
1288
- case 21:
1289
- // Use withHeartbeat to emit heartbeat events during long-running operations
1290
- result = _state.sent();
1291
- return [
1292
- 3,
1293
- 27
1294
- ]; // Success
1295
- case 22:
1296
- error = _state.sent();
1297
- if (!(retries < MAX_RETRIES)) return [
1298
- 3,
1299
- 24
1300
- ];
1301
- retries++;
1302
- return [
1303
- 4,
1304
- {
1305
- type: BRAIN_EVENTS.STEP_RETRY,
1306
- stepTitle: step.block.title,
1307
- stepId: step.id,
1308
- error: {
1309
- name: error.name,
1310
- message: error.message,
1311
- stack: error.stack
1312
- },
1313
- attempt: retries,
1314
- options: (_this_options3 = this.options) !== null && _this_options3 !== void 0 ? _this_options3 : {},
1315
- brainRunId: this.brainRunId
1316
- }
1317
- ];
1318
- case 23:
1319
- _state.sent();
1320
- return [
1321
- 3,
1322
- 25
1323
- ];
1324
- case 24:
1325
- throw error;
1326
- case 25:
1327
- return [
1328
- 3,
1329
- 26
1330
- ];
1331
- case 26:
1332
- return [
1333
- 3,
1334
- 19
1335
- ];
1336
- case 27:
1337
- this.currentState = result && (typeof result === "undefined" ? "undefined" : _type_of(result)) === 'object' && 'waitFor' in result ? result.state : result;
1338
- return [
1339
- 5,
1340
- _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState1))))
1341
- ];
1342
- case 28:
1343
- _state.sent();
1344
- if (!(result && (typeof result === "undefined" ? "undefined" : _type_of(result)) === 'object' && 'waitFor' in result)) return [
1345
- 3,
1346
- 30
1347
- ];
1348
- // Serialize webhook registrations (remove Zod schemas for event serializability)
1349
- serializedWaitFor = result.waitFor.map(function(registration) {
1350
- return {
1351
- slug: registration.slug,
1352
- identifier: registration.identifier
1353
- };
1354
- });
1355
- return [
1356
- 4,
1357
- {
1358
- type: BRAIN_EVENTS.WEBHOOK,
1359
- waitFor: serializedWaitFor,
1360
- options: this.options,
1361
- brainRunId: this.brainRunId
1362
- }
1363
- ];
1364
- case 29:
1365
- _state.sent();
1366
- _state.label = 30;
1367
- case 30:
1368
- return [
1369
- 2
1370
- ];
1371
- }
1372
- });
1373
- }).call(this);
1374
- }
1375
- },
1376
- {
1377
- key: "executeLoop",
1378
- value: function executeLoop(step) {
1379
- return _wrap_async_generator(function() {
1380
- var block, prevState, _this_options, config, 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;
1381
- return _ts_generator(this, function(_state) {
1382
- switch(_state.label){
1383
- case 0:
1384
- block = step.block;
1385
- prevState = this.currentState;
1386
- return [
1387
- 4,
1388
- _await_async_generator(block.configFn(_object_spread({
1389
- state: this.currentState,
1390
- options: (_this_options = this.options) !== null && _this_options !== void 0 ? _this_options : {},
1391
- client: this.client,
1392
- resources: this.resources,
1393
- response: this.currentResponse,
1394
- pages: this.pages,
1395
- env: this.env
1396
- }, this.services)))
1397
- ];
1398
- case 1:
1399
- config = _state.sent();
1400
- if (!this.loopResumeContext) return [
1401
- 3,
1402
- 4
1403
- ];
1404
- resumeContext = this.loopResumeContext;
1405
- // Emit WEBHOOK_RESPONSE event to record the response
1406
- return [
1407
- 4,
1408
- {
1409
- type: BRAIN_EVENTS.WEBHOOK_RESPONSE,
1410
- response: resumeContext.webhookResponse,
1411
- options: (_this_options1 = this.options) !== null && _this_options1 !== void 0 ? _this_options1 : {},
1412
- brainRunId: this.brainRunId
1413
- }
1414
- ];
1415
- case 2:
1416
- _state.sent();
1417
- // Emit LOOP_TOOL_RESULT for the pending tool (webhook response injected as tool result)
1418
- return [
1419
- 4,
1420
- {
1421
- type: BRAIN_EVENTS.LOOP_TOOL_RESULT,
1422
- stepTitle: step.block.title,
1423
- stepId: step.id,
1424
- toolCallId: resumeContext.pendingToolCallId,
1425
- toolName: resumeContext.pendingToolName,
1426
- result: resumeContext.webhookResponse,
1427
- options: (_this_options2 = this.options) !== null && _this_options2 !== void 0 ? _this_options2 : {},
1428
- brainRunId: this.brainRunId
1429
- }
1430
- ];
1431
- case 3:
1432
- _state.sent();
1433
- // Use restored messages from the resume context
1434
- messages = resumeContext.messages;
1435
- // Clear the context so it's only used once
1436
- this.loopResumeContext = undefined;
1437
- return [
1438
- 3,
1439
- 6
1440
- ];
1441
- case 4:
1442
- // Emit loop start event (only for fresh starts)
1443
- return [
1444
- 4,
1445
- {
1446
- type: BRAIN_EVENTS.LOOP_START,
1447
- stepTitle: step.block.title,
1448
- stepId: step.id,
1449
- prompt: config.prompt,
1450
- system: config.system,
1451
- options: (_this_options3 = this.options) !== null && _this_options3 !== void 0 ? _this_options3 : {},
1452
- brainRunId: this.brainRunId
1453
- }
1454
- ];
1455
- case 5:
1456
- _state.sent();
1457
- // Initialize messages for fresh start
1458
- messages = [
1459
- {
1460
- role: 'user',
1461
- content: config.prompt
1462
- }
1463
- ];
1464
- _state.label = 6;
1465
- case 6:
1466
- // Initialize token tracking
1467
- totalTokens = 0;
1468
- iteration = 0;
1469
- _state.label = 7;
1470
- case 7:
1471
- if (!true) return [
1472
- 3,
1473
- 33
1474
- ];
1475
- iteration++;
1476
- // Emit iteration event
1477
- return [
1478
- 4,
1479
- {
1480
- type: BRAIN_EVENTS.LOOP_ITERATION,
1481
- stepTitle: step.block.title,
1482
- stepId: step.id,
1483
- iteration: iteration,
1484
- options: (_this_options4 = this.options) !== null && _this_options4 !== void 0 ? _this_options4 : {},
1485
- brainRunId: this.brainRunId
1486
- }
1487
- ];
1488
- case 8:
1489
- _state.sent();
1490
- // Check if client supports generateText
1491
- if (!this.client.generateText) {
1492
- throw new Error('Client does not support generateText. Use a client that implements generateText for loop steps.');
1493
- }
1494
- // Build tools object for the client (description and inputSchema only)
1495
- toolsForClient = {};
1496
- _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1497
- try {
1498
- for(_iterator = Object.entries(config.tools)[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1499
- _step_value = _sliced_to_array(_step.value, 2), name = _step_value[0], toolDef = _step_value[1];
1500
- tool = toolDef;
1501
- toolsForClient[name] = {
1502
- description: tool.description,
1503
- inputSchema: tool.inputSchema
1504
- };
1505
- }
1506
- } catch (err) {
1507
- _didIteratorError = true;
1508
- _iteratorError = err;
1509
- } finally{
1510
- try {
1511
- if (!_iteratorNormalCompletion && _iterator.return != null) {
1512
- _iterator.return();
1513
- }
1514
- } finally{
1515
- if (_didIteratorError) {
1516
- throw _iteratorError;
1517
- }
1518
- }
1519
- }
1520
- // Prepend default system prompt to user's system prompt
1521
- systemPrompt = config.system ? "".concat(DEFAULT_LOOP_SYSTEM_PROMPT, "\n\n").concat(config.system) : DEFAULT_LOOP_SYSTEM_PROMPT;
1522
- return [
1523
- 5,
1524
- _ts_values(_async_generator_delegate(_async_iterator(this.withHeartbeat(this.client.generateText({
1525
- system: systemPrompt,
1526
- messages: messages,
1527
- tools: toolsForClient
1528
- }), step))))
1529
- ];
1530
- case 9:
1531
- response = _state.sent();
1532
- // Track tokens
1533
- totalTokens += response.usage.totalTokens;
1534
- if (!(config.maxTokens && totalTokens > config.maxTokens)) return [
1535
- 3,
1536
- 12
1537
- ];
1538
- return [
1539
- 4,
1540
- {
1541
- type: BRAIN_EVENTS.LOOP_TOKEN_LIMIT,
1542
- stepTitle: step.block.title,
1543
- stepId: step.id,
1544
- totalTokens: totalTokens,
1545
- maxTokens: config.maxTokens,
1546
- options: (_this_options5 = this.options) !== null && _this_options5 !== void 0 ? _this_options5 : {},
1547
- brainRunId: this.brainRunId
1548
- }
1549
- ];
1550
- case 10:
1551
- _state.sent();
1552
- return [
1553
- 5,
1554
- _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState))))
1555
- ];
1556
- case 11:
1557
- _state.sent();
1558
- return [
1559
- 2
1560
- ];
1561
- case 12:
1562
- if (!response.text) return [
1563
- 3,
1564
- 14
1565
- ];
1566
- return [
1567
- 4,
1568
- {
1569
- type: BRAIN_EVENTS.LOOP_ASSISTANT_MESSAGE,
1570
- stepTitle: step.block.title,
1571
- stepId: step.id,
1572
- content: response.text,
1573
- options: (_this_options6 = this.options) !== null && _this_options6 !== void 0 ? _this_options6 : {},
1574
- brainRunId: this.brainRunId
1575
- }
1576
- ];
1577
- case 13:
1578
- _state.sent();
1579
- messages.push({
1580
- role: 'assistant',
1581
- content: response.text
1582
- });
1583
- _state.label = 14;
1584
- case 14:
1585
- if (!(!response.toolCalls || response.toolCalls.length === 0)) return [
1586
- 3,
1587
- 16
1588
- ];
1589
- return [
1590
- 5,
1591
- _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState))))
1592
- ];
1593
- case 15:
1594
- _state.sent();
1595
- return [
1596
- 2
1597
- ];
1598
- case 16:
1599
- _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
1600
- _state.label = 17;
1601
- case 17:
1602
- _state.trys.push([
1603
- 17,
1604
- 30,
1605
- 31,
1606
- 32
1607
- ]);
1608
- _iterator1 = response.toolCalls[Symbol.iterator]();
1609
- _state.label = 18;
1610
- case 18:
1611
- if (!!(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done)) return [
1612
- 3,
1613
- 29
1614
- ];
1615
- toolCall = _step1.value;
1616
- return [
1617
- 4,
1618
- {
1619
- type: BRAIN_EVENTS.LOOP_TOOL_CALL,
1620
- stepTitle: step.block.title,
1621
- stepId: step.id,
1622
- toolName: toolCall.toolName,
1623
- toolCallId: toolCall.toolCallId,
1624
- input: toolCall.args,
1625
- options: (_this_options7 = this.options) !== null && _this_options7 !== void 0 ? _this_options7 : {},
1626
- brainRunId: this.brainRunId
1627
- }
1628
- ];
1629
- case 19:
1630
- _state.sent();
1631
- tool1 = config.tools[toolCall.toolName];
1632
- if (!tool1) {
1633
- throw new Error("Unknown tool: ".concat(toolCall.toolName));
1634
- }
1635
- if (!tool1.terminal) return [
1636
- 3,
1637
- 22
1638
- ];
1639
- return [
1640
- 4,
1641
- {
1642
- type: BRAIN_EVENTS.LOOP_COMPLETE,
1643
- stepTitle: step.block.title,
1644
- stepId: step.id,
1645
- terminalToolName: toolCall.toolName,
1646
- result: toolCall.args,
1647
- totalIterations: iteration,
1648
- options: (_this_options8 = this.options) !== null && _this_options8 !== void 0 ? _this_options8 : {},
1649
- brainRunId: this.brainRunId
1650
- }
1651
- ];
1652
- case 20:
1653
- _state.sent();
1654
- // Merge terminal result into state
1655
- this.currentState = _object_spread({}, this.currentState, toolCall.args);
1656
- return [
1657
- 5,
1658
- _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState))))
1659
- ];
1660
- case 21:
1661
- _state.sent();
1662
- return [
1663
- 2
1664
- ];
1665
- case 22:
1666
- if (!tool1.execute) return [
1667
- 3,
1668
- 28
1669
- ];
1670
- return [
1671
- 5,
1672
- _ts_values(_async_generator_delegate(_async_iterator(this.withHeartbeat(Promise.resolve(tool1.execute(toolCall.args)), step))))
1673
- ];
1674
- case 23:
1675
- toolResult = _state.sent();
1676
- if (!(toolResult && (typeof toolResult === "undefined" ? "undefined" : _type_of(toolResult)) === 'object' && 'waitFor' in toolResult)) return [
1677
- 3,
1678
- 26
1679
- ];
1680
- waitForResult = toolResult;
1681
- // Normalize waitFor to array (supports single or multiple webhooks)
1682
- webhooks = Array.isArray(waitForResult.waitFor) ? waitForResult.waitFor : [
1683
- waitForResult.waitFor
1684
- ];
1685
- // Emit loop webhook event first (captures pending tool context)
1686
- return [
1687
- 4,
1688
- {
1689
- type: BRAIN_EVENTS.LOOP_WEBHOOK,
1690
- stepTitle: step.block.title,
1691
- stepId: step.id,
1692
- toolCallId: toolCall.toolCallId,
1693
- toolName: toolCall.toolName,
1694
- input: toolCall.args,
1695
- options: (_this_options9 = this.options) !== null && _this_options9 !== void 0 ? _this_options9 : {},
1696
- brainRunId: this.brainRunId
1697
- }
1698
- ];
1699
- case 24:
1700
- _state.sent();
1701
- // Then emit webhook event with all webhooks (first response wins)
1702
- return [
1703
- 4,
1704
- {
1705
- type: BRAIN_EVENTS.WEBHOOK,
1706
- waitFor: webhooks.map(function(w) {
1707
- return {
1708
- slug: w.slug,
1709
- identifier: w.identifier
1710
- };
1711
- }),
1712
- options: (_this_options10 = this.options) !== null && _this_options10 !== void 0 ? _this_options10 : {},
1713
- brainRunId: this.brainRunId
1714
- }
1715
- ];
1716
- case 25:
1717
- _state.sent();
1718
- return [
1719
- 2
1720
- ];
1721
- case 26:
1722
- // Normal tool result
1723
- return [
1724
- 4,
1725
- {
1726
- type: BRAIN_EVENTS.LOOP_TOOL_RESULT,
1727
- stepTitle: step.block.title,
1728
- stepId: step.id,
1729
- toolName: toolCall.toolName,
1730
- toolCallId: toolCall.toolCallId,
1731
- result: toolResult,
1732
- options: (_this_options11 = this.options) !== null && _this_options11 !== void 0 ? _this_options11 : {},
1733
- brainRunId: this.brainRunId
1734
- }
1735
- ];
1736
- case 27:
1737
- _state.sent();
1738
- messages.push({
1739
- role: 'tool',
1740
- content: JSON.stringify(toolResult),
1741
- toolCallId: toolCall.toolCallId,
1742
- toolName: toolCall.toolName
1743
- });
1744
- _state.label = 28;
1745
- case 28:
1746
- _iteratorNormalCompletion1 = true;
1747
- return [
1748
- 3,
1749
- 18
1750
- ];
1751
- case 29:
1752
- return [
1753
- 3,
1754
- 32
1755
- ];
1756
- case 30:
1757
- err = _state.sent();
1758
- _didIteratorError1 = true;
1759
- _iteratorError1 = err;
1760
- return [
1761
- 3,
1762
- 32
1763
- ];
1764
- case 31:
1765
- try {
1766
- if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
1767
- _iterator1.return();
1768
- }
1769
- } finally{
1770
- if (_didIteratorError1) {
1771
- throw _iteratorError1;
1772
- }
1773
- }
1774
- return [
1775
- 7
1776
- ];
1777
- case 32:
1778
- return [
1779
- 3,
1780
- 7
1781
- ];
1782
- case 33:
1783
- return [
1784
- 2
1785
- ];
1786
- }
1787
- });
1788
- }).call(this);
1789
- }
1790
- },
1791
- {
1792
- key: "completeStep",
1793
- value: function completeStep(step, prevState) {
1794
- var patch, _this_options;
1795
- return _ts_generator(this, function(_state) {
1796
- switch(_state.label){
1797
- case 0:
1798
- step.withStatus(STATUS.COMPLETE);
1799
- // Create patch for the state change
1800
- patch = createPatch(prevState, this.currentState);
1801
- step.withPatch(patch);
1802
- return [
1803
- 4,
1804
- {
1805
- type: BRAIN_EVENTS.STEP_COMPLETE,
1806
- status: STATUS.RUNNING,
1807
- stepTitle: step.block.title,
1808
- stepId: step.id,
1809
- patch: patch,
1810
- options: (_this_options = this.options) !== null && _this_options !== void 0 ? _this_options : {},
1811
- brainRunId: this.brainRunId
1812
- }
1813
- ];
1814
- case 1:
1815
- _state.sent();
1816
- return [
1817
- 2
1818
- ];
1819
- }
1820
- });
1821
- }
1822
- },
1823
- {
1824
- key: "withHeartbeat",
1825
- value: /**
1826
- * Wraps a promise with heartbeat emission to keep Durable Objects alive during long-running operations.
1827
- * Emits HEARTBEAT events at regular intervals while waiting for the promise to resolve.
1828
- */ function withHeartbeat(promise, step) {
1829
- return _wrap_async_generator(function() {
1830
- var resolved, result, error, promiseHandler, _this_options;
1831
- return _ts_generator(this, function(_state) {
1832
- switch(_state.label){
1833
- case 0:
1834
- // Create a deferred to track completion
1835
- resolved = false;
1836
- promiseHandler = promise.then(function(r) {
1837
- resolved = true;
1838
- result = r;
1839
- }).catch(function(e) {
1840
- resolved = true;
1841
- error = e;
1842
- });
1843
- _state.label = 1;
1844
- case 1:
1845
- if (!!resolved) return [
1846
- 3,
1847
- 5
1848
- ];
1849
- // Race between the promise and the heartbeat interval
1850
- return [
1851
- 4,
1852
- _await_async_generator(Promise.race([
1853
- promiseHandler,
1854
- sleep(HEARTBEAT_INTERVAL_MS)
1855
- ]))
1856
- ];
1857
- case 2:
1858
- _state.sent();
1859
- if (!!resolved) return [
1860
- 3,
1861
- 4
1862
- ];
1863
- return [
1864
- 4,
1865
- {
1866
- type: BRAIN_EVENTS.HEARTBEAT,
1867
- stepId: step.id,
1868
- stepTitle: step.block.title,
1869
- options: (_this_options = this.options) !== null && _this_options !== void 0 ? _this_options : {},
1870
- brainRunId: this.brainRunId
1871
- }
1872
- ];
1873
- case 3:
1874
- _state.sent();
1875
- _state.label = 4;
1876
- case 4:
1877
- return [
1878
- 3,
1879
- 1
1880
- ];
1881
- case 5:
1882
- if (error) {
1883
- throw error;
1884
- }
1885
- return [
1886
- 2,
1887
- result
1888
- ];
1889
- }
1890
- });
1891
- }).call(this);
1892
- }
1893
- }
1894
- ]);
1895
- return BrainEventStream;
1896
- }();
1897
- var brainNamesAreUnique = process.env.NODE_ENV !== 'test';
1898
- var brainNames = new Set();
1899
- export var brain = function brain(brainConfig) {
1900
- var title = typeof brainConfig === 'string' ? brainConfig : brainConfig.title;
1901
- var description = typeof brainConfig === 'string' ? undefined : brainConfig.description;
1902
- if (brainNamesAreUnique && brainNames.has(title)) {
1903
- throw new Error('Brain with title "'.concat(title, '" already exists. Brain titles must be unique.'));
1904
- }
1905
- if (brainNamesAreUnique) {
1906
- brainNames.add(title);
1907
- }
1908
- return new Brain(title, description);
1909
- };
1910
- var clone = function(value) {
1911
- return structuredClone(value);
1912
- };
1
+ // Re-export from new modular structure for backwards compatibility
2
+ // Builder
3
+ export { Brain, brain } from './builder/brain.js';
4
+ // Execution - Constants
5
+ export { DEFAULT_ENV } from './execution/constants.js';