@positronic/core 0.0.76 → 0.0.78

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 (130) hide show
  1. package/dist/src/dsl/brain-runner.js +37 -182
  2. package/dist/src/dsl/brain-state-machine.js +58 -112
  3. package/dist/src/dsl/brain.js +1 -0
  4. package/dist/src/dsl/builder/brain.js +250 -404
  5. package/dist/src/dsl/builder/continuation.js +67 -0
  6. package/dist/src/dsl/constants.js +16 -17
  7. package/dist/src/dsl/create-brain.js +29 -45
  8. package/dist/src/dsl/example-webhook.js +1 -1
  9. package/dist/src/dsl/execution/constants.js +0 -4
  10. package/dist/src/dsl/execution/event-channel.js +77 -0
  11. package/dist/src/dsl/execution/event-stream.js +1625 -1462
  12. package/dist/src/dsl/signal-validation.js +0 -1
  13. package/dist/src/dsl/webhook.js +4 -1
  14. package/dist/src/files/event-wrapper.js +268 -0
  15. package/dist/src/files/index.js +1 -0
  16. package/dist/src/files/mime.js +31 -0
  17. package/dist/src/files/types.js +13 -0
  18. package/dist/src/index.js +10 -3
  19. package/dist/src/jsx-runtime.js +49 -0
  20. package/dist/src/memory/{scoped-memory.js → create-memory.js} +5 -5
  21. package/dist/src/plugins/collect-webhooks.js +49 -0
  22. package/dist/src/plugins/define-plugin.js +15 -0
  23. package/dist/src/plugins/index.js +1 -0
  24. package/dist/src/plugins/types.js +4 -0
  25. package/dist/src/store/types.js +2 -3
  26. package/dist/src/template/render-html.js +282 -0
  27. package/dist/src/template/render.js +357 -0
  28. package/dist/src/tools/index.js +88 -27
  29. package/dist/src/ui/generate-page-html.js +6 -6
  30. package/dist/src/ui/{generate-ui.js → generate-page.js} +24 -12
  31. package/dist/src/ui/parse-form-data.js +1 -11
  32. package/dist/src/ui/types.js +0 -123
  33. package/dist/src/yaml/data-validator.js +0 -27
  34. package/dist/src/yaml/type-inference.js +10 -9
  35. package/dist/types/clients/types.d.ts +15 -5
  36. package/dist/types/clients/types.d.ts.map +1 -1
  37. package/dist/types/dsl/brain-runner.d.ts +9 -14
  38. package/dist/types/dsl/brain-runner.d.ts.map +1 -1
  39. package/dist/types/dsl/brain-state-machine.d.ts +18 -28
  40. package/dist/types/dsl/brain-state-machine.d.ts.map +1 -1
  41. package/dist/types/dsl/brain.d.ts +3 -2
  42. package/dist/types/dsl/brain.d.ts.map +1 -1
  43. package/dist/types/dsl/builder/brain.d.ts +87 -230
  44. package/dist/types/dsl/builder/brain.d.ts.map +1 -1
  45. package/dist/types/dsl/builder/continuation.d.ts +16 -0
  46. package/dist/types/dsl/builder/continuation.d.ts.map +1 -0
  47. package/dist/types/dsl/constants.d.ts +12 -12
  48. package/dist/types/dsl/constants.d.ts.map +1 -1
  49. package/dist/types/dsl/create-brain.d.ts +17 -57
  50. package/dist/types/dsl/create-brain.d.ts.map +1 -1
  51. package/dist/types/dsl/definitions/blocks.d.ts +67 -55
  52. package/dist/types/dsl/definitions/blocks.d.ts.map +1 -1
  53. package/dist/types/dsl/definitions/brain-types.d.ts +8 -11
  54. package/dist/types/dsl/definitions/brain-types.d.ts.map +1 -1
  55. package/dist/types/dsl/definitions/events.d.ts +61 -55
  56. package/dist/types/dsl/definitions/events.d.ts.map +1 -1
  57. package/dist/types/dsl/definitions/run-params.d.ts +20 -21
  58. package/dist/types/dsl/definitions/run-params.d.ts.map +1 -1
  59. package/dist/types/dsl/definitions/steps.d.ts +1 -1
  60. package/dist/types/dsl/definitions/steps.d.ts.map +1 -1
  61. package/dist/types/dsl/example-webhook.d.ts +3 -3
  62. package/dist/types/dsl/example-webhook.d.ts.map +1 -1
  63. package/dist/types/dsl/execution/constants.d.ts +0 -5
  64. package/dist/types/dsl/execution/constants.d.ts.map +1 -1
  65. package/dist/types/dsl/execution/event-channel.d.ts +16 -0
  66. package/dist/types/dsl/execution/event-channel.d.ts.map +1 -0
  67. package/dist/types/dsl/execution/event-stream.d.ts +46 -34
  68. package/dist/types/dsl/execution/event-stream.d.ts.map +1 -1
  69. package/dist/types/dsl/signal-validation.d.ts.map +1 -1
  70. package/dist/types/dsl/types.d.ts +21 -83
  71. package/dist/types/dsl/types.d.ts.map +1 -1
  72. package/dist/types/dsl/webhook.d.ts +12 -2
  73. package/dist/types/dsl/webhook.d.ts.map +1 -1
  74. package/dist/types/files/event-wrapper.d.ts +20 -0
  75. package/dist/types/files/event-wrapper.d.ts.map +1 -0
  76. package/dist/types/files/index.d.ts +2 -0
  77. package/dist/types/files/index.d.ts.map +1 -0
  78. package/dist/types/files/mime.d.ts +2 -0
  79. package/dist/types/files/mime.d.ts.map +1 -0
  80. package/dist/types/files/types.d.ts +88 -0
  81. package/dist/types/files/types.d.ts.map +1 -0
  82. package/dist/types/index.d.ts +22 -12
  83. package/dist/types/index.d.ts.map +1 -1
  84. package/dist/types/jsx-runtime.d.ts +35 -0
  85. package/dist/types/jsx-runtime.d.ts.map +1 -0
  86. package/dist/types/memory/{scoped-memory.d.ts → create-memory.d.ts} +7 -7
  87. package/dist/types/memory/create-memory.d.ts.map +1 -0
  88. package/dist/types/memory/types.d.ts +4 -4
  89. package/dist/types/memory/types.d.ts.map +1 -1
  90. package/dist/types/plugins/collect-webhooks.d.ts +8 -0
  91. package/dist/types/plugins/collect-webhooks.d.ts.map +1 -0
  92. package/dist/types/plugins/define-plugin.d.ts +25 -0
  93. package/dist/types/plugins/define-plugin.d.ts.map +1 -0
  94. package/dist/types/plugins/index.d.ts +3 -0
  95. package/dist/types/plugins/index.d.ts.map +1 -0
  96. package/dist/types/plugins/types.d.ts +83 -0
  97. package/dist/types/plugins/types.d.ts.map +1 -0
  98. package/dist/types/store/index.d.ts +1 -1
  99. package/dist/types/store/index.d.ts.map +1 -1
  100. package/dist/types/store/types.d.ts +0 -8
  101. package/dist/types/store/types.d.ts.map +1 -1
  102. package/dist/types/template/render-html.d.ts +9 -0
  103. package/dist/types/template/render-html.d.ts.map +1 -0
  104. package/dist/types/template/render.d.ts +15 -0
  105. package/dist/types/template/render.d.ts.map +1 -0
  106. package/dist/types/tools/index.d.ts +39 -27
  107. package/dist/types/tools/index.d.ts.map +1 -1
  108. package/dist/types/ui/generate-page-html.d.ts +4 -6
  109. package/dist/types/ui/generate-page-html.d.ts.map +1 -1
  110. package/dist/types/ui/{generate-ui.d.ts → generate-page.d.ts} +6 -6
  111. package/dist/types/ui/generate-page.d.ts.map +1 -0
  112. package/dist/types/ui/parse-form-data.d.ts +1 -5
  113. package/dist/types/ui/parse-form-data.d.ts.map +1 -1
  114. package/dist/types/ui/types.d.ts +0 -49
  115. package/dist/types/ui/types.d.ts.map +1 -1
  116. package/dist/types/yaml/data-validator.d.ts +0 -5
  117. package/dist/types/yaml/data-validator.d.ts.map +1 -1
  118. package/dist/types/yaml/type-inference.d.ts +4 -2
  119. package/dist/types/yaml/type-inference.d.ts.map +1 -1
  120. package/dist/types/yaml/types.d.ts +0 -1
  121. package/dist/types/yaml/types.d.ts.map +1 -1
  122. package/package.json +5 -1
  123. package/dist/src/dsl/agent-messages.js +0 -5
  124. package/dist/src/ui/validate-form.js +0 -428
  125. package/dist/types/dsl/agent-messages.d.ts +0 -12
  126. package/dist/types/dsl/agent-messages.d.ts.map +0 -1
  127. package/dist/types/memory/scoped-memory.d.ts.map +0 -1
  128. package/dist/types/ui/generate-ui.d.ts.map +0 -1
  129. package/dist/types/ui/validate-form.d.ts +0 -45
  130. package/dist/types/ui/validate-form.d.ts.map +0 -1
@@ -1,11 +1,3 @@
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_without_holes(arr) {
7
- if (Array.isArray(arr)) return _array_like_to_array(arr);
8
- }
9
1
  function _async_iterator(iterable) {
10
2
  var method, async, sync, retry = 2;
11
3
  for("undefined" != typeof Symbol && (async = Symbol.asyncIterator, sync = Symbol.iterator); retry--;){
@@ -108,66 +100,10 @@ function _define_property(obj, key, value) {
108
100
  }
109
101
  return obj;
110
102
  }
111
- function _iterable_to_array(iter) {
112
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
113
- }
114
- function _non_iterable_spread() {
115
- throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
116
- }
117
- function _object_spread(target) {
118
- for(var i = 1; i < arguments.length; i++){
119
- var source = arguments[i] != null ? arguments[i] : {};
120
- var ownKeys = Object.keys(source);
121
- if (typeof Object.getOwnPropertySymbols === "function") {
122
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
123
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
124
- }));
125
- }
126
- ownKeys.forEach(function(key) {
127
- _define_property(target, key, source[key]);
128
- });
129
- }
130
- return target;
131
- }
132
- function ownKeys(object, enumerableOnly) {
133
- var keys = Object.keys(object);
134
- if (Object.getOwnPropertySymbols) {
135
- var symbols = Object.getOwnPropertySymbols(object);
136
- if (enumerableOnly) {
137
- symbols = symbols.filter(function(sym) {
138
- return Object.getOwnPropertyDescriptor(object, sym).enumerable;
139
- });
140
- }
141
- keys.push.apply(keys, symbols);
142
- }
143
- return keys;
144
- }
145
- function _object_spread_props(target, source) {
146
- source = source != null ? source : {};
147
- if (Object.getOwnPropertyDescriptors) {
148
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
149
- } else {
150
- ownKeys(Object(source)).forEach(function(key) {
151
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
152
- });
153
- }
154
- return target;
155
- }
156
- function _to_consumable_array(arr) {
157
- return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
158
- }
159
103
  function _type_of(obj) {
160
104
  "@swc/helpers - typeof";
161
105
  return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
162
106
  }
163
- function _unsupported_iterable_to_array(o, minLen) {
164
- if (!o) return;
165
- if (typeof o === "string") return _array_like_to_array(o, minLen);
166
- var n = Object.prototype.toString.call(o).slice(8, -1);
167
- if (n === "Object" && o.constructor) n = o.constructor.name;
168
- if (n === "Map" || n === "Set") return Array.from(n);
169
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
170
- }
171
107
  function _ts_generator(thisArg, body) {
172
108
  var f, y, t, _ = {
173
109
  label: 0,
@@ -276,39 +212,6 @@ function _ts_values(o) {
276
212
  import { BRAIN_EVENTS, STATUS } from './constants.js';
277
213
  import { createBrainExecutionMachine, sendEvent } from './brain-state-machine.js';
278
214
  import { DEFAULT_ENV } from './brain.js';
279
- /**
280
- * Convert execution stack to ResumeContext tree.
281
- * Adds agent context to the deepest level.
282
- * Webhook response is no longer passed here - it comes from signals during execution.
283
- * This is internal to BrainRunner - external consumers don't need to know about ResumeContext.
284
- */ function executionStackToResumeContext(stack, agentContext, iterateContext, currentPage) {
285
- if (stack.length === 0) {
286
- throw new Error('Cannot convert empty execution stack to ResumeContext');
287
- }
288
- // Build from bottom of stack up (deepest to root)
289
- var context;
290
- for(var i = stack.length - 1; i >= 0; i--){
291
- var entry = stack[i];
292
- if (i === stack.length - 1) {
293
- // Deepest level - add agent context, iterate progress, and page context
294
- context = {
295
- stepIndex: entry.stepIndex,
296
- state: entry.state,
297
- agentContext: agentContext !== null && agentContext !== void 0 ? agentContext : undefined,
298
- iterateProgress: iterateContext !== null && iterateContext !== void 0 ? iterateContext : undefined,
299
- currentPage: currentPage !== null && currentPage !== void 0 ? currentPage : undefined
300
- };
301
- } else {
302
- // Outer level - wrap inner context
303
- context = {
304
- stepIndex: entry.stepIndex,
305
- state: entry.state,
306
- innerResumeContext: context
307
- };
308
- }
309
- }
310
- return context;
311
- }
312
215
  /**
313
216
  * Create a CANCELLED event for when the brain is aborted via signal.
314
217
  * This is synthesized by the runner, not yielded from the brain's event stream.
@@ -323,75 +226,16 @@ import { DEFAULT_ENV } from './brain.js';
323
226
  }
324
227
  export var BrainRunner = /*#__PURE__*/ function() {
325
228
  "use strict";
326
- function BrainRunner(options) {
229
+ function BrainRunner(config) {
327
230
  _class_call_check(this, BrainRunner);
328
- _define_property(this, "options", void 0);
329
- this.options = options;
231
+ _define_property(this, "config", void 0);
232
+ this.config = config;
330
233
  }
331
234
  _create_class(BrainRunner, [
332
235
  {
333
- key: "withAdapters",
334
- value: function withAdapters(adapters) {
335
- var _this_options = this.options, existingAdapters = _this_options.adapters;
336
- return new BrainRunner(_object_spread_props(_object_spread({}, this.options), {
337
- adapters: _to_consumable_array(existingAdapters).concat(_to_consumable_array(adapters))
338
- }));
339
- }
340
- },
341
- {
342
- key: "withClient",
343
- value: function withClient(client) {
344
- return new BrainRunner(_object_spread_props(_object_spread({}, this.options), {
345
- client: client
346
- }));
347
- }
348
- },
349
- {
350
- key: "withResources",
351
- value: function withResources(resources) {
352
- return new BrainRunner(_object_spread_props(_object_spread({}, this.options), {
353
- resources: resources
354
- }));
355
- }
356
- },
357
- {
358
- key: "withPages",
359
- value: function withPages(pages) {
360
- return new BrainRunner(_object_spread_props(_object_spread({}, this.options), {
361
- pages: pages
362
- }));
363
- }
364
- },
365
- {
366
- key: "withEnv",
367
- value: function withEnv(env) {
368
- return new BrainRunner(_object_spread_props(_object_spread({}, this.options), {
369
- env: env
370
- }));
371
- }
372
- },
373
- {
374
- key: "withSignalProvider",
375
- value: function withSignalProvider(signalProvider) {
376
- return new BrainRunner(_object_spread_props(_object_spread({}, this.options), {
377
- signalProvider: signalProvider
378
- }));
379
- }
380
- },
381
- {
382
- key: "withGovernor",
383
- value: function withGovernor(governor) {
384
- return new BrainRunner(_object_spread_props(_object_spread({}, this.options), {
385
- governor: governor
386
- }));
387
- }
388
- },
389
- {
390
- key: "withStoreProvider",
391
- value: function withStoreProvider(storeProvider) {
392
- return new BrainRunner(_object_spread_props(_object_spread({}, this.options), {
393
- storeProvider: storeProvider
394
- }));
236
+ key: "client",
237
+ get: function get() {
238
+ return this.config.client;
395
239
  }
396
240
  },
397
241
  {
@@ -424,28 +268,37 @@ export var BrainRunner = /*#__PURE__*/ function() {
424
268
  value: /**
425
269
  * Resume a brain from a previous execution point.
426
270
  * The machine should have historical events already replayed to reconstruct execution state.
427
- * The BrainRunner will derive the ResumeContext from the machine's execution stack.
271
+ * The BrainRunner builds a ResumeParams from the machine's execution stack.
428
272
  * Webhook response data comes from signals, not as a parameter.
429
273
  */ function resume(brain, options) {
430
274
  return _async_to_generator(function() {
431
- var machine, brainRunId, brainOptions, endAfter, signal, currentUser, _machine_context, executionStack, agentContext, iterateContext, currentPage, resumeContext;
275
+ var machine, brainRunId, brainOptions, endAfter, signal, currentUser, _machine_context, executionStack, iterateContext, currentPage, promptLoopContext, topEntry, innerStack;
432
276
  return _ts_generator(this, function(_state) {
433
277
  machine = options.machine, brainRunId = options.brainRunId, brainOptions = options.options, endAfter = options.endAfter, signal = options.signal, currentUser = options.currentUser;
434
- // Build ResumeContext from machine's execution stack
435
- // Webhook response comes from signals during execution, not from resume parameters
436
- _machine_context = machine.context, executionStack = _machine_context.executionStack, agentContext = _machine_context.agentContext, iterateContext = _machine_context.iterateContext, currentPage = _machine_context.currentPage;
437
- resumeContext = executionStackToResumeContext(executionStack, agentContext, iterateContext, currentPage);
278
+ _machine_context = machine.context, executionStack = _machine_context.executionStack, iterateContext = _machine_context.iterateContext, currentPage = _machine_context.currentPage, promptLoopContext = _machine_context.promptLoopContext;
279
+ if (executionStack.length === 0) {
280
+ throw new Error('Cannot resume from empty execution stack');
281
+ }
282
+ topEntry = executionStack[0];
283
+ innerStack = executionStack.length > 1 ? executionStack.slice(1) : undefined;
438
284
  return [
439
285
  2,
440
286
  this.execute(brain, {
441
- resumeContext: resumeContext,
287
+ resume: {
288
+ state: topEntry.state,
289
+ stepIndex: topEntry.stepIndex,
290
+ innerStack: innerStack,
291
+ iterateProgress: iterateContext !== null && iterateContext !== void 0 ? iterateContext : undefined,
292
+ currentPage: currentPage !== null && currentPage !== void 0 ? currentPage : undefined,
293
+ promptLoopContext: promptLoopContext !== null && promptLoopContext !== void 0 ? promptLoopContext : undefined
294
+ },
442
295
  machine: machine,
443
296
  options: brainOptions,
444
297
  brainRunId: brainRunId,
445
298
  endAfter: endAfter,
446
299
  signal: signal,
447
300
  currentUser: currentUser,
448
- initialStepCount: resumeContext.stepIndex
301
+ initialStepCount: topEntry.stepIndex
449
302
  })
450
303
  ];
451
304
  });
@@ -458,43 +311,45 @@ export var BrainRunner = /*#__PURE__*/ function() {
458
311
  * Internal execution method shared by run() and resume().
459
312
  */ function execute(brain, params) {
460
313
  return _async_to_generator(function() {
461
- var _this_options, adapters, rawClient, resources, pages, env, signalProvider, governor, storeProvider, client, resolvedEnv, initialState, resumeContext, providedMachine, options, brainRunId, endAfter, signal, currentUser, initialStepCount, _resumeContext_state, _ref, machine, brainRun, _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _loop, _iterator, _step, _ret, err, error, _machine_context_brainRunId, cancelledEvent;
314
+ var _this_config, rawClient, adapters, env, resources, signalProvider, governor, files, pages, storeProvider, client, resolvedEnv, initialState, resume, providedMachine, options, brainRunId, endAfter, signal, currentUser, initialStepCount, _resume_state, _ref, machine, brainRun, _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _loop, _iterator, _step, _ret, err, error, _machine_context_brainRunId, cancelledEvent;
462
315
  return _ts_generator(this, function(_state) {
463
316
  switch(_state.label){
464
317
  case 0:
465
- _this_options = this.options, adapters = _this_options.adapters, rawClient = _this_options.client, resources = _this_options.resources, pages = _this_options.pages, env = _this_options.env, signalProvider = _this_options.signalProvider, governor = _this_options.governor, storeProvider = _this_options.storeProvider;
318
+ _this_config = this.config, rawClient = _this_config.client, adapters = _this_config.adapters, env = _this_config.env, resources = _this_config.resources, signalProvider = _this_config.signalProvider, governor = _this_config.governor, files = _this_config.files, pages = _this_config.pages, storeProvider = _this_config.storeProvider;
466
319
  client = governor ? governor(rawClient) : rawClient;
467
320
  resolvedEnv = env !== null && env !== void 0 ? env : DEFAULT_ENV;
468
- initialState = params.initialState, resumeContext = params.resumeContext, providedMachine = params.machine, options = params.options, brainRunId = params.brainRunId, endAfter = params.endAfter, signal = params.signal, currentUser = params.currentUser, initialStepCount = params.initialStepCount;
321
+ initialState = params.initialState, resume = params.resume, providedMachine = params.machine, options = params.options, brainRunId = params.brainRunId, endAfter = params.endAfter, signal = params.signal, currentUser = params.currentUser, initialStepCount = params.initialStepCount;
469
322
  // Use provided state machine if available (for resumes with historical events),
470
323
  // otherwise create a new one
471
324
  machine = providedMachine !== null && providedMachine !== void 0 ? providedMachine : createBrainExecutionMachine({
472
- initialState: (_ref = (_resumeContext_state = resumeContext === null || resumeContext === void 0 ? void 0 : resumeContext.state) !== null && _resumeContext_state !== void 0 ? _resumeContext_state : initialState) !== null && _ref !== void 0 ? _ref : {}
325
+ initialState: (_ref = (_resume_state = resume === null || resume === void 0 ? void 0 : resume.state) !== null && _resume_state !== void 0 ? _resume_state : initialState) !== null && _ref !== void 0 ? _ref : {}
473
326
  });
474
- brainRun = resumeContext ? brain.run({
475
- resumeContext: resumeContext,
327
+ brainRun = resume ? brain.run({
328
+ resume: resume,
476
329
  brainRunId: brainRunId,
477
330
  options: options,
478
331
  client: client,
479
332
  resources: resources !== null && resources !== void 0 ? resources : {},
480
- pages: pages,
481
333
  env: resolvedEnv,
482
334
  signalProvider: signalProvider,
483
335
  governor: governor,
484
- storeProvider: storeProvider,
485
- currentUser: currentUser
336
+ currentUser: currentUser,
337
+ files: files,
338
+ pages: pages,
339
+ storeProvider: storeProvider
486
340
  }) : brain.run({
487
341
  initialState: initialState !== null && initialState !== void 0 ? initialState : {},
488
342
  options: options,
489
343
  client: client,
490
344
  brainRunId: brainRunId,
491
345
  resources: resources !== null && resources !== void 0 ? resources : {},
492
- pages: pages,
493
346
  env: resolvedEnv,
494
347
  signalProvider: signalProvider,
495
348
  governor: governor,
496
- storeProvider: storeProvider,
497
- currentUser: currentUser
349
+ currentUser: currentUser,
350
+ files: files,
351
+ pages: pages,
352
+ storeProvider: storeProvider
498
353
  });
499
354
  _state.label = 1;
500
355
  case 1:
@@ -125,8 +125,8 @@ var createInitialContext = function(opts) {
125
125
  pendingWebhooks: null,
126
126
  currentState: (_opts_initialState = opts === null || opts === void 0 ? void 0 : opts.initialState) !== null && _opts_initialState !== void 0 ? _opts_initialState : {},
127
127
  options: (_opts_options = opts === null || opts === void 0 ? void 0 : opts.options) !== null && _opts_options !== void 0 ? _opts_options : {},
128
- agentContext: null,
129
128
  iterateContext: null,
129
+ promptLoopContext: null,
130
130
  currentPage: null,
131
131
  status: STATUS.PENDING,
132
132
  isTopLevel: false,
@@ -136,9 +136,7 @@ var createInitialContext = function(opts) {
136
136
  isWaiting: false,
137
137
  isError: false,
138
138
  isCancelled: false,
139
- isInAgentLoop: false,
140
- topLevelStepCount: 0,
141
- totalTokens: 0
139
+ topLevelStepCount: 0
142
140
  };
143
141
  };
144
142
  // ============================================================================
@@ -146,7 +144,6 @@ var createInitialContext = function(opts) {
146
144
  // ============================================================================
147
145
  var updateDerivedState = function(ctx, executionState) {
148
146
  // Map ExecutionState to STATUS - this gives consumers the authoritative status
149
- // Note: agentLoop maps to RUNNING publicly (consumers don't need to know the difference)
150
147
  var status;
151
148
  switch(executionState){
152
149
  case 'idle':
@@ -155,9 +152,6 @@ var updateDerivedState = function(ctx, executionState) {
155
152
  case 'running':
156
153
  status = STATUS.RUNNING;
157
154
  break;
158
- case 'agentLoop':
159
- status = STATUS.RUNNING; // Publicly still "running"
160
- break;
161
155
  case 'paused':
162
156
  status = STATUS.PAUSED;
163
157
  break;
@@ -179,13 +173,12 @@ var updateDerivedState = function(ctx, executionState) {
179
173
  return _object_spread_props(_object_spread({}, ctx), {
180
174
  status: status,
181
175
  isTopLevel: ctx.depth === 1,
182
- isRunning: executionState === 'running' || executionState === 'agentLoop',
176
+ isRunning: executionState === 'running',
183
177
  isComplete: executionState === 'complete',
184
178
  isPaused: executionState === 'paused',
185
179
  isWaiting: executionState === 'waiting',
186
180
  isError: executionState === 'error',
187
- isCancelled: executionState === 'cancelled',
188
- isInAgentLoop: executionState === 'agentLoop'
181
+ isCancelled: executionState === 'cancelled'
189
182
  });
190
183
  };
191
184
  // ============================================================================
@@ -287,8 +280,7 @@ var completeInnerBrainError = reduce(function(ctx, param) {
287
280
  brainIdStack: brainIdStack.slice(0, -1),
288
281
  executionStack: executionStack.slice(0, -1),
289
282
  depth: depth - 1,
290
- error: error,
291
- agentContext: null
283
+ error: error
292
284
  });
293
285
  return updateDerivedState(newCtx, 'running');
294
286
  });
@@ -336,7 +328,7 @@ var startStep = reduce(function(ctx, param) {
336
328
  });
337
329
  var completeStep = reduce(function(ctx, param) {
338
330
  var stepId = param.stepId, stepTitle = param.stepTitle, patch = param.patch, halted = param.halted, pageContext = param.pageContext;
339
- var _ctx_iterateContext;
331
+ var _ctx_iterateContext, _ctx_promptLoopContext;
340
332
  var brains = ctx.brains, brainIdStack = ctx.brainIdStack, executionStack = ctx.executionStack, depth = ctx.depth, currentState = ctx.currentState, topLevelStepCount = ctx.topLevelStepCount;
341
333
  if (brainIdStack.length === 0) return ctx;
342
334
  // === NEW: Update flat structures ===
@@ -394,7 +386,9 @@ var completeStep = reduce(function(ctx, param) {
394
386
  // Only clear iterateContext when the iterate step itself completes,
395
387
  // not when inner brain steps complete during iteration
396
388
  var newIterateContext = ((_ctx_iterateContext = ctx.iterateContext) === null || _ctx_iterateContext === void 0 ? void 0 : _ctx_iterateContext.stepId) === stepId ? null : ctx.iterateContext;
397
- // Track page context: set when UI step completes (has pageContext),
389
+ // Clear promptLoopContext when the prompt step completes
390
+ var newPromptLoopContext = ((_ctx_promptLoopContext = ctx.promptLoopContext) === null || _ctx_promptLoopContext === void 0 ? void 0 : _ctx_promptLoopContext.stepId) === stepId ? null : ctx.promptLoopContext;
391
+ // Track page context: set when page step completes (has pageContext),
398
392
  // clear when the next step completes (page is ephemeral)
399
393
  var newCurrentPage = pageContext !== null && pageContext !== void 0 ? pageContext : null;
400
394
  return _object_spread_props(_object_spread({}, ctx), {
@@ -403,6 +397,7 @@ var completeStep = reduce(function(ctx, param) {
403
397
  currentState: newState1,
404
398
  topLevelStepCount: newStepCount,
405
399
  iterateContext: newIterateContext,
400
+ promptLoopContext: newPromptLoopContext,
406
401
  currentPage: newCurrentPage
407
402
  });
408
403
  });
@@ -419,9 +414,6 @@ var pauseBrain = reduce(function(ctx) {
419
414
  var resumeBrain = reduce(function(ctx) {
420
415
  return updateDerivedState(ctx, 'running');
421
416
  });
422
- var resumeToAgentLoop = reduce(function(ctx) {
423
- return updateDerivedState(ctx, 'agentLoop');
424
- });
425
417
  var webhookResponse = reduce(function(ctx) {
426
418
  var newCtx = _object_spread_props(_object_spread({}, ctx), {
427
419
  pendingWebhooks: null
@@ -460,12 +452,6 @@ var stepStatus = reduce(function(ctx, param) {
460
452
  brains: newBrains
461
453
  });
462
454
  });
463
- // passthrough is now a no-op - we just let the event pass through
464
- var passthrough = function() {
465
- return reduce(function(ctx) {
466
- return ctx;
467
- });
468
- };
469
455
  // Reducer for ITERATE_ITEM_COMPLETE - appends a single item result into iterateContext
470
456
  var iterateItemComplete = reduce(function(ctx, payload) {
471
457
  var existing = ctx.iterateContext;
@@ -480,72 +466,68 @@ var iterateItemComplete = reduce(function(ctx, payload) {
480
466
  accumulatedResults: newResults,
481
467
  processedCount: payload.processedCount,
482
468
  totalItems: payload.totalItems,
483
- schemaName: payload.schemaName
469
+ stateKey: payload.stateKey
484
470
  }
485
471
  });
486
472
  });
487
- // Reducer for agent iteration events that tracks tokens per-iteration
488
- // This ensures tokens are counted even if the agent doesn't complete (e.g., webhook interruption)
489
- var agentIteration = reduce(function(ctx, ev) {
490
- var totalTokens = ctx.totalTokens;
491
- var _ev_tokensThisIteration;
492
- return _object_spread_props(_object_spread({}, ctx), {
493
- totalTokens: totalTokens + ((_ev_tokensThisIteration = ev.tokensThisIteration) !== null && _ev_tokensThisIteration !== void 0 ? _ev_tokensThisIteration : 0)
494
- });
495
- });
496
- // Reducer for agent terminal events - clears agentContext since the agent has completed
497
- var agentTerminal = function() {
498
- return reduce(function(ctx) {
499
- return _object_spread_props(_object_spread({}, ctx), {
500
- agentContext: null
501
- });
502
- });
503
- };
504
- // Reducer for AGENT_START - initializes agentContext
505
- var agentStart = reduce(function(ctx, param) {
473
+ // Prompt loop reducers
474
+ // responseMessages and pendingToolCallId/Name are tracked here because on
475
+ // resume the DO replays persisted events through a fresh state machine to
476
+ // reconstruct context, then runner.resume() extracts promptLoopContext to
477
+ // pass into the new event stream's ResumeParams.
478
+ var promptStart = reduce(function(ctx, param) {
506
479
  var stepId = param.stepId, stepTitle = param.stepTitle, prompt = param.prompt, system = param.system;
507
- var newCtx = _object_spread_props(_object_spread({}, ctx), {
508
- agentContext: {
480
+ return _object_spread_props(_object_spread({}, ctx), {
481
+ promptLoopContext: {
509
482
  stepId: stepId,
510
483
  stepTitle: stepTitle,
511
484
  prompt: prompt,
512
485
  system: system,
513
486
  responseMessages: [],
514
487
  pendingToolCallId: null,
515
- pendingToolName: null
488
+ pendingToolName: null,
489
+ iteration: 0,
490
+ totalTokens: 0
516
491
  }
517
492
  });
518
- return updateDerivedState(newCtx, 'agentLoop');
519
493
  });
520
- // Reducer for AGENT_RAW_RESPONSE_MESSAGE - accumulates messages in agentContext
521
- var agentRawResponseMessage = reduce(function(ctx, param) {
494
+ var promptIteration = reduce(function(ctx, param) {
495
+ var iteration = param.iteration, totalTokens = param.totalTokens;
496
+ if (!ctx.promptLoopContext) return ctx;
497
+ return _object_spread_props(_object_spread({}, ctx), {
498
+ promptLoopContext: _object_spread_props(_object_spread({}, ctx.promptLoopContext), {
499
+ iteration: iteration,
500
+ totalTokens: totalTokens
501
+ })
502
+ });
503
+ });
504
+ var promptRawMessage = reduce(function(ctx, param) {
522
505
  var message = param.message;
523
- var agentContext = ctx.agentContext;
524
- // Accumulate the message in agentContext
525
- var updatedAgentContext = agentContext ? _object_spread_props(_object_spread({}, agentContext), {
526
- responseMessages: _to_consumable_array(agentContext.responseMessages).concat([
527
- message
528
- ])
529
- }) : null;
506
+ if (!ctx.promptLoopContext) return ctx;
507
+ // Replace, don't append — each emission carries the full conversation
508
+ // history from generateText (the SDK accumulates internally)
530
509
  return _object_spread_props(_object_spread({}, ctx), {
531
- agentContext: updatedAgentContext
510
+ promptLoopContext: _object_spread_props(_object_spread({}, ctx.promptLoopContext), {
511
+ responseMessages: message
512
+ })
532
513
  });
533
514
  });
534
- // Reducer for AGENT_WEBHOOK - records pending tool call in agentContext
535
- var agentWebhook = reduce(function(ctx, param) {
515
+ var promptWebhook = reduce(function(ctx, param) {
536
516
  var toolCallId = param.toolCallId, toolName = param.toolName;
537
- var agentContext = ctx.agentContext;
538
- // Update agentContext with pending tool info
539
- var updatedAgentContext = agentContext ? _object_spread_props(_object_spread({}, agentContext), {
540
- pendingToolCallId: toolCallId,
541
- pendingToolName: toolName
542
- }) : null;
517
+ if (!ctx.promptLoopContext) return ctx;
543
518
  return _object_spread_props(_object_spread({}, ctx), {
544
- agentContext: updatedAgentContext
519
+ promptLoopContext: _object_spread_props(_object_spread({}, ctx.promptLoopContext), {
520
+ pendingToolCallId: toolCallId,
521
+ pendingToolName: toolName
522
+ })
545
523
  });
546
524
  });
547
- // Reducer for AGENT_USER_MESSAGE - no-op, just stays in agentLoop
548
- var agentUserMessage = reduce(function(ctx) {
525
+ var promptComplete = reduce(function(ctx) {
526
+ return _object_spread_props(_object_spread({}, ctx), {
527
+ promptLoopContext: null
528
+ });
529
+ });
530
+ var passthrough = reduce(function(ctx) {
549
531
  return ctx;
550
532
  });
551
533
  // ============================================================================
@@ -557,25 +539,9 @@ var isOuterBrain = guard(function(ctx) {
557
539
  var isInnerBrain = guard(function(ctx) {
558
540
  return ctx.depth > 1;
559
541
  });
560
- // Guard to check if we have agentContext (for resuming to agentLoop)
561
- var hasAgentContext = guard(function(ctx) {
562
- return ctx.agentContext !== null;
563
- });
564
542
  // ============================================================================
565
543
  // State Machine Definition
566
544
  // ============================================================================
567
- // Define agent loop transitions as a reusable array for cleaner code
568
- var agentLoopTransitions = [
569
- // Agent micro-events that stay in agentLoop
570
- transition(BRAIN_EVENTS.AGENT_ITERATION, 'agentLoop', agentIteration),
571
- transition(BRAIN_EVENTS.AGENT_RAW_RESPONSE_MESSAGE, 'agentLoop', agentRawResponseMessage),
572
- transition(BRAIN_EVENTS.AGENT_TOOL_CALL, 'agentLoop', passthrough()),
573
- transition(BRAIN_EVENTS.AGENT_TOOL_RESULT, 'agentLoop', passthrough()),
574
- transition(BRAIN_EVENTS.AGENT_ASSISTANT_MESSAGE, 'agentLoop', passthrough()),
575
- transition(BRAIN_EVENTS.AGENT_USER_MESSAGE, 'agentLoop', agentUserMessage),
576
- // AGENT_WEBHOOK records pending tool call but stays in agentLoop
577
- transition(BRAIN_EVENTS.AGENT_WEBHOOK, 'agentLoop', agentWebhook)
578
- ];
579
545
  // Internal machine factory - called with pre-built context
580
546
  var makeBrainMachine = function(initialContext) {
581
547
  return createMachine('idle', {
@@ -588,41 +554,21 @@ var makeBrainMachine = function(initialContext) {
588
554
  transition(BRAIN_EVENTS.ERROR, 'error', isOuterBrain, errorBrain), // Inner brain error -> stay running (pop the inner brain off the stack)
589
555
  transition(BRAIN_EVENTS.ERROR, 'running', isInnerBrain, completeInnerBrainError), // Cancelled
590
556
  transition(BRAIN_EVENTS.CANCELLED, 'cancelled', cancelBrain), // Paused (by signal)
591
- transition(BRAIN_EVENTS.PAUSED, 'paused', pauseBrain), // Webhook -> waiting (for non-agent webhooks)
592
- transition(BRAIN_EVENTS.WEBHOOK, 'waiting', webhookPause), // Webhook response (for resume from non-agent webhook)
557
+ transition(BRAIN_EVENTS.PAUSED, 'paused', pauseBrain), // Webhook -> waiting
558
+ transition(BRAIN_EVENTS.WEBHOOK, 'waiting', webhookPause), // Webhook response
593
559
  transition(BRAIN_EVENTS.WEBHOOK_RESPONSE, 'running', webhookResponse), // Step events
594
560
  transition(BRAIN_EVENTS.STEP_START, 'running', startStep), transition(BRAIN_EVENTS.STEP_COMPLETE, 'running', completeStep), transition(BRAIN_EVENTS.STEP_STATUS, 'running', stepStatus), // Iterate item complete - stays in running, accumulates results
595
- transition(BRAIN_EVENTS.ITERATE_ITEM_COMPLETE, 'running', iterateItemComplete), // AGENT_START transitions to the agentLoop state
596
- transition(BRAIN_EVENTS.AGENT_START, 'agentLoop', agentStart)),
597
- // Explicit agent loop state - isolates agent execution logic
598
- agentLoop: state.apply(void 0, // Spread agent micro-transitions
599
- _to_consumable_array(agentLoopTransitions).concat([
600
- // Exit strategies - agent terminal events return to running
601
- transition(BRAIN_EVENTS.AGENT_COMPLETE, 'running', agentTerminal()),
602
- transition(BRAIN_EVENTS.AGENT_TOKEN_LIMIT, 'running', agentTerminal()),
603
- transition(BRAIN_EVENTS.AGENT_ITERATION_LIMIT, 'running', agentTerminal()),
604
- // Interruption handling - can pause or wait from agentLoop
605
- transition(BRAIN_EVENTS.PAUSED, 'paused', pauseBrain),
606
- transition(BRAIN_EVENTS.WEBHOOK, 'waiting', webhookPause),
607
- // Error handling
608
- transition(BRAIN_EVENTS.ERROR, 'error', isOuterBrain, errorBrain),
609
- // Inner brain error -> back to running (pop inner brain, clear agentContext)
610
- transition(BRAIN_EVENTS.ERROR, 'running', isInnerBrain, completeInnerBrainError),
611
- transition(BRAIN_EVENTS.CANCELLED, 'cancelled', cancelBrain)
612
- ])),
561
+ transition(BRAIN_EVENTS.ITERATE_ITEM_COMPLETE, 'running', iterateItemComplete), // Prompt loop events - stay in running, update promptLoopContext
562
+ transition(BRAIN_EVENTS.PROMPT_START, 'running', promptStart), transition(BRAIN_EVENTS.PROMPT_ITERATION, 'running', promptIteration), transition(BRAIN_EVENTS.PROMPT_TOOL_CALL, 'running', passthrough), transition(BRAIN_EVENTS.PROMPT_TOOL_RESULT, 'running', passthrough), transition(BRAIN_EVENTS.PROMPT_ASSISTANT_MESSAGE, 'running', passthrough), transition(BRAIN_EVENTS.PROMPT_COMPLETE, 'running', promptComplete), transition(BRAIN_EVENTS.PROMPT_TOKEN_LIMIT, 'running', promptComplete), transition(BRAIN_EVENTS.PROMPT_ITERATION_LIMIT, 'running', promptComplete), transition(BRAIN_EVENTS.PROMPT_RAW_RESPONSE_MESSAGE, 'running', promptRawMessage), transition(BRAIN_EVENTS.PROMPT_WEBHOOK, 'running', promptWebhook)),
613
563
  paused: state(transition(BRAIN_EVENTS.CANCELLED, 'cancelled', cancelBrain), // RESUMED transitions out of paused state without creating a new brain
614
- // If we have agentContext, resume to agentLoop; otherwise to running
615
- transition(BRAIN_EVENTS.RESUMED, 'agentLoop', hasAgentContext, resumeToAgentLoop), transition(BRAIN_EVENTS.RESUMED, 'running', resumeBrain), // START is kept for backwards compatibility but RESUMED is preferred
616
- transition(BRAIN_EVENTS.START, 'agentLoop', hasAgentContext, startBrain), transition(BRAIN_EVENTS.START, 'running', startBrain)),
564
+ transition(BRAIN_EVENTS.RESUMED, 'running', resumeBrain), // START is kept for backwards compatibility but RESUMED is preferred
565
+ transition(BRAIN_EVENTS.START, 'running', startBrain)),
617
566
  waiting: state(// TODO: Could add PAUSED transition here to allow pausing a waiting brain.
618
567
  // This would require queueing webhook responses (similar to USER_MESSAGE signals)
619
568
  // so they can be processed when the brain is resumed.
620
- // Webhook response - if we have agentContext, go back to agentLoop
621
- transition(BRAIN_EVENTS.WEBHOOK_RESPONSE, 'agentLoop', hasAgentContext, webhookResponse), // Otherwise go to running
622
569
  transition(BRAIN_EVENTS.WEBHOOK_RESPONSE, 'running', webhookResponse), transition(BRAIN_EVENTS.CANCELLED, 'cancelled', cancelBrain), // RESUMED transitions out of waiting (e.g., timeout-triggered wakeUp with no webhook response)
623
570
  transition(BRAIN_EVENTS.RESUMED, 'running', resumeBrain), // START can resume from waiting (after webhook response is processed)
624
- // If we have agentContext, resume to agentLoop; otherwise to running
625
- transition(BRAIN_EVENTS.START, 'agentLoop', hasAgentContext, startBrain), transition(BRAIN_EVENTS.START, 'running', startBrain)),
571
+ transition(BRAIN_EVENTS.START, 'running', startBrain)),
626
572
  // Terminal states - limited outgoing transitions
627
573
  complete: state(),
628
574
  error: state(// Allow STEP_STATUS after error so we can emit the final step statuses
@@ -1,5 +1,6 @@
1
1
  // Re-export from new modular structure for backwards compatibility
2
2
  // Builder
3
3
  export { Brain, brain } from './builder/brain.js';
4
+ export { Continuation } from './builder/continuation.js';
4
5
  // Execution - Constants
5
6
  export { DEFAULT_ENV } from './execution/constants.js';