@positronic/core 0.0.52 → 0.0.53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/dist/src/dsl/{loop-messages.js → agent-messages.js} +21 -21
  2. package/dist/src/dsl/brain-runner.js +6 -6
  3. package/dist/src/dsl/brain-state-machine.js +2 -2
  4. package/dist/src/dsl/brain.js +5 -1912
  5. package/dist/src/dsl/builder/brain.js +944 -0
  6. package/dist/src/dsl/builder/step.js +75 -0
  7. package/dist/src/dsl/constants.js +9 -10
  8. package/dist/src/dsl/create-brain.js +63 -0
  9. package/dist/src/dsl/definitions/blocks.js +1 -0
  10. package/dist/src/dsl/definitions/brain-types.js +4 -0
  11. package/dist/src/dsl/definitions/events.js +2 -0
  12. package/dist/src/dsl/definitions/run-params.js +1 -0
  13. package/dist/src/dsl/definitions/steps.js +2 -0
  14. package/dist/src/dsl/execution/constants.js +14 -0
  15. package/dist/src/dsl/execution/event-stream.js +1638 -0
  16. package/dist/src/dsl/execution/retry.js +298 -0
  17. package/dist/src/dsl/types.js +2 -2
  18. package/dist/src/index.js +5 -3
  19. package/dist/src/tools/index.js +181 -0
  20. package/dist/src/ui/component-utils.js +107 -0
  21. package/dist/src/ui/generate-page-html.js +36 -0
  22. package/dist/src/ui/generate-ui.js +601 -0
  23. package/dist/src/ui/types.js +165 -0
  24. package/dist/src/ui/validate-form.js +428 -0
  25. package/dist/src/yaml/data-validator.js +302 -0
  26. package/dist/src/yaml/index.js +9 -0
  27. package/dist/src/yaml/parser.js +224 -0
  28. package/dist/src/yaml/schema-extractor.js +330 -0
  29. package/dist/src/yaml/type-inference.js +210 -0
  30. package/dist/src/yaml/types.js +12 -0
  31. package/dist/types/clients/types.d.ts +42 -0
  32. package/dist/types/clients/types.d.ts.map +1 -1
  33. package/dist/types/dsl/agent-messages.d.ts +18 -0
  34. package/dist/types/dsl/agent-messages.d.ts.map +1 -0
  35. package/dist/types/dsl/brain-runner.d.ts +2 -2
  36. package/dist/types/dsl/brain-runner.d.ts.map +1 -1
  37. package/dist/types/dsl/brain-state-machine.d.ts.map +1 -1
  38. package/dist/types/dsl/brain.d.ts +7 -273
  39. package/dist/types/dsl/brain.d.ts.map +1 -1
  40. package/dist/types/dsl/builder/brain.d.ts +200 -0
  41. package/dist/types/dsl/builder/brain.d.ts.map +1 -0
  42. package/dist/types/dsl/builder/step.d.ts +15 -0
  43. package/dist/types/dsl/builder/step.d.ts.map +1 -0
  44. package/dist/types/dsl/constants.d.ts +8 -9
  45. package/dist/types/dsl/constants.d.ts.map +1 -1
  46. package/dist/types/dsl/create-brain.d.ts +80 -0
  47. package/dist/types/dsl/create-brain.d.ts.map +1 -0
  48. package/dist/types/dsl/definitions/blocks.d.ts +62 -0
  49. package/dist/types/dsl/definitions/blocks.d.ts.map +1 -0
  50. package/dist/types/dsl/definitions/brain-types.d.ts +33 -0
  51. package/dist/types/dsl/definitions/brain-types.d.ts.map +1 -0
  52. package/dist/types/dsl/definitions/events.d.ts +129 -0
  53. package/dist/types/dsl/definitions/events.d.ts.map +1 -0
  54. package/dist/types/dsl/definitions/run-params.d.ts +26 -0
  55. package/dist/types/dsl/definitions/run-params.d.ts.map +1 -0
  56. package/dist/types/dsl/definitions/steps.d.ts +20 -0
  57. package/dist/types/dsl/definitions/steps.d.ts.map +1 -0
  58. package/dist/types/dsl/example-webhook.d.ts +1 -1
  59. package/dist/types/dsl/example-webhook.d.ts.map +1 -1
  60. package/dist/types/dsl/execution/constants.d.ts +16 -0
  61. package/dist/types/dsl/execution/constants.d.ts.map +1 -0
  62. package/dist/types/dsl/execution/event-stream.d.ts +44 -0
  63. package/dist/types/dsl/execution/event-stream.d.ts.map +1 -0
  64. package/dist/types/dsl/execution/retry.d.ts +30 -0
  65. package/dist/types/dsl/execution/retry.d.ts.map +1 -0
  66. package/dist/types/dsl/types.d.ts +35 -14
  67. package/dist/types/dsl/types.d.ts.map +1 -1
  68. package/dist/types/index.d.ts +9 -7
  69. package/dist/types/index.d.ts.map +1 -1
  70. package/dist/types/tools/index.d.ts +33 -0
  71. package/dist/types/tools/index.d.ts.map +1 -0
  72. package/dist/types/ui/component-utils.d.ts +19 -0
  73. package/dist/types/ui/component-utils.d.ts.map +1 -0
  74. package/dist/types/ui/generate-page-html.d.ts +39 -0
  75. package/dist/types/ui/generate-page-html.d.ts.map +1 -0
  76. package/dist/types/ui/generate-ui.d.ts +47 -0
  77. package/dist/types/ui/generate-ui.d.ts.map +1 -0
  78. package/dist/types/ui/types.d.ts +138 -0
  79. package/dist/types/ui/types.d.ts.map +1 -0
  80. package/dist/types/ui/validate-form.d.ts +45 -0
  81. package/dist/types/ui/validate-form.d.ts.map +1 -0
  82. package/dist/types/yaml/data-validator.d.ts +35 -0
  83. package/dist/types/yaml/data-validator.d.ts.map +1 -0
  84. package/dist/types/yaml/index.d.ts +11 -0
  85. package/dist/types/yaml/index.d.ts.map +1 -0
  86. package/dist/types/yaml/parser.d.ts +20 -0
  87. package/dist/types/yaml/parser.d.ts.map +1 -0
  88. package/dist/types/yaml/schema-extractor.d.ts +29 -0
  89. package/dist/types/yaml/schema-extractor.d.ts.map +1 -0
  90. package/dist/types/yaml/type-inference.d.ts +50 -0
  91. package/dist/types/yaml/type-inference.d.ts.map +1 -0
  92. package/dist/types/yaml/types.d.ts +89 -0
  93. package/dist/types/yaml/types.d.ts.map +1 -0
  94. package/package.json +4 -2
  95. package/dist/types/dsl/loop-messages.d.ts +0 -18
  96. package/dist/types/dsl/loop-messages.d.ts.map +0 -1
@@ -0,0 +1,944 @@
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 _class_call_check(instance, Constructor) {
188
+ if (!(instance instanceof Constructor)) {
189
+ throw new TypeError("Cannot call a class as a function");
190
+ }
191
+ }
192
+ function _defineProperties(target, props) {
193
+ for(var i = 0; i < props.length; i++){
194
+ var descriptor = props[i];
195
+ descriptor.enumerable = descriptor.enumerable || false;
196
+ descriptor.configurable = true;
197
+ if ("value" in descriptor) descriptor.writable = true;
198
+ Object.defineProperty(target, descriptor.key, descriptor);
199
+ }
200
+ }
201
+ function _create_class(Constructor, protoProps, staticProps) {
202
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
203
+ if (staticProps) _defineProperties(Constructor, staticProps);
204
+ return Constructor;
205
+ }
206
+ function _define_property(obj, key, value) {
207
+ if (key in obj) {
208
+ Object.defineProperty(obj, key, {
209
+ value: value,
210
+ enumerable: true,
211
+ configurable: true,
212
+ writable: true
213
+ });
214
+ } else {
215
+ obj[key] = value;
216
+ }
217
+ return obj;
218
+ }
219
+ function _object_spread(target) {
220
+ for(var i = 1; i < arguments.length; i++){
221
+ var source = arguments[i] != null ? arguments[i] : {};
222
+ var ownKeys = Object.keys(source);
223
+ if (typeof Object.getOwnPropertySymbols === "function") {
224
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
225
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
226
+ }));
227
+ }
228
+ ownKeys.forEach(function(key) {
229
+ _define_property(target, key, source[key]);
230
+ });
231
+ }
232
+ return target;
233
+ }
234
+ function ownKeys(object, enumerableOnly) {
235
+ var keys = Object.keys(object);
236
+ if (Object.getOwnPropertySymbols) {
237
+ var symbols = Object.getOwnPropertySymbols(object);
238
+ if (enumerableOnly) {
239
+ symbols = symbols.filter(function(sym) {
240
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
241
+ });
242
+ }
243
+ keys.push.apply(keys, symbols);
244
+ }
245
+ return keys;
246
+ }
247
+ function _object_spread_props(target, source) {
248
+ source = source != null ? source : {};
249
+ if (Object.getOwnPropertyDescriptors) {
250
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
251
+ } else {
252
+ ownKeys(Object(source)).forEach(function(key) {
253
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
254
+ });
255
+ }
256
+ return target;
257
+ }
258
+ function _overload_yield(value, kind) {
259
+ this.v = value;
260
+ this.k = kind;
261
+ }
262
+ function _type_of(obj) {
263
+ "@swc/helpers - typeof";
264
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
265
+ }
266
+ function _wrap_async_generator(fn) {
267
+ return function() {
268
+ return new _async_generator(fn.apply(this, arguments));
269
+ };
270
+ }
271
+ function _ts_generator(thisArg, body) {
272
+ var f, y, t, _ = {
273
+ label: 0,
274
+ sent: function() {
275
+ if (t[0] & 1) throw t[1];
276
+ return t[1];
277
+ },
278
+ trys: [],
279
+ ops: []
280
+ }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
281
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
282
+ return this;
283
+ }), g;
284
+ function verb(n) {
285
+ return function(v) {
286
+ return step([
287
+ n,
288
+ v
289
+ ]);
290
+ };
291
+ }
292
+ function step(op) {
293
+ if (f) throw new TypeError("Generator is already executing.");
294
+ while(g && (g = 0, op[0] && (_ = 0)), _)try {
295
+ 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;
296
+ if (y = 0, t) op = [
297
+ op[0] & 2,
298
+ t.value
299
+ ];
300
+ switch(op[0]){
301
+ case 0:
302
+ case 1:
303
+ t = op;
304
+ break;
305
+ case 4:
306
+ _.label++;
307
+ return {
308
+ value: op[1],
309
+ done: false
310
+ };
311
+ case 5:
312
+ _.label++;
313
+ y = op[1];
314
+ op = [
315
+ 0
316
+ ];
317
+ continue;
318
+ case 7:
319
+ op = _.ops.pop();
320
+ _.trys.pop();
321
+ continue;
322
+ default:
323
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
324
+ _ = 0;
325
+ continue;
326
+ }
327
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
328
+ _.label = op[1];
329
+ break;
330
+ }
331
+ if (op[0] === 6 && _.label < t[1]) {
332
+ _.label = t[1];
333
+ t = op;
334
+ break;
335
+ }
336
+ if (t && _.label < t[2]) {
337
+ _.label = t[2];
338
+ _.ops.push(op);
339
+ break;
340
+ }
341
+ if (t[2]) _.ops.pop();
342
+ _.trys.pop();
343
+ continue;
344
+ }
345
+ op = body.call(thisArg, _);
346
+ } catch (e) {
347
+ op = [
348
+ 6,
349
+ e
350
+ ];
351
+ y = 0;
352
+ } finally{
353
+ f = t = 0;
354
+ }
355
+ if (op[0] & 5) throw op[1];
356
+ return {
357
+ value: op[0] ? op[1] : void 0,
358
+ done: true
359
+ };
360
+ }
361
+ }
362
+ function _ts_values(o) {
363
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
364
+ if (m) return m.call(o);
365
+ if (o && typeof o.length === "number") return {
366
+ next: function() {
367
+ if (o && i >= o.length) o = void 0;
368
+ return {
369
+ value: o && o[i++],
370
+ done: !o
371
+ };
372
+ }
373
+ };
374
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
375
+ }
376
+ import { z } from 'zod';
377
+ import { BrainEventStream } from '../execution/event-stream.js';
378
+ import { Semaphore, normalizeRetryConfig, executeWithRetry } from '../execution/retry.js';
379
+ export var Brain = /*#__PURE__*/ function() {
380
+ "use strict";
381
+ function Brain(title, description) {
382
+ _class_call_check(this, Brain);
383
+ _define_property(this, "title", void 0);
384
+ _define_property(this, "description", void 0);
385
+ _define_property(this, "blocks", void 0);
386
+ _define_property(this, "type", void 0);
387
+ _define_property(this, "services", void 0);
388
+ _define_property(this, "optionsSchema", void 0);
389
+ _define_property(this, "components", void 0);
390
+ _define_property(this, "defaultTools", void 0);
391
+ this.title = title;
392
+ this.description = description;
393
+ this.blocks = [];
394
+ this.type = 'brain';
395
+ this.services = {};
396
+ }
397
+ _create_class(Brain, [
398
+ {
399
+ key: "structure",
400
+ get: function get() {
401
+ return {
402
+ title: this.title,
403
+ description: this.description,
404
+ steps: this.blocks.map(function(block) {
405
+ if (block.type === 'step') {
406
+ return {
407
+ type: 'step',
408
+ title: block.title
409
+ };
410
+ } else if (block.type === 'agent') {
411
+ return {
412
+ type: 'agent',
413
+ title: block.title
414
+ };
415
+ } else {
416
+ // block.type === 'brain'
417
+ return {
418
+ type: 'brain',
419
+ title: block.title,
420
+ innerBrain: block.innerBrain.structure
421
+ };
422
+ }
423
+ })
424
+ };
425
+ }
426
+ },
427
+ {
428
+ // New method to add services
429
+ key: "withServices",
430
+ value: function withServices(services) {
431
+ var nextBrain = new Brain(this.title, this.description).withBlocks(this.blocks);
432
+ // Set services
433
+ nextBrain.services = services;
434
+ // Copy optionsSchema to maintain it through the chain
435
+ nextBrain.optionsSchema = this.optionsSchema;
436
+ nextBrain.components = this.components;
437
+ nextBrain.defaultTools = this.defaultTools;
438
+ return nextBrain;
439
+ }
440
+ },
441
+ {
442
+ key: "withOptionsSchema",
443
+ value: function withOptionsSchema(schema) {
444
+ var nextBrain = new Brain(this.title, this.description).withBlocks(this.blocks);
445
+ nextBrain.optionsSchema = schema;
446
+ nextBrain.services = this.services;
447
+ nextBrain.components = this.components;
448
+ nextBrain.defaultTools = this.defaultTools;
449
+ return nextBrain;
450
+ }
451
+ },
452
+ {
453
+ /**
454
+ * Configure UI components for generative UI steps.
455
+ *
456
+ * @param components - Record of component definitions
457
+ *
458
+ * @example
459
+ * ```typescript
460
+ * import { components } from '@positronic/gen-ui-components';
461
+ *
462
+ * const myBrain = brain('my-brain')
463
+ * .withComponents(components)
464
+ * .ui('Show Form', formPrompt);
465
+ * ```
466
+ */ key: "withComponents",
467
+ value: function withComponents(components) {
468
+ var nextBrain = new Brain(this.title, this.description).withBlocks(this.blocks);
469
+ nextBrain.optionsSchema = this.optionsSchema;
470
+ nextBrain.services = this.services;
471
+ nextBrain.components = components;
472
+ nextBrain.defaultTools = this.defaultTools;
473
+ return nextBrain;
474
+ }
475
+ },
476
+ {
477
+ /**
478
+ * Configure default tools for agent steps.
479
+ * These tools will be automatically available in all agent steps and can be
480
+ * extended or overridden in individual step configurations.
481
+ *
482
+ * @param tools - Record of default tool definitions
483
+ *
484
+ * @example
485
+ * ```typescript
486
+ * import { defaultTools } from '@positronic/core';
487
+ *
488
+ * const myBrain = brain('my-brain')
489
+ * .withTools(defaultTools)
490
+ * .brain('agent', ({ tools }) => ({
491
+ * system: 'You are helpful',
492
+ * prompt: 'Do something',
493
+ * tools // uses defaults
494
+ * }));
495
+ * ```
496
+ */ key: "withTools",
497
+ value: function withTools(tools) {
498
+ var next = this.nextBrain();
499
+ next.defaultTools = tools;
500
+ return next;
501
+ }
502
+ },
503
+ {
504
+ key: "step",
505
+ value: function step(title, action) {
506
+ var stepBlock = {
507
+ type: 'step',
508
+ title: title,
509
+ action: action
510
+ };
511
+ this.blocks.push(stepBlock);
512
+ return this.nextBrain();
513
+ }
514
+ },
515
+ {
516
+ // Implementation
517
+ key: "brain",
518
+ value: function brain(title, innerBrainOrConfig, action, initialState) {
519
+ // Case 1: Nested brain instance
520
+ if (innerBrainOrConfig && (typeof innerBrainOrConfig === "undefined" ? "undefined" : _type_of(innerBrainOrConfig)) === 'object' && 'type' in innerBrainOrConfig && innerBrainOrConfig.type === 'brain') {
521
+ var nestedBlock = {
522
+ type: 'brain',
523
+ title: title,
524
+ innerBrain: innerBrainOrConfig,
525
+ initialState: initialState || function() {
526
+ return {};
527
+ },
528
+ action: function(outerState, innerState, services) {
529
+ return action({
530
+ state: outerState,
531
+ brainState: innerState,
532
+ services: services
533
+ });
534
+ }
535
+ };
536
+ this.blocks.push(nestedBlock);
537
+ return this.nextBrain();
538
+ }
539
+ // Case 2 & 3: Agent config (object or function)
540
+ var configFn = typeof innerBrainOrConfig === 'function' ? innerBrainOrConfig : function() {
541
+ return innerBrainOrConfig;
542
+ };
543
+ var agentBlock = {
544
+ type: 'agent',
545
+ title: title,
546
+ configFn: configFn
547
+ };
548
+ this.blocks.push(agentBlock);
549
+ return this.nextBrain();
550
+ }
551
+ },
552
+ {
553
+ // Implementation
554
+ key: "prompt",
555
+ value: function prompt(title, config, batchConfig) {
556
+ // Schema-less prompt - returns text response for next step
557
+ if (!config.outputSchema) {
558
+ var textSchema = z.object({
559
+ text: z.string()
560
+ });
561
+ var promptBlock = {
562
+ type: 'step',
563
+ title: title,
564
+ action: function(param) {
565
+ var state = param.state, runClient = param.client, resources = param.resources;
566
+ return _async_to_generator(function() {
567
+ var template, stepClient, client, prompt, response;
568
+ return _ts_generator(this, function(_state) {
569
+ switch(_state.label){
570
+ case 0:
571
+ template = config.template, stepClient = config.client;
572
+ client = stepClient !== null && stepClient !== void 0 ? stepClient : runClient;
573
+ return [
574
+ 4,
575
+ template(state, resources)
576
+ ];
577
+ case 1:
578
+ prompt = _state.sent();
579
+ return [
580
+ 4,
581
+ client.generateObject({
582
+ schema: textSchema,
583
+ schemaName: 'TextResponse',
584
+ prompt: prompt
585
+ })
586
+ ];
587
+ case 2:
588
+ response = _state.sent();
589
+ return [
590
+ 2,
591
+ {
592
+ state: state,
593
+ promptResponse: response
594
+ }
595
+ ];
596
+ }
597
+ });
598
+ })();
599
+ }
600
+ };
601
+ this.blocks.push(promptBlock);
602
+ return this.nextBrain();
603
+ }
604
+ // At this point, outputSchema is guaranteed to exist (schema-less case returned early)
605
+ var outputSchema = config.outputSchema;
606
+ if (batchConfig) {
607
+ // Batch mode - run prompt for each item
608
+ var promptBlock1 = {
609
+ type: 'step',
610
+ title: title,
611
+ action: function(param) {
612
+ var state = param.state, runClient = param.client, resources = param.resources;
613
+ return _async_to_generator(function() {
614
+ var template, stepClient, schema, schemaName, client, items, _batchConfig_concurrency, semaphore, _batchConfig_stagger, stagger, retryConfig, results, sleep, promises, finalResults;
615
+ return _ts_generator(this, function(_state) {
616
+ switch(_state.label){
617
+ case 0:
618
+ template = config.template, stepClient = config.client;
619
+ schema = outputSchema.schema, schemaName = outputSchema.name;
620
+ client = stepClient !== null && stepClient !== void 0 ? stepClient : runClient;
621
+ items = batchConfig.over(state);
622
+ semaphore = new Semaphore((_batchConfig_concurrency = batchConfig.concurrency) !== null && _batchConfig_concurrency !== void 0 ? _batchConfig_concurrency : 10);
623
+ stagger = (_batchConfig_stagger = batchConfig.stagger) !== null && _batchConfig_stagger !== void 0 ? _batchConfig_stagger : 0;
624
+ retryConfig = normalizeRetryConfig(batchConfig.retry);
625
+ results = new Array(items.length);
626
+ sleep = function(ms) {
627
+ return new Promise(function(r) {
628
+ return setTimeout(r, ms);
629
+ });
630
+ };
631
+ promises = items.map(function(item, index) {
632
+ return _async_to_generator(function() {
633
+ var promptText, output, error, fallback;
634
+ return _ts_generator(this, function(_state) {
635
+ switch(_state.label){
636
+ case 0:
637
+ if (!(stagger > 0 && index > 0)) return [
638
+ 3,
639
+ 2
640
+ ];
641
+ return [
642
+ 4,
643
+ sleep(stagger * index)
644
+ ];
645
+ case 1:
646
+ _state.sent();
647
+ _state.label = 2;
648
+ case 2:
649
+ return [
650
+ 4,
651
+ semaphore.acquire()
652
+ ];
653
+ case 3:
654
+ _state.sent();
655
+ _state.label = 4;
656
+ case 4:
657
+ _state.trys.push([
658
+ 4,
659
+ 7,
660
+ 8,
661
+ 9
662
+ ]);
663
+ return [
664
+ 4,
665
+ template(item, resources)
666
+ ];
667
+ case 5:
668
+ promptText = _state.sent();
669
+ return [
670
+ 4,
671
+ executeWithRetry(function() {
672
+ return client.generateObject({
673
+ schema: schema,
674
+ schemaName: schemaName,
675
+ prompt: promptText
676
+ });
677
+ }, retryConfig)
678
+ ];
679
+ case 6:
680
+ output = _state.sent();
681
+ results[index] = [
682
+ item,
683
+ output
684
+ ];
685
+ return [
686
+ 3,
687
+ 9
688
+ ];
689
+ case 7:
690
+ error = _state.sent();
691
+ if (batchConfig.error) {
692
+ fallback = batchConfig.error(item, error);
693
+ if (fallback !== null) {
694
+ results[index] = [
695
+ item,
696
+ fallback
697
+ ];
698
+ }
699
+ } else {
700
+ throw error;
701
+ }
702
+ return [
703
+ 3,
704
+ 9
705
+ ];
706
+ case 8:
707
+ semaphore.release();
708
+ return [
709
+ 7
710
+ ];
711
+ case 9:
712
+ return [
713
+ 2
714
+ ];
715
+ }
716
+ });
717
+ })();
718
+ });
719
+ return [
720
+ 4,
721
+ Promise.all(promises)
722
+ ];
723
+ case 1:
724
+ _state.sent();
725
+ finalResults = results.filter(function(r) {
726
+ return r !== undefined;
727
+ });
728
+ return [
729
+ 2,
730
+ _object_spread_props(_object_spread({}, state), _define_property({}, outputSchema.name, finalResults))
731
+ ];
732
+ }
733
+ });
734
+ })();
735
+ }
736
+ };
737
+ this.blocks.push(promptBlock1);
738
+ return this.nextBrain();
739
+ } else {
740
+ // Single mode - run prompt once with current state
741
+ var promptBlock2 = {
742
+ type: 'step',
743
+ title: title,
744
+ action: function(param) {
745
+ var state = param.state, runClient = param.client, resources = param.resources;
746
+ return _async_to_generator(function() {
747
+ var template, stepClient, schema, schemaName, client, prompt, response;
748
+ return _ts_generator(this, function(_state) {
749
+ switch(_state.label){
750
+ case 0:
751
+ template = config.template, stepClient = config.client;
752
+ schema = outputSchema.schema, schemaName = outputSchema.name;
753
+ client = stepClient !== null && stepClient !== void 0 ? stepClient : runClient;
754
+ return [
755
+ 4,
756
+ template(state, resources)
757
+ ];
758
+ case 1:
759
+ prompt = _state.sent();
760
+ return [
761
+ 4,
762
+ client.generateObject({
763
+ schema: schema,
764
+ schemaName: schemaName,
765
+ prompt: prompt
766
+ })
767
+ ];
768
+ case 2:
769
+ response = _state.sent();
770
+ return [
771
+ 2,
772
+ _object_spread_props(_object_spread({}, state), _define_property({}, outputSchema.name, response))
773
+ ];
774
+ }
775
+ });
776
+ })();
777
+ }
778
+ };
779
+ this.blocks.push(promptBlock2);
780
+ return this.nextBrain();
781
+ }
782
+ }
783
+ },
784
+ {
785
+ /**
786
+ * Add a UI generation step that creates an interactive page.
787
+ *
788
+ * The step:
789
+ * 1. Calls an LLM agent to generate UI components based on the prompt
790
+ * 2. Renders the components to an HTML page
791
+ * 3. Stores the page and makes it available via URL
792
+ * 4. Creates a webhook for form submissions (typed based on responseSchema)
793
+ *
794
+ * The next step receives a `page` object with:
795
+ * - `url`: URL to the generated page
796
+ * - `webhook`: Pre-configured WebhookRegistration for form submissions
797
+ *
798
+ * The brain author is responsible for notifying users about the page (via Slack,
799
+ * email, etc.) and using `waitFor` to pause until the form is submitted.
800
+ * Form data arrives in the `response` parameter of the step after `waitFor`.
801
+ *
802
+ * @example
803
+ * ```typescript
804
+ * brain('feedback-form')
805
+ * .step('Initialize', () => ({ userName: 'John' }))
806
+ * .ui('Create Form', {
807
+ * template: (state) => `Create a feedback form for ${state.userName}`,
808
+ * responseSchema: z.object({
809
+ * rating: z.number().min(1).max(5),
810
+ * comments: z.string(),
811
+ * }),
812
+ * })
813
+ * .step('Notify and Wait', async ({ state, page, slack }) => {
814
+ * // Notify user however you want
815
+ * await slack.post('#general', `Please fill out: ${page.url}`);
816
+ * // Wait for form submission
817
+ * return { state, waitFor: [page.webhook] };
818
+ * })
819
+ * .step('Process Feedback', ({ state, response }) => ({
820
+ * ...state,
821
+ * // response is typed: { rating: number, comments: string }
822
+ * rating: response.rating,
823
+ * comments: response.comments,
824
+ * }))
825
+ * ```
826
+ */ key: "ui",
827
+ value: function ui(title, config) {
828
+ var uiBlock = {
829
+ type: 'step',
830
+ title: title,
831
+ isUIStep: true,
832
+ uiConfig: {
833
+ template: config.template,
834
+ responseSchema: config.responseSchema
835
+ },
836
+ action: function(params) {
837
+ return _async_to_generator(function() {
838
+ return _ts_generator(this, function(_state) {
839
+ // The actual UI generation is handled by BrainRunner/BrainEventStream
840
+ // This action is a placeholder that gets replaced during execution
841
+ // when the runner detects `isUIStep: true` and has components configured
842
+ throw new Error('UI step "'.concat(title, '" requires components to be configured via BrainRunner.withComponents(). ') + "The UI generation is handled by the runner, not the step action directly.");
843
+ });
844
+ })();
845
+ }
846
+ };
847
+ this.blocks.push(uiBlock);
848
+ return this.nextBrain();
849
+ }
850
+ },
851
+ {
852
+ key: "run",
853
+ value: // Implementation signature
854
+ function run(params) {
855
+ return _wrap_async_generator(function() {
856
+ var _this, title, description, blocks, validatedOptions, stream;
857
+ return _ts_generator(this, function(_state) {
858
+ switch(_state.label){
859
+ case 0:
860
+ _this = this, title = _this.title, description = _this.description, blocks = _this.blocks;
861
+ if (this.optionsSchema) {
862
+ // Just call parse - Zod handles defaults automatically
863
+ validatedOptions = this.optionsSchema.parse(params.options || {});
864
+ } else {
865
+ // If no schema is defined but options are provided, throw error
866
+ if (params.options && Object.keys(params.options).length > 0) {
867
+ throw new Error("Brain '".concat(this.title, "' received options but no schema was defined. Use withOptionsSchema() to define a schema for options."));
868
+ }
869
+ validatedOptions = {};
870
+ }
871
+ stream = new BrainEventStream(_object_spread_props(_object_spread({
872
+ title: title,
873
+ description: description,
874
+ blocks: blocks
875
+ }, params), {
876
+ options: validatedOptions,
877
+ services: this.services,
878
+ components: this.components,
879
+ defaultTools: this.defaultTools
880
+ }));
881
+ return [
882
+ 5,
883
+ _ts_values(_async_generator_delegate(_async_iterator(stream.next())))
884
+ ];
885
+ case 1:
886
+ _state.sent();
887
+ return [
888
+ 2
889
+ ];
890
+ }
891
+ });
892
+ }).call(this);
893
+ }
894
+ },
895
+ {
896
+ key: "withBlocks",
897
+ value: function withBlocks(blocks) {
898
+ this.blocks = blocks;
899
+ return this;
900
+ }
901
+ },
902
+ {
903
+ key: "nextBrain",
904
+ value: function nextBrain() {
905
+ // Pass default options to the next brain
906
+ var nextBrain = new Brain(this.title, this.description).withBlocks(this.blocks);
907
+ // Copy services to the next brain
908
+ nextBrain.services = this.services;
909
+ // Copy optionsSchema to the next brain
910
+ nextBrain.optionsSchema = this.optionsSchema;
911
+ // Copy components to the next brain
912
+ nextBrain.components = this.components;
913
+ // Copy defaultTools to the next brain
914
+ nextBrain.defaultTools = this.defaultTools;
915
+ return nextBrain;
916
+ }
917
+ }
918
+ ]);
919
+ return Brain;
920
+ }();
921
+ var brainNamesAreUnique = process.env.NODE_ENV !== 'test';
922
+ var brainNames = new Set();
923
+ /**
924
+ * Helper to register a brain name and check for uniqueness
925
+ */ function registerBrainName(title) {
926
+ if (brainNamesAreUnique && brainNames.has(title)) {
927
+ throw new Error('Brain with title "'.concat(title, '" already exists. Brain titles must be unique.'));
928
+ }
929
+ if (brainNamesAreUnique) {
930
+ brainNames.add(title);
931
+ }
932
+ }
933
+ // Implementation
934
+ export function brain(titleOrConfig, agentConfig) {
935
+ var title = typeof titleOrConfig === 'string' ? titleOrConfig : titleOrConfig.title;
936
+ var description = typeof titleOrConfig === 'string' ? undefined : titleOrConfig.description;
937
+ registerBrainName(title);
938
+ var newBrain = new Brain(title, description);
939
+ // If agentConfig is provided, create a brain with a single 'main' agent step
940
+ if (agentConfig !== undefined) {
941
+ return newBrain.brain('main', agentConfig);
942
+ }
943
+ return newBrain;
944
+ }