@positronic/core 0.0.1 → 0.0.3

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 (79) hide show
  1. package/CLAUDE.md +141 -0
  2. package/dist/src/adapters/types.js +1 -16
  3. package/dist/src/clients/types.js +4 -1
  4. package/dist/src/dsl/brain-runner.js +487 -0
  5. package/dist/src/dsl/brain-runner.test.js +733 -0
  6. package/dist/src/dsl/brain.js +1128 -0
  7. package/dist/src/dsl/brain.test.js +4225 -0
  8. package/dist/src/dsl/constants.js +6 -6
  9. package/dist/src/dsl/json-patch.js +37 -9
  10. package/dist/src/index.js +11 -10
  11. package/dist/src/resources/resources.js +371 -0
  12. package/dist/src/test-utils.js +474 -0
  13. package/dist/src/testing.js +3 -0
  14. package/dist/types/adapters/types.d.ts +3 -8
  15. package/dist/types/adapters/types.d.ts.map +1 -1
  16. package/dist/types/clients/types.d.ts +46 -6
  17. package/dist/types/clients/types.d.ts.map +1 -1
  18. package/dist/types/dsl/brain-runner.d.ts +24 -0
  19. package/dist/types/dsl/brain-runner.d.ts.map +1 -0
  20. package/dist/types/dsl/brain.d.ts +136 -0
  21. package/dist/types/dsl/brain.d.ts.map +1 -0
  22. package/dist/types/dsl/constants.d.ts +5 -5
  23. package/dist/types/dsl/constants.d.ts.map +1 -1
  24. package/dist/types/dsl/json-patch.d.ts +2 -1
  25. package/dist/types/dsl/json-patch.d.ts.map +1 -1
  26. package/dist/types/index.d.ts +13 -11
  27. package/dist/types/index.d.ts.map +1 -1
  28. package/dist/types/resources/resource-loader.d.ts +6 -0
  29. package/dist/types/resources/resource-loader.d.ts.map +1 -0
  30. package/dist/types/resources/resources.d.ts +23 -0
  31. package/dist/types/resources/resources.d.ts.map +1 -0
  32. package/dist/types/test-utils.d.ts +94 -0
  33. package/dist/types/test-utils.d.ts.map +1 -0
  34. package/dist/types/testing.d.ts +2 -0
  35. package/dist/types/testing.d.ts.map +1 -0
  36. package/docs/core-testing-guide.md +289 -0
  37. package/package.json +26 -7
  38. package/src/adapters/types.ts +3 -22
  39. package/src/clients/types.ts +50 -10
  40. package/src/dsl/brain-runner.test.ts +384 -0
  41. package/src/dsl/brain-runner.ts +111 -0
  42. package/src/dsl/brain.test.ts +1981 -0
  43. package/src/dsl/brain.ts +740 -0
  44. package/src/dsl/constants.ts +6 -6
  45. package/src/dsl/json-patch.ts +24 -9
  46. package/src/dsl/types.ts +1 -1
  47. package/src/index.ts +30 -16
  48. package/src/resources/resource-loader.ts +8 -0
  49. package/src/resources/resources.ts +267 -0
  50. package/src/test-utils.ts +254 -0
  51. package/test/resources.test.ts +248 -0
  52. package/tsconfig.json +2 -2
  53. package/.swcrc +0 -31
  54. package/dist/src/dsl/extensions.js +0 -19
  55. package/dist/src/dsl/workflow-runner.js +0 -93
  56. package/dist/src/dsl/workflow.js +0 -308
  57. package/dist/src/file-stores/local-file-store.js +0 -12
  58. package/dist/src/utils/temp-files.js +0 -27
  59. package/dist/types/dsl/extensions.d.ts +0 -18
  60. package/dist/types/dsl/extensions.d.ts.map +0 -1
  61. package/dist/types/dsl/workflow-runner.d.ts +0 -28
  62. package/dist/types/dsl/workflow-runner.d.ts.map +0 -1
  63. package/dist/types/dsl/workflow.d.ts +0 -118
  64. package/dist/types/dsl/workflow.d.ts.map +0 -1
  65. package/dist/types/file-stores/local-file-store.d.ts +0 -7
  66. package/dist/types/file-stores/local-file-store.d.ts.map +0 -1
  67. package/dist/types/file-stores/types.d.ts +0 -4
  68. package/dist/types/file-stores/types.d.ts.map +0 -1
  69. package/dist/types/utils/temp-files.d.ts +0 -12
  70. package/dist/types/utils/temp-files.d.ts.map +0 -1
  71. package/src/dsl/extensions.ts +0 -58
  72. package/src/dsl/workflow-runner.test.ts +0 -203
  73. package/src/dsl/workflow-runner.ts +0 -146
  74. package/src/dsl/workflow.test.ts +0 -1435
  75. package/src/dsl/workflow.ts +0 -554
  76. package/src/file-stores/local-file-store.ts +0 -11
  77. package/src/file-stores/types.ts +0 -3
  78. package/src/utils/temp-files.ts +0 -46
  79. /package/dist/src/{file-stores/types.js → resources/resource-loader.js} +0 -0
@@ -0,0 +1,1128 @@
1
+ function _async_generator(gen) {
2
+ var front, back;
3
+ function send(key, arg) {
4
+ return new Promise(function(resolve, reject) {
5
+ var request = {
6
+ key: key,
7
+ arg: arg,
8
+ resolve: resolve,
9
+ reject: reject,
10
+ next: null
11
+ };
12
+ if (back) back = back.next = request;
13
+ else {
14
+ front = back = request;
15
+ resume(key, arg);
16
+ }
17
+ });
18
+ }
19
+ function resume(key, arg) {
20
+ try {
21
+ var result = gen[key](arg);
22
+ var value = result.value;
23
+ var overloaded = value instanceof _overload_yield;
24
+ Promise.resolve(overloaded ? value.v : value).then(function(arg) {
25
+ if (overloaded) {
26
+ var nextKey = key === "return" ? "return" : "next";
27
+ if (!value.k || arg.done) return resume(nextKey, arg);
28
+ else arg = gen[nextKey](arg).value;
29
+ }
30
+ settle(result.done ? "return" : "normal", arg);
31
+ }, function(err) {
32
+ resume("throw", err);
33
+ });
34
+ } catch (err) {
35
+ settle("throw", err);
36
+ }
37
+ }
38
+ function settle(type, value) {
39
+ switch(type){
40
+ case "return":
41
+ front.resolve({
42
+ value: value,
43
+ done: true
44
+ });
45
+ break;
46
+ case "throw":
47
+ front.reject(value);
48
+ break;
49
+ default:
50
+ front.resolve({
51
+ value: value,
52
+ done: false
53
+ });
54
+ break;
55
+ }
56
+ front = front.next;
57
+ if (front) resume(front.key, front.arg);
58
+ else back = null;
59
+ }
60
+ this._invoke = send;
61
+ if (typeof gen.return !== "function") this.return = undefined;
62
+ }
63
+ _async_generator.prototype[typeof Symbol === "function" && Symbol.asyncIterator || "@@asyncIterator"] = function() {
64
+ return this;
65
+ };
66
+ _async_generator.prototype.next = function(arg) {
67
+ return this._invoke("next", arg);
68
+ };
69
+ _async_generator.prototype.throw = function(arg) {
70
+ return this._invoke("throw", arg);
71
+ };
72
+ _async_generator.prototype.return = function(arg) {
73
+ return this._invoke("return", arg);
74
+ };
75
+ function _async_generator_delegate(inner) {
76
+ var iter = {}, waiting = false;
77
+ function pump(key, value) {
78
+ waiting = true;
79
+ value = new Promise(function(resolve) {
80
+ resolve(inner[key](value));
81
+ });
82
+ return {
83
+ done: false,
84
+ value: new _overload_yield(value, 1)
85
+ };
86
+ }
87
+ iter[typeof Symbol !== "undefined" && Symbol.iterator || "@@iterator"] = function() {
88
+ return this;
89
+ };
90
+ iter.next = function(value) {
91
+ if (waiting) {
92
+ waiting = false;
93
+ return value;
94
+ }
95
+ return pump("next", value);
96
+ };
97
+ if (typeof inner.throw === "function") {
98
+ iter.throw = function(value) {
99
+ if (waiting) {
100
+ waiting = false;
101
+ throw value;
102
+ }
103
+ return pump("throw", value);
104
+ };
105
+ }
106
+ if (typeof inner.return === "function") {
107
+ iter.return = function(value) {
108
+ if (waiting) {
109
+ waiting = false;
110
+ return value;
111
+ }
112
+ return pump("return", value);
113
+ };
114
+ }
115
+ return iter;
116
+ }
117
+ function _async_iterator(iterable) {
118
+ var method, async, sync, retry = 2;
119
+ for("undefined" != typeof Symbol && (async = Symbol.asyncIterator, sync = Symbol.iterator); retry--;){
120
+ if (async && null != (method = iterable[async])) return method.call(iterable);
121
+ if (sync && null != (method = iterable[sync])) return new AsyncFromSyncIterator(method.call(iterable));
122
+ async = "@@asyncIterator", sync = "@@iterator";
123
+ }
124
+ throw new TypeError("Object is not async iterable");
125
+ }
126
+ function AsyncFromSyncIterator(s) {
127
+ function AsyncFromSyncIteratorContinuation(r) {
128
+ if (Object(r) !== r) return Promise.reject(new TypeError(r + " is not an object."));
129
+ var done = r.done;
130
+ return Promise.resolve(r.value).then(function(value) {
131
+ return {
132
+ value: value,
133
+ done: done
134
+ };
135
+ });
136
+ }
137
+ return AsyncFromSyncIterator = function(s) {
138
+ this.s = s, this.n = s.next;
139
+ }, AsyncFromSyncIterator.prototype = {
140
+ s: null,
141
+ n: null,
142
+ next: function() {
143
+ return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments));
144
+ },
145
+ return: function(value) {
146
+ var ret = this.s.return;
147
+ return void 0 === ret ? Promise.resolve({
148
+ value: value,
149
+ done: !0
150
+ }) : AsyncFromSyncIteratorContinuation(ret.apply(this.s, arguments));
151
+ },
152
+ throw: function(value) {
153
+ var thr = this.s.return;
154
+ return void 0 === thr ? Promise.reject(value) : AsyncFromSyncIteratorContinuation(thr.apply(this.s, arguments));
155
+ }
156
+ }, new AsyncFromSyncIterator(s);
157
+ }
158
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
159
+ try {
160
+ var info = gen[key](arg);
161
+ var value = info.value;
162
+ } catch (error) {
163
+ reject(error);
164
+ return;
165
+ }
166
+ if (info.done) {
167
+ resolve(value);
168
+ } else {
169
+ Promise.resolve(value).then(_next, _throw);
170
+ }
171
+ }
172
+ function _async_to_generator(fn) {
173
+ return function() {
174
+ var self = this, args = arguments;
175
+ return new Promise(function(resolve, reject) {
176
+ var gen = fn.apply(self, args);
177
+ function _next(value) {
178
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
179
+ }
180
+ function _throw(err) {
181
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
182
+ }
183
+ _next(undefined);
184
+ });
185
+ };
186
+ }
187
+ function _await_async_generator(value) {
188
+ return new _overload_yield(value, 0);
189
+ }
190
+ function _class_call_check(instance, Constructor) {
191
+ if (!(instance instanceof Constructor)) {
192
+ throw new TypeError("Cannot call a class as a function");
193
+ }
194
+ }
195
+ function _defineProperties(target, props) {
196
+ for(var i = 0; i < props.length; i++){
197
+ var descriptor = props[i];
198
+ descriptor.enumerable = descriptor.enumerable || false;
199
+ descriptor.configurable = true;
200
+ if ("value" in descriptor) descriptor.writable = true;
201
+ Object.defineProperty(target, descriptor.key, descriptor);
202
+ }
203
+ }
204
+ function _create_class(Constructor, protoProps, staticProps) {
205
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
206
+ if (staticProps) _defineProperties(Constructor, staticProps);
207
+ return Constructor;
208
+ }
209
+ function _define_property(obj, key, value) {
210
+ if (key in obj) {
211
+ Object.defineProperty(obj, key, {
212
+ value: value,
213
+ enumerable: true,
214
+ configurable: true,
215
+ writable: true
216
+ });
217
+ } else {
218
+ obj[key] = value;
219
+ }
220
+ return obj;
221
+ }
222
+ function _object_spread(target) {
223
+ for(var i = 1; i < arguments.length; i++){
224
+ var source = arguments[i] != null ? arguments[i] : {};
225
+ var ownKeys = Object.keys(source);
226
+ if (typeof Object.getOwnPropertySymbols === "function") {
227
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
228
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
229
+ }));
230
+ }
231
+ ownKeys.forEach(function(key) {
232
+ _define_property(target, key, source[key]);
233
+ });
234
+ }
235
+ return target;
236
+ }
237
+ function ownKeys(object, enumerableOnly) {
238
+ var keys = Object.keys(object);
239
+ if (Object.getOwnPropertySymbols) {
240
+ var symbols = Object.getOwnPropertySymbols(object);
241
+ if (enumerableOnly) {
242
+ symbols = symbols.filter(function(sym) {
243
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
244
+ });
245
+ }
246
+ keys.push.apply(keys, symbols);
247
+ }
248
+ return keys;
249
+ }
250
+ function _object_spread_props(target, source) {
251
+ source = source != null ? source : {};
252
+ if (Object.getOwnPropertyDescriptors) {
253
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
254
+ } else {
255
+ ownKeys(Object(source)).forEach(function(key) {
256
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
257
+ });
258
+ }
259
+ return target;
260
+ }
261
+ function _object_without_properties(source, excluded) {
262
+ if (source == null) return {};
263
+ var target = _object_without_properties_loose(source, excluded);
264
+ var key, i;
265
+ if (Object.getOwnPropertySymbols) {
266
+ var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
267
+ for(i = 0; i < sourceSymbolKeys.length; i++){
268
+ key = sourceSymbolKeys[i];
269
+ if (excluded.indexOf(key) >= 0) continue;
270
+ if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
271
+ target[key] = source[key];
272
+ }
273
+ }
274
+ return target;
275
+ }
276
+ function _object_without_properties_loose(source, excluded) {
277
+ if (source == null) return {};
278
+ var target = {};
279
+ var sourceKeys = Object.keys(source);
280
+ var key, i;
281
+ for(i = 0; i < sourceKeys.length; i++){
282
+ key = sourceKeys[i];
283
+ if (excluded.indexOf(key) >= 0) continue;
284
+ target[key] = source[key];
285
+ }
286
+ return target;
287
+ }
288
+ function _overload_yield(value, kind) {
289
+ this.v = value;
290
+ this.k = kind;
291
+ }
292
+ function _wrap_async_generator(fn) {
293
+ return function() {
294
+ return new _async_generator(fn.apply(this, arguments));
295
+ };
296
+ }
297
+ function _ts_generator(thisArg, body) {
298
+ var f, y, t, _ = {
299
+ label: 0,
300
+ sent: function() {
301
+ if (t[0] & 1) throw t[1];
302
+ return t[1];
303
+ },
304
+ trys: [],
305
+ ops: []
306
+ }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
307
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
308
+ return this;
309
+ }), g;
310
+ function verb(n) {
311
+ return function(v) {
312
+ return step([
313
+ n,
314
+ v
315
+ ]);
316
+ };
317
+ }
318
+ function step(op) {
319
+ if (f) throw new TypeError("Generator is already executing.");
320
+ while(g && (g = 0, op[0] && (_ = 0)), _)try {
321
+ 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;
322
+ if (y = 0, t) op = [
323
+ op[0] & 2,
324
+ t.value
325
+ ];
326
+ switch(op[0]){
327
+ case 0:
328
+ case 1:
329
+ t = op;
330
+ break;
331
+ case 4:
332
+ _.label++;
333
+ return {
334
+ value: op[1],
335
+ done: false
336
+ };
337
+ case 5:
338
+ _.label++;
339
+ y = op[1];
340
+ op = [
341
+ 0
342
+ ];
343
+ continue;
344
+ case 7:
345
+ op = _.ops.pop();
346
+ _.trys.pop();
347
+ continue;
348
+ default:
349
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
350
+ _ = 0;
351
+ continue;
352
+ }
353
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
354
+ _.label = op[1];
355
+ break;
356
+ }
357
+ if (op[0] === 6 && _.label < t[1]) {
358
+ _.label = t[1];
359
+ t = op;
360
+ break;
361
+ }
362
+ if (t && _.label < t[2]) {
363
+ _.label = t[2];
364
+ _.ops.push(op);
365
+ break;
366
+ }
367
+ if (t[2]) _.ops.pop();
368
+ _.trys.pop();
369
+ continue;
370
+ }
371
+ op = body.call(thisArg, _);
372
+ } catch (e) {
373
+ op = [
374
+ 6,
375
+ e
376
+ ];
377
+ y = 0;
378
+ } finally{
379
+ f = t = 0;
380
+ }
381
+ if (op[0] & 5) throw op[1];
382
+ return {
383
+ value: op[0] ? op[1] : void 0,
384
+ done: true
385
+ };
386
+ }
387
+ }
388
+ function _ts_values(o) {
389
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
390
+ if (m) return m.call(o);
391
+ if (o && typeof o.length === "number") return {
392
+ next: function() {
393
+ if (o && i >= o.length) o = void 0;
394
+ return {
395
+ value: o && o[i++],
396
+ done: !o
397
+ };
398
+ }
399
+ };
400
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
401
+ }
402
+ import { v4 as uuidv4 } from 'uuid';
403
+ import { STATUS, BRAIN_EVENTS } from './constants.js';
404
+ import { createPatch, applyPatches } from './json-patch.js';
405
+ export var Brain = /*#__PURE__*/ function() {
406
+ "use strict";
407
+ function Brain(title, description) {
408
+ _class_call_check(this, Brain);
409
+ _define_property(this, "title", void 0);
410
+ _define_property(this, "description", void 0);
411
+ _define_property(this, "blocks", void 0);
412
+ _define_property(this, "type", void 0);
413
+ _define_property(this, "defaultOptions", void 0);
414
+ _define_property(this, "services", void 0);
415
+ this.title = title;
416
+ this.description = description;
417
+ this.blocks = [];
418
+ this.type = 'brain';
419
+ this.defaultOptions = {};
420
+ this.services = {};
421
+ }
422
+ _create_class(Brain, [
423
+ {
424
+ key: "structure",
425
+ get: function get() {
426
+ return {
427
+ title: this.title,
428
+ description: this.description,
429
+ steps: this.blocks.map(function(block) {
430
+ if (block.type === 'step') {
431
+ return {
432
+ type: 'step',
433
+ title: block.title
434
+ };
435
+ } else {
436
+ // block.type === 'brain'
437
+ return {
438
+ type: 'brain',
439
+ title: block.title,
440
+ innerBrain: block.innerBrain.structure
441
+ };
442
+ }
443
+ })
444
+ };
445
+ }
446
+ },
447
+ {
448
+ // New method to specify default options
449
+ key: "withOptions",
450
+ value: function withOptions(options) {
451
+ this.defaultOptions = _object_spread({}, this.defaultOptions, options);
452
+ return this;
453
+ }
454
+ },
455
+ {
456
+ // New method to add services
457
+ key: "withServices",
458
+ value: function withServices(services) {
459
+ var nextBrain = new Brain(this.title, this.description).withBlocks(this.blocks);
460
+ // Copy default options
461
+ nextBrain.withOptions(this.defaultOptions);
462
+ // Set services
463
+ nextBrain.services = services;
464
+ return nextBrain;
465
+ }
466
+ },
467
+ {
468
+ key: "step",
469
+ value: function step(title, action) {
470
+ var stepBlock = {
471
+ type: 'step',
472
+ title: title,
473
+ action: action
474
+ };
475
+ this.blocks.push(stepBlock);
476
+ return this.nextBrain();
477
+ }
478
+ },
479
+ {
480
+ key: "brain",
481
+ value: function brain(title, innerBrain, action, initialState) {
482
+ var nestedBlock = {
483
+ type: 'brain',
484
+ title: title,
485
+ innerBrain: innerBrain,
486
+ initialState: initialState || function() {
487
+ return {};
488
+ },
489
+ action: function(outerState, innerState, services) {
490
+ return action({
491
+ state: outerState,
492
+ brainState: innerState,
493
+ services: services
494
+ });
495
+ }
496
+ };
497
+ this.blocks.push(nestedBlock);
498
+ return this.nextBrain();
499
+ }
500
+ },
501
+ {
502
+ // TResponseKey:
503
+ // The response key must be a string literal, so if defining a response model
504
+ // a consumer of this brain must use "as const" to ensure the key is a string literal
505
+ // this type makes sure that the will get a ts error if they don't.
506
+ key: "prompt",
507
+ value: function prompt(title, config, reduce) {
508
+ var promptBlock = {
509
+ type: 'step',
510
+ title: title,
511
+ action: function(_param) {
512
+ return _async_to_generator(function() {
513
+ var state, runClient, options, resources, services, template, outputSchema, stepClient, schema, schemaName, client, prompt, response, stateWithResponse;
514
+ return _ts_generator(this, function(_state) {
515
+ switch(_state.label){
516
+ case 0:
517
+ state = _param.state, runClient = _param.client, options = _param.options, resources = _param.resources, services = _object_without_properties(_param, [
518
+ "state",
519
+ "client",
520
+ "options",
521
+ "resources"
522
+ ]);
523
+ template = config.template, outputSchema = config.outputSchema, stepClient = config.client;
524
+ schema = outputSchema.schema, schemaName = outputSchema.name;
525
+ client = stepClient !== null && stepClient !== void 0 ? stepClient : runClient;
526
+ return [
527
+ 4,
528
+ template(state, resources)
529
+ ];
530
+ case 1:
531
+ prompt = _state.sent();
532
+ return [
533
+ 4,
534
+ client.generateObject({
535
+ schema: schema,
536
+ schemaName: schemaName,
537
+ prompt: prompt
538
+ })
539
+ ];
540
+ case 2:
541
+ response = _state.sent();
542
+ stateWithResponse = _object_spread_props(_object_spread({}, state), _define_property({}, config.outputSchema.name, response));
543
+ return [
544
+ 2,
545
+ reduce ? reduce(_object_spread({
546
+ state: state,
547
+ response: response,
548
+ options: options,
549
+ prompt: prompt,
550
+ resources: resources
551
+ }, services)) : stateWithResponse
552
+ ];
553
+ }
554
+ });
555
+ })();
556
+ }
557
+ };
558
+ this.blocks.push(promptBlock);
559
+ return this.nextBrain();
560
+ }
561
+ },
562
+ {
563
+ key: "run",
564
+ value: // Implementation signature
565
+ function run(params) {
566
+ return _wrap_async_generator(function() {
567
+ var _this, title, description, blocks, mergedOptions, stream;
568
+ return _ts_generator(this, function(_state) {
569
+ switch(_state.label){
570
+ case 0:
571
+ _this = this, title = _this.title, description = _this.description, blocks = _this.blocks;
572
+ // Merge default options with provided options
573
+ mergedOptions = _object_spread({}, this.defaultOptions, params.options || {});
574
+ stream = new BrainEventStream(_object_spread_props(_object_spread({
575
+ title: title,
576
+ description: description,
577
+ blocks: blocks
578
+ }, params), {
579
+ options: mergedOptions,
580
+ services: this.services
581
+ }));
582
+ return [
583
+ 5,
584
+ _ts_values(_async_generator_delegate(_async_iterator(stream.next())))
585
+ ];
586
+ case 1:
587
+ _state.sent();
588
+ return [
589
+ 2
590
+ ];
591
+ }
592
+ });
593
+ }).call(this);
594
+ }
595
+ },
596
+ {
597
+ key: "withBlocks",
598
+ value: function withBlocks(blocks) {
599
+ this.blocks = blocks;
600
+ return this;
601
+ }
602
+ },
603
+ {
604
+ key: "nextBrain",
605
+ value: function nextBrain() {
606
+ // Pass default options to the next brain
607
+ var nextBrain = new Brain(this.title, this.description).withBlocks(this.blocks);
608
+ // Copy default options to the next brain
609
+ nextBrain.withOptions(this.defaultOptions);
610
+ // Copy services to the next brain
611
+ nextBrain.services = this.services;
612
+ return nextBrain;
613
+ }
614
+ }
615
+ ]);
616
+ return Brain;
617
+ }();
618
+ var Step = /*#__PURE__*/ function() {
619
+ "use strict";
620
+ function Step(block, id) {
621
+ _class_call_check(this, Step);
622
+ _define_property(this, "block", void 0);
623
+ _define_property(this, "id", void 0);
624
+ _define_property(this, "patch", void 0);
625
+ _define_property(this, "status", void 0);
626
+ this.block = block;
627
+ this.status = STATUS.PENDING;
628
+ this.id = id || uuidv4();
629
+ }
630
+ _create_class(Step, [
631
+ {
632
+ key: "withPatch",
633
+ value: function withPatch(patch) {
634
+ this.patch = patch;
635
+ return this;
636
+ }
637
+ },
638
+ {
639
+ key: "withStatus",
640
+ value: function withStatus(status) {
641
+ this.status = status;
642
+ return this;
643
+ }
644
+ },
645
+ {
646
+ key: "serialized",
647
+ get: function get() {
648
+ return {
649
+ id: this.id,
650
+ title: this.block.title,
651
+ status: this.status,
652
+ patch: typeof this.patch === 'string' ? JSON.parse(this.patch) : this.patch
653
+ };
654
+ }
655
+ }
656
+ ]);
657
+ return Step;
658
+ }();
659
+ var BrainEventStream = /*#__PURE__*/ function() {
660
+ "use strict";
661
+ function BrainEventStream(params) {
662
+ _class_call_check(this, BrainEventStream);
663
+ _define_property(this, "currentState", void 0);
664
+ _define_property(this, "steps", void 0);
665
+ _define_property(this, "currentStepIndex", 0);
666
+ _define_property(this, "initialState", void 0);
667
+ _define_property(this, "brainRunId", void 0);
668
+ _define_property(this, "title", void 0);
669
+ _define_property(this, "description", void 0);
670
+ _define_property(this, "client", void 0);
671
+ _define_property(this, "options", void 0);
672
+ _define_property(this, "services", void 0);
673
+ _define_property(this, "resources", void 0);
674
+ 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;
675
+ this.initialState = initialState;
676
+ this.title = title;
677
+ this.description = description;
678
+ this.client = client;
679
+ this.options = options;
680
+ this.services = services;
681
+ this.resources = resources;
682
+ // Initialize steps array with UUIDs and pending status
683
+ this.steps = blocks.map(function(block, index) {
684
+ var completedStep = initialCompletedSteps === null || initialCompletedSteps === void 0 ? void 0 : initialCompletedSteps[index];
685
+ if (completedStep) {
686
+ return new Step(block, completedStep.id).withStatus(completedStep.status).withPatch(completedStep.patch);
687
+ }
688
+ return new Step(block);
689
+ });
690
+ this.currentState = clone(this.initialState);
691
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
692
+ try {
693
+ for(var _iterator = this.steps[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
694
+ var step = _step.value;
695
+ if (step.serialized.status === STATUS.COMPLETE && step.serialized.patch) {
696
+ this.currentState = applyPatches(this.currentState, [
697
+ step.serialized.patch
698
+ ]);
699
+ }
700
+ }
701
+ } catch (err) {
702
+ _didIteratorError = true;
703
+ _iteratorError = err;
704
+ } finally{
705
+ try {
706
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
707
+ _iterator.return();
708
+ }
709
+ } finally{
710
+ if (_didIteratorError) {
711
+ throw _iteratorError;
712
+ }
713
+ }
714
+ }
715
+ // Use provided ID if available, otherwise generate one
716
+ this.brainRunId = providedBrainRunId !== null && providedBrainRunId !== void 0 ? providedBrainRunId : uuidv4();
717
+ }
718
+ _create_class(BrainEventStream, [
719
+ {
720
+ key: "next",
721
+ value: function next() {
722
+ return _wrap_async_generator(function() {
723
+ var _this, steps, brainTitle, brainDescription, currentState, options, brainRunId, hasCompletedSteps, step, err, error, currentStep;
724
+ return _ts_generator(this, function(_state) {
725
+ switch(_state.label){
726
+ case 0:
727
+ _this = this, steps = _this.steps, brainTitle = _this.title, brainDescription = _this.description, currentState = _this.currentState, options = _this.options, brainRunId = _this.brainRunId;
728
+ _state.label = 1;
729
+ case 1:
730
+ _state.trys.push([
731
+ 1,
732
+ 11,
733
+ ,
734
+ 14
735
+ ]);
736
+ hasCompletedSteps = steps.some(function(step) {
737
+ return step.serialized.status !== STATUS.PENDING;
738
+ });
739
+ return [
740
+ 4,
741
+ {
742
+ type: hasCompletedSteps ? BRAIN_EVENTS.RESTART : BRAIN_EVENTS.START,
743
+ status: STATUS.RUNNING,
744
+ brainTitle: brainTitle,
745
+ brainDescription: brainDescription,
746
+ initialState: currentState,
747
+ options: options,
748
+ brainRunId: brainRunId
749
+ }
750
+ ];
751
+ case 2:
752
+ _state.sent();
753
+ // Emit initial step status after brain starts
754
+ return [
755
+ 4,
756
+ {
757
+ type: BRAIN_EVENTS.STEP_STATUS,
758
+ steps: steps.map(function(step) {
759
+ var _step_serialized = step.serialized, patch = _step_serialized.patch, rest = _object_without_properties(_step_serialized, [
760
+ "patch"
761
+ ]);
762
+ return rest;
763
+ }),
764
+ options: options,
765
+ brainRunId: brainRunId
766
+ }
767
+ ];
768
+ case 3:
769
+ _state.sent();
770
+ _state.label = 4;
771
+ case 4:
772
+ if (!(this.currentStepIndex < steps.length)) return [
773
+ 3,
774
+ 9
775
+ ];
776
+ step = steps[this.currentStepIndex];
777
+ // Skip completed steps
778
+ if (step.serialized.status === STATUS.COMPLETE) {
779
+ this.currentStepIndex++;
780
+ return [
781
+ 3,
782
+ 4
783
+ ];
784
+ }
785
+ // Step start event
786
+ return [
787
+ 4,
788
+ {
789
+ type: BRAIN_EVENTS.STEP_START,
790
+ status: STATUS.RUNNING,
791
+ stepTitle: step.block.title,
792
+ stepId: step.id,
793
+ options: options,
794
+ brainRunId: brainRunId
795
+ }
796
+ ];
797
+ case 5:
798
+ _state.sent();
799
+ step.withStatus(STATUS.RUNNING);
800
+ // Step Status Event to indicate that the step is running
801
+ return [
802
+ 4,
803
+ {
804
+ type: BRAIN_EVENTS.STEP_STATUS,
805
+ steps: steps.map(function(step) {
806
+ var _step_serialized = step.serialized, patch = _step_serialized.patch, rest = _object_without_properties(_step_serialized, [
807
+ "patch"
808
+ ]);
809
+ return rest;
810
+ }),
811
+ options: options,
812
+ brainRunId: brainRunId
813
+ }
814
+ ];
815
+ case 6:
816
+ _state.sent();
817
+ // Execute step and yield the STEP_COMPLETE event and
818
+ // all events from inner brains if any
819
+ return [
820
+ 5,
821
+ _ts_values(_async_generator_delegate(_async_iterator(this.executeStep(step))))
822
+ ];
823
+ case 7:
824
+ _state.sent();
825
+ // Step Status Event
826
+ return [
827
+ 4,
828
+ {
829
+ type: BRAIN_EVENTS.STEP_STATUS,
830
+ steps: steps.map(function(step) {
831
+ var _step_serialized = step.serialized, patch = _step_serialized.patch, rest = _object_without_properties(_step_serialized, [
832
+ "patch"
833
+ ]);
834
+ return rest;
835
+ }),
836
+ options: options,
837
+ brainRunId: brainRunId
838
+ }
839
+ ];
840
+ case 8:
841
+ _state.sent();
842
+ this.currentStepIndex++;
843
+ return [
844
+ 3,
845
+ 4
846
+ ];
847
+ case 9:
848
+ return [
849
+ 4,
850
+ {
851
+ type: BRAIN_EVENTS.COMPLETE,
852
+ status: STATUS.COMPLETE,
853
+ brainTitle: brainTitle,
854
+ brainDescription: brainDescription,
855
+ brainRunId: brainRunId,
856
+ options: options
857
+ }
858
+ ];
859
+ case 10:
860
+ _state.sent();
861
+ return [
862
+ 3,
863
+ 14
864
+ ];
865
+ case 11:
866
+ err = _state.sent();
867
+ error = err;
868
+ currentStep = steps[this.currentStepIndex];
869
+ currentStep === null || currentStep === void 0 ? void 0 : currentStep.withStatus(STATUS.ERROR);
870
+ return [
871
+ 4,
872
+ {
873
+ type: BRAIN_EVENTS.ERROR,
874
+ status: STATUS.ERROR,
875
+ brainTitle: brainTitle,
876
+ brainDescription: brainDescription,
877
+ brainRunId: brainRunId,
878
+ error: {
879
+ name: error.name,
880
+ message: error.message,
881
+ stack: error.stack
882
+ },
883
+ options: options
884
+ }
885
+ ];
886
+ case 12:
887
+ _state.sent();
888
+ // Step Status Event
889
+ return [
890
+ 4,
891
+ {
892
+ type: BRAIN_EVENTS.STEP_STATUS,
893
+ steps: steps.map(function(step) {
894
+ var _step_serialized = step.serialized, patch = _step_serialized.patch, rest = _object_without_properties(_step_serialized, [
895
+ "patch"
896
+ ]);
897
+ return rest;
898
+ }),
899
+ options: options,
900
+ brainRunId: brainRunId
901
+ }
902
+ ];
903
+ case 13:
904
+ _state.sent();
905
+ throw error;
906
+ case 14:
907
+ return [
908
+ 2
909
+ ];
910
+ }
911
+ });
912
+ }).call(this);
913
+ }
914
+ },
915
+ {
916
+ key: "executeStep",
917
+ value: function executeStep(step) {
918
+ return _wrap_async_generator(function() {
919
+ var block, initialState, patches, _this_options, innerRun, _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, _value, event, err, innerState, prevState, _, prevState1, _this_options1, _1;
920
+ return _ts_generator(this, function(_state) {
921
+ switch(_state.label){
922
+ case 0:
923
+ block = step.block;
924
+ if (!(block.type === 'brain')) return [
925
+ 3,
926
+ 16
927
+ ];
928
+ initialState = typeof block.initialState === 'function' ? block.initialState(this.currentState) : block.initialState;
929
+ // Run inner brain and yield all its events
930
+ patches = [];
931
+ innerRun = block.innerBrain.run({
932
+ resources: this.resources,
933
+ client: this.client,
934
+ initialState: initialState,
935
+ options: (_this_options = this.options) !== null && _this_options !== void 0 ? _this_options : {}
936
+ });
937
+ _iteratorAbruptCompletion = false, _didIteratorError = false;
938
+ _state.label = 1;
939
+ case 1:
940
+ _state.trys.push([
941
+ 1,
942
+ 7,
943
+ 8,
944
+ 13
945
+ ]);
946
+ _iterator = _async_iterator(innerRun);
947
+ _state.label = 2;
948
+ case 2:
949
+ return [
950
+ 4,
951
+ _await_async_generator(_iterator.next())
952
+ ];
953
+ case 3:
954
+ if (!(_iteratorAbruptCompletion = !(_step = _state.sent()).done)) return [
955
+ 3,
956
+ 6
957
+ ];
958
+ _value = _step.value;
959
+ event = _value;
960
+ return [
961
+ 4,
962
+ event
963
+ ];
964
+ case 4:
965
+ _state.sent(); // Forward all inner brain events
966
+ if (event.type === BRAIN_EVENTS.STEP_COMPLETE) {
967
+ patches.push(event.patch);
968
+ }
969
+ _state.label = 5;
970
+ case 5:
971
+ _iteratorAbruptCompletion = false;
972
+ return [
973
+ 3,
974
+ 2
975
+ ];
976
+ case 6:
977
+ return [
978
+ 3,
979
+ 13
980
+ ];
981
+ case 7:
982
+ err = _state.sent();
983
+ _didIteratorError = true;
984
+ _iteratorError = err;
985
+ return [
986
+ 3,
987
+ 13
988
+ ];
989
+ case 8:
990
+ _state.trys.push([
991
+ 8,
992
+ ,
993
+ 11,
994
+ 12
995
+ ]);
996
+ if (!(_iteratorAbruptCompletion && _iterator.return != null)) return [
997
+ 3,
998
+ 10
999
+ ];
1000
+ return [
1001
+ 4,
1002
+ _await_async_generator(_iterator.return())
1003
+ ];
1004
+ case 9:
1005
+ _state.sent();
1006
+ _state.label = 10;
1007
+ case 10:
1008
+ return [
1009
+ 3,
1010
+ 12
1011
+ ];
1012
+ case 11:
1013
+ if (_didIteratorError) {
1014
+ throw _iteratorError;
1015
+ }
1016
+ return [
1017
+ 7
1018
+ ];
1019
+ case 12:
1020
+ return [
1021
+ 7
1022
+ ];
1023
+ case 13:
1024
+ // Apply collected patches to get final inner state
1025
+ innerState = applyPatches(initialState, patches);
1026
+ // Get previous state before action
1027
+ prevState = this.currentState;
1028
+ // Update state with inner brain results
1029
+ _ = this;
1030
+ return [
1031
+ 4,
1032
+ _await_async_generator(block.action(this.currentState, innerState, this.services))
1033
+ ];
1034
+ case 14:
1035
+ _.currentState = _state.sent();
1036
+ return [
1037
+ 5,
1038
+ _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState))))
1039
+ ];
1040
+ case 15:
1041
+ _state.sent();
1042
+ return [
1043
+ 3,
1044
+ 19
1045
+ ];
1046
+ case 16:
1047
+ // Get previous state before action
1048
+ prevState1 = this.currentState;
1049
+ // Execute regular step
1050
+ _1 = this;
1051
+ return [
1052
+ 4,
1053
+ _await_async_generator(block.action(_object_spread({
1054
+ state: this.currentState,
1055
+ options: (_this_options1 = this.options) !== null && _this_options1 !== void 0 ? _this_options1 : {},
1056
+ client: this.client,
1057
+ resources: this.resources
1058
+ }, this.services)))
1059
+ ];
1060
+ case 17:
1061
+ _1.currentState = _state.sent();
1062
+ return [
1063
+ 5,
1064
+ _ts_values(_async_generator_delegate(_async_iterator(this.completeStep(step, prevState1))))
1065
+ ];
1066
+ case 18:
1067
+ _state.sent();
1068
+ _state.label = 19;
1069
+ case 19:
1070
+ return [
1071
+ 2
1072
+ ];
1073
+ }
1074
+ });
1075
+ }).call(this);
1076
+ }
1077
+ },
1078
+ {
1079
+ key: "completeStep",
1080
+ value: function completeStep(step, prevState) {
1081
+ var patch, _this_options;
1082
+ return _ts_generator(this, function(_state) {
1083
+ switch(_state.label){
1084
+ case 0:
1085
+ step.withStatus(STATUS.COMPLETE);
1086
+ // Create patch for the state change
1087
+ patch = createPatch(prevState, this.currentState);
1088
+ step.withPatch(patch);
1089
+ return [
1090
+ 4,
1091
+ {
1092
+ type: BRAIN_EVENTS.STEP_COMPLETE,
1093
+ status: STATUS.RUNNING,
1094
+ stepTitle: step.block.title,
1095
+ stepId: step.id,
1096
+ patch: patch,
1097
+ options: (_this_options = this.options) !== null && _this_options !== void 0 ? _this_options : {},
1098
+ brainRunId: this.brainRunId
1099
+ }
1100
+ ];
1101
+ case 1:
1102
+ _state.sent();
1103
+ return [
1104
+ 2
1105
+ ];
1106
+ }
1107
+ });
1108
+ }
1109
+ }
1110
+ ]);
1111
+ return BrainEventStream;
1112
+ }();
1113
+ var brainNamesAreUnique = process.env.NODE_ENV !== 'test';
1114
+ var brainNames = new Set();
1115
+ export var brain = function brain(brainConfig) {
1116
+ var title = typeof brainConfig === 'string' ? brainConfig : brainConfig.title;
1117
+ var description = typeof brainConfig === 'string' ? undefined : brainConfig.description;
1118
+ if (brainNamesAreUnique && brainNames.has(title)) {
1119
+ throw new Error('Brain with name "'.concat(title, '" already exists. Brain names must be unique.'));
1120
+ }
1121
+ if (brainNamesAreUnique) {
1122
+ brainNames.add(title);
1123
+ }
1124
+ return new Brain(title, description);
1125
+ };
1126
+ var clone = function(value) {
1127
+ return structuredClone(value);
1128
+ };