@mastra/core 0.10.13 → 0.10.15-alpha.0

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 (235) hide show
  1. package/a2a.d.ts +1 -0
  2. package/agent.d.ts +1 -0
  3. package/base.d.ts +1 -0
  4. package/bundler.d.ts +1 -0
  5. package/deployer.d.ts +1 -0
  6. package/di.d.ts +1 -0
  7. package/dist/a2a/index.cjs +79 -0
  8. package/dist/a2a/index.d.cts +780 -0
  9. package/dist/a2a/index.d.ts +780 -0
  10. package/dist/a2a/index.js +68 -0
  11. package/dist/agent/index.cjs +15 -0
  12. package/dist/agent/index.d.cts +29 -0
  13. package/dist/agent/index.d.ts +29 -0
  14. package/dist/agent/index.js +2 -0
  15. package/dist/base-B_y9sMg0.d.cts +162 -0
  16. package/dist/base-CTj7ESwt.d.cts +4132 -0
  17. package/dist/base-ClrXcCRx.d.ts +162 -0
  18. package/dist/base-qVqAnB-c.d.ts +4132 -0
  19. package/dist/base.cjs +10 -0
  20. package/dist/base.d.cts +6 -0
  21. package/dist/base.d.ts +6 -0
  22. package/dist/base.js +1 -0
  23. package/dist/bundler/index.cjs +10 -0
  24. package/dist/bundler/index.d.cts +30 -0
  25. package/dist/bundler/index.d.ts +30 -0
  26. package/dist/bundler/index.js +1 -0
  27. package/dist/chunk-32C7JDIZ.js +1 -0
  28. package/dist/chunk-4UWPFBC6.js +88 -0
  29. package/dist/chunk-4Z3OU5RY.cjs +31 -0
  30. package/dist/chunk-5HTMDAXP.js +359 -0
  31. package/dist/chunk-5IEKR756.js +53 -0
  32. package/dist/chunk-5YDTZN2X.js +114 -0
  33. package/dist/chunk-6UNGH46J.js +75 -0
  34. package/dist/chunk-6Y4UL5Z6.cjs +94 -0
  35. package/dist/chunk-7H2GET5Z.cjs +668 -0
  36. package/dist/chunk-7HZ6NIAF.cjs +2 -0
  37. package/dist/chunk-7XQIPES3.js +668 -0
  38. package/dist/chunk-AKYTYALY.js +70 -0
  39. package/dist/chunk-AOWJUV2N.js +2415 -0
  40. package/dist/chunk-ATXBSEFT.js +22 -0
  41. package/dist/chunk-B6TOBUS6.cjs +80 -0
  42. package/dist/chunk-B7SQOKEC.cjs +91 -0
  43. package/dist/chunk-BB4KXGBU.js +83 -0
  44. package/dist/chunk-BB6DPGIV.cjs +6 -0
  45. package/dist/chunk-BVD7NVAR.cjs +244 -0
  46. package/dist/chunk-C4LMN2IR.js +27 -0
  47. package/dist/chunk-DR4JS662.js +989 -0
  48. package/dist/chunk-F2WMR75C.cjs +183 -0
  49. package/dist/chunk-FEYYOBBG.cjs +24 -0
  50. package/dist/chunk-FL5SZ2XU.js +181 -0
  51. package/dist/chunk-GH2KM66J.js +37 -0
  52. package/dist/chunk-GWFS5DAR.cjs +37 -0
  53. package/dist/chunk-HNEE7IF4.js +60 -0
  54. package/dist/chunk-HSVOEWAM.cjs +2 -0
  55. package/dist/chunk-IBKM5CLQ.js +428 -0
  56. package/dist/chunk-ID5LG5CQ.cjs +659 -0
  57. package/dist/chunk-J52TXHZV.cjs +73 -0
  58. package/dist/chunk-J62R4M7K.js +240 -0
  59. package/dist/chunk-JNMQKJH4.js +10 -0
  60. package/dist/chunk-JQOMTERC.js +89 -0
  61. package/dist/chunk-LABUWBKX.cjs +71 -0
  62. package/dist/chunk-LBUQ6YNU.cjs +447 -0
  63. package/dist/chunk-LXFZUKP3.cjs +34 -0
  64. package/dist/chunk-MP2QBLUJ.cjs +70 -0
  65. package/dist/chunk-MUNFCOMB.cjs +62 -0
  66. package/dist/chunk-MVCHTRVB.js +5038 -0
  67. package/dist/chunk-NH5WJNNS.js +1 -0
  68. package/dist/chunk-P3Q73CAW.cjs +55 -0
  69. package/dist/chunk-Q33INUG2.cjs +81 -0
  70. package/dist/chunk-QFTBW7ZZ.cjs +2 -0
  71. package/dist/chunk-QQ5K5TZE.cjs +619 -0
  72. package/dist/chunk-R4V75T7J.js +1 -0
  73. package/dist/chunk-RVFWMGGR.js +77 -0
  74. package/dist/chunk-SGGPJWRQ.js +69 -0
  75. package/dist/chunk-ST5RMVLG.cjs +87 -0
  76. package/dist/chunk-TC2SCOTE.js +605 -0
  77. package/dist/chunk-TTMYHBQM.js +657 -0
  78. package/dist/chunk-U64IJDC5.cjs +109 -0
  79. package/dist/chunk-ULZ6MRTN.cjs +5065 -0
  80. package/dist/chunk-V5D2LIF5.js +68 -0
  81. package/dist/chunk-WQNOATKB.js +103 -0
  82. package/dist/chunk-Y7D2JLKS.js +4 -0
  83. package/dist/chunk-YOQP5T77.js +32 -0
  84. package/dist/chunk-ZCU3PLIL.cjs +2429 -0
  85. package/dist/chunk-ZIZ3CVHN.cjs +120 -0
  86. package/dist/chunk-ZPOUMTTH.cjs +362 -0
  87. package/dist/chunk-ZTPPDHQK.cjs +991 -0
  88. package/dist/chunk-ZZLBNB3U.cjs +12 -0
  89. package/dist/deployer/index.cjs +10 -0
  90. package/dist/deployer/index.d.cts +19 -0
  91. package/dist/deployer/index.d.ts +19 -0
  92. package/dist/deployer/index.js +1 -0
  93. package/dist/di/index.cjs +10 -0
  94. package/dist/di/index.d.cts +1 -0
  95. package/dist/di/index.d.ts +1 -0
  96. package/dist/di/index.js +1 -0
  97. package/dist/error/index.cjs +22 -0
  98. package/dist/error/index.d.cts +86 -0
  99. package/dist/error/index.d.ts +86 -0
  100. package/dist/error/index.js +1 -0
  101. package/dist/eval/index.cjs +14 -0
  102. package/dist/eval/index.d.cts +43 -0
  103. package/dist/eval/index.d.ts +43 -0
  104. package/dist/eval/index.js +1 -0
  105. package/dist/hooks/index.cjs +18 -0
  106. package/dist/hooks/index.d.cts +33 -0
  107. package/dist/hooks/index.d.ts +33 -0
  108. package/dist/hooks/index.js +1 -0
  109. package/dist/index.cjs +285 -0
  110. package/dist/index.d.cts +92 -0
  111. package/dist/index.d.ts +92 -0
  112. package/dist/index.js +112 -0
  113. package/dist/integration/index.cjs +14 -0
  114. package/dist/integration/index.d.cts +65 -0
  115. package/dist/integration/index.d.ts +65 -0
  116. package/dist/integration/index.js +1 -0
  117. package/dist/llm/index.cjs +10 -0
  118. package/dist/llm/index.d.cts +29 -0
  119. package/dist/llm/index.d.ts +29 -0
  120. package/dist/llm/index.js +1 -0
  121. package/dist/logger/index.cjs +43 -0
  122. package/dist/logger/index.d.cts +96 -0
  123. package/dist/logger/index.d.ts +96 -0
  124. package/dist/logger/index.js +2 -0
  125. package/dist/logger-B8XXh6ya.d.cts +159 -0
  126. package/dist/logger-Bpa2oLL4.d.ts +159 -0
  127. package/dist/mastra/index.cjs +10 -0
  128. package/dist/mastra/index.d.cts +29 -0
  129. package/dist/mastra/index.d.ts +29 -0
  130. package/dist/mastra/index.js +1 -0
  131. package/dist/mcp/index.cjs +106 -0
  132. package/dist/mcp/index.d.cts +29 -0
  133. package/dist/mcp/index.d.ts +29 -0
  134. package/dist/mcp/index.js +100 -0
  135. package/dist/memory/index.cjs +18 -0
  136. package/dist/memory/index.d.cts +29 -0
  137. package/dist/memory/index.d.ts +29 -0
  138. package/dist/memory/index.js +1 -0
  139. package/dist/network/index.cjs +311 -0
  140. package/dist/network/index.d.cts +29 -0
  141. package/dist/network/index.d.ts +29 -0
  142. package/dist/network/index.js +309 -0
  143. package/dist/network/vNext/index.cjs +880 -0
  144. package/dist/network/vNext/index.d.cts +29 -0
  145. package/dist/network/vNext/index.d.ts +29 -0
  146. package/dist/network/vNext/index.js +878 -0
  147. package/dist/relevance/index.cjs +18 -0
  148. package/dist/relevance/index.d.cts +50 -0
  149. package/dist/relevance/index.d.ts +50 -0
  150. package/dist/relevance/index.js +1 -0
  151. package/dist/runtime-context/index.cjs +10 -0
  152. package/dist/runtime-context/index.d.cts +52 -0
  153. package/dist/runtime-context/index.d.ts +52 -0
  154. package/dist/runtime-context/index.js +1 -0
  155. package/dist/server/index.cjs +62 -0
  156. package/dist/server/index.d.cts +52 -0
  157. package/dist/server/index.d.ts +52 -0
  158. package/dist/server/index.js +59 -0
  159. package/dist/storage/index.cjs +336 -0
  160. package/dist/storage/index.d.cts +149 -0
  161. package/dist/storage/index.d.ts +149 -0
  162. package/dist/storage/index.js +303 -0
  163. package/dist/telemetry/index.cjs +30 -0
  164. package/dist/telemetry/index.d.cts +75 -0
  165. package/dist/telemetry/index.d.ts +75 -0
  166. package/dist/telemetry/index.js +1 -0
  167. package/dist/telemetry/otel-vendor.cjs +103 -0
  168. package/dist/telemetry/otel-vendor.d.cts +20 -0
  169. package/dist/telemetry/otel-vendor.d.ts +20 -0
  170. package/dist/telemetry/otel-vendor.js +57 -0
  171. package/dist/tools/index.cjs +18 -0
  172. package/dist/tools/index.d.cts +41 -0
  173. package/dist/tools/index.d.ts +41 -0
  174. package/dist/tools/index.js +1 -0
  175. package/dist/tts/index.cjs +10 -0
  176. package/dist/tts/index.d.cts +28 -0
  177. package/dist/tts/index.d.ts +28 -0
  178. package/dist/tts/index.js +1 -0
  179. package/dist/types-Bo1uigWx.d.cts +17 -0
  180. package/dist/types-Bo1uigWx.d.ts +17 -0
  181. package/dist/utils.cjs +62 -0
  182. package/dist/utils.d.cts +150 -0
  183. package/dist/utils.d.ts +150 -0
  184. package/dist/utils.js +1 -0
  185. package/dist/vector/filter/index.cjs +192 -0
  186. package/dist/vector/filter/index.d.cts +128 -0
  187. package/dist/vector/filter/index.d.ts +128 -0
  188. package/dist/vector/filter/index.js +190 -0
  189. package/dist/vector/index.cjs +10 -0
  190. package/dist/vector/index.d.cts +77 -0
  191. package/dist/vector/index.d.ts +77 -0
  192. package/dist/vector/index.js +1 -0
  193. package/dist/voice/index.cjs +18 -0
  194. package/dist/voice/index.d.cts +29 -0
  195. package/dist/voice/index.d.ts +29 -0
  196. package/dist/voice/index.js +1 -0
  197. package/dist/workflows/constants.cjs +10 -0
  198. package/dist/workflows/constants.d.cts +3 -0
  199. package/dist/workflows/constants.d.ts +3 -0
  200. package/dist/workflows/constants.js +1 -0
  201. package/dist/workflows/index.cjs +42 -0
  202. package/dist/workflows/index.d.cts +285 -0
  203. package/dist/workflows/index.d.ts +285 -0
  204. package/dist/workflows/index.js +1 -0
  205. package/dist/workflows/legacy/index.cjs +90 -0
  206. package/dist/workflows/legacy/index.d.cts +91 -0
  207. package/dist/workflows/legacy/index.d.ts +91 -0
  208. package/dist/workflows/legacy/index.js +1 -0
  209. package/error.d.ts +1 -0
  210. package/eval.d.ts +1 -0
  211. package/hooks.d.ts +1 -0
  212. package/integration.d.ts +1 -0
  213. package/llm.d.ts +1 -0
  214. package/logger.d.ts +1 -0
  215. package/mastra.d.ts +1 -0
  216. package/mcp.d.ts +1 -0
  217. package/memory.d.ts +1 -0
  218. package/network/vNext.d.ts +1 -0
  219. package/network.d.ts +1 -0
  220. package/package.json +2 -3
  221. package/relevance.d.ts +1 -0
  222. package/runtime-context.d.ts +1 -0
  223. package/server.d.ts +1 -0
  224. package/storage.d.ts +1 -0
  225. package/telemetry/otel-vendor.d.ts +1 -0
  226. package/telemetry.d.ts +1 -0
  227. package/tools.d.ts +1 -0
  228. package/tts.d.ts +1 -0
  229. package/utils.d.ts +1 -0
  230. package/vector/filter.d.ts +1 -0
  231. package/vector.d.ts +1 -0
  232. package/voice.d.ts +1 -0
  233. package/workflows/_constants.d.ts +1 -0
  234. package/workflows/legacy.d.ts +1 -0
  235. package/workflows.d.ts +1 -0
@@ -0,0 +1,5065 @@
1
+ 'use strict';
2
+
3
+ var chunkZPOUMTTH_cjs = require('./chunk-ZPOUMTTH.cjs');
4
+ var chunkZTPPDHQK_cjs = require('./chunk-ZTPPDHQK.cjs');
5
+ var chunkST5RMVLG_cjs = require('./chunk-ST5RMVLG.cjs');
6
+ var chunkID5LG5CQ_cjs = require('./chunk-ID5LG5CQ.cjs');
7
+ var chunkQQ5K5TZE_cjs = require('./chunk-QQ5K5TZE.cjs');
8
+ var chunkLBUQ6YNU_cjs = require('./chunk-LBUQ6YNU.cjs');
9
+ var chunkB6TOBUS6_cjs = require('./chunk-B6TOBUS6.cjs');
10
+ var chunkP3Q73CAW_cjs = require('./chunk-P3Q73CAW.cjs');
11
+ var chunkZIZ3CVHN_cjs = require('./chunk-ZIZ3CVHN.cjs');
12
+ var chunkLABUWBKX_cjs = require('./chunk-LABUWBKX.cjs');
13
+ var chunkU64IJDC5_cjs = require('./chunk-U64IJDC5.cjs');
14
+ var api = require('@opentelemetry/api');
15
+ var zod = require('zod');
16
+ var radash = require('radash');
17
+ var crypto$1 = require('crypto');
18
+ var EventEmitter = require('events');
19
+ var sift = require('sift');
20
+ var xstate = require('xstate');
21
+
22
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
23
+
24
+ var EventEmitter__default = /*#__PURE__*/_interopDefault(EventEmitter);
25
+ var sift__default = /*#__PURE__*/_interopDefault(sift);
26
+
27
+ // ../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js
28
+ var require_fast_deep_equal = chunkU64IJDC5_cjs.__commonJS({
29
+ "../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js"(exports, module) {
30
+
31
+ module.exports = function equal(a, b) {
32
+ if (a === b) return true;
33
+ if (a && b && typeof a == "object" && typeof b == "object") {
34
+ if (a.constructor !== b.constructor) return false;
35
+ var length, i, keys;
36
+ if (Array.isArray(a)) {
37
+ length = a.length;
38
+ if (length != b.length) return false;
39
+ for (i = length; i-- !== 0;) if (!equal(a[i], b[i])) return false;
40
+ return true;
41
+ }
42
+ if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
43
+ if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
44
+ if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
45
+ keys = Object.keys(a);
46
+ length = keys.length;
47
+ if (length !== Object.keys(b).length) return false;
48
+ for (i = length; i-- !== 0;) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
49
+ for (i = length; i-- !== 0;) {
50
+ var key = keys[i];
51
+ if (!equal(a[key], b[key])) return false;
52
+ }
53
+ return true;
54
+ }
55
+ return a !== a && b !== b;
56
+ };
57
+ }
58
+ });
59
+
60
+ // src/workflows/legacy/step.ts
61
+ var LegacyStep = class {
62
+ id;
63
+ description;
64
+ inputSchema;
65
+ outputSchema;
66
+ payload;
67
+ execute;
68
+ retryConfig;
69
+ mastra;
70
+ constructor({
71
+ id,
72
+ description,
73
+ execute,
74
+ payload,
75
+ outputSchema,
76
+ inputSchema,
77
+ retryConfig
78
+ }) {
79
+ this.id = id;
80
+ this.description = description ?? "";
81
+ this.inputSchema = inputSchema;
82
+ this.payload = payload;
83
+ this.outputSchema = outputSchema;
84
+ this.execute = execute;
85
+ this.retryConfig = retryConfig;
86
+ }
87
+ };
88
+
89
+ // src/workflows/legacy/types.ts
90
+ var WhenConditionReturnValue = /* @__PURE__ */(WhenConditionReturnValue2 => {
91
+ WhenConditionReturnValue2["CONTINUE"] = "continue";
92
+ WhenConditionReturnValue2["CONTINUE_FAILED"] = "continue_failed";
93
+ WhenConditionReturnValue2["ABORT"] = "abort";
94
+ WhenConditionReturnValue2["LIMBO"] = "limbo";
95
+ return WhenConditionReturnValue2;
96
+ })(WhenConditionReturnValue || {});
97
+
98
+ // src/agent/index.ts
99
+ var import_fast_deep_equal = chunkU64IJDC5_cjs.__toESM(require_fast_deep_equal(), 1);
100
+
101
+ // src/agent/save-queue/index.ts
102
+ var SaveQueueManager = class _SaveQueueManager {
103
+ logger;
104
+ debounceMs;
105
+ memory;
106
+ static MAX_STALENESS_MS = 1e3;
107
+ constructor({
108
+ logger,
109
+ debounceMs,
110
+ memory
111
+ }) {
112
+ this.logger = logger;
113
+ this.debounceMs = debounceMs || 100;
114
+ this.memory = memory;
115
+ }
116
+ saveQueues = /* @__PURE__ */new Map();
117
+ saveDebounceTimers = /* @__PURE__ */new Map();
118
+ /**
119
+ * Debounces save operations for a thread, ensuring that consecutive save requests
120
+ * are batched and only the latest is executed after a short delay.
121
+ * @param threadId - The ID of the thread to debounce saves for.
122
+ * @param saveFn - The save function to debounce.
123
+ */
124
+ debounceSave(threadId, messageList, memoryConfig) {
125
+ if (this.saveDebounceTimers.has(threadId)) {
126
+ clearTimeout(this.saveDebounceTimers.get(threadId));
127
+ }
128
+ this.saveDebounceTimers.set(threadId, setTimeout(() => {
129
+ this.enqueueSave(threadId, messageList, memoryConfig).catch(err => {
130
+ this.logger?.error?.("Error in debounceSave", {
131
+ err,
132
+ threadId
133
+ });
134
+ });
135
+ this.saveDebounceTimers.delete(threadId);
136
+ }, this.debounceMs));
137
+ }
138
+ /**
139
+ * Enqueues a save operation for a thread, ensuring that saves are executed in order and
140
+ * only one save runs at a time per thread. If a save is already in progress for the thread,
141
+ * the new save is queued to run after the previous completes.
142
+ *
143
+ * @param threadId - The ID of the thread whose messages should be saved.
144
+ * @param messageList - The MessageList instance containing unsaved messages.
145
+ * @param memoryConfig - Optional memory configuration to use for saving.
146
+ */
147
+ enqueueSave(threadId, messageList, memoryConfig) {
148
+ const prev = this.saveQueues.get(threadId) || Promise.resolve();
149
+ const next = prev.then(() => this.persistUnsavedMessages(messageList, memoryConfig)).catch(err => {
150
+ this.logger?.error?.("Error in enqueueSave", {
151
+ err,
152
+ threadId
153
+ });
154
+ }).then(() => {
155
+ if (this.saveQueues.get(threadId) === next) {
156
+ this.saveQueues.delete(threadId);
157
+ }
158
+ });
159
+ this.saveQueues.set(threadId, next);
160
+ return next;
161
+ }
162
+ /**
163
+ * Clears any pending debounced save for a thread, preventing the scheduled save
164
+ * from executing if it hasn't already fired.
165
+ *
166
+ * @param threadId - The ID of the thread whose debounced save should be cleared.
167
+ */
168
+ clearDebounce(threadId) {
169
+ if (this.saveDebounceTimers.has(threadId)) {
170
+ clearTimeout(this.saveDebounceTimers.get(threadId));
171
+ this.saveDebounceTimers.delete(threadId);
172
+ }
173
+ }
174
+ /**
175
+ * Persists any unsaved messages from the MessageList to memory storage.
176
+ * Drains the list of unsaved messages and writes them using the memory backend.
177
+ * @param messageList - The MessageList instance for the current thread.
178
+ * @param memoryConfig - The memory configuration for saving.
179
+ */
180
+ async persistUnsavedMessages(messageList, memoryConfig) {
181
+ const newMessages = messageList.drainUnsavedMessages();
182
+ if (newMessages.length > 0 && this.memory) {
183
+ await this.memory.saveMessages({
184
+ messages: newMessages,
185
+ memoryConfig
186
+ });
187
+ }
188
+ }
189
+ /**
190
+ * Batches a save of unsaved messages for a thread, using debouncing to batch rapid updates.
191
+ * If the oldest unsaved message is stale (older than MAX_STALENESS_MS), the save is performed immediately.
192
+ * Otherwise, the save is delayed to batch multiple updates and reduce redundant writes.
193
+ *
194
+ * @param messageList - The MessageList instance containing unsaved messages.
195
+ * @param threadId - The ID of the thread whose messages are being saved.
196
+ * @param memoryConfig - Optional memory configuration for saving.
197
+ */
198
+ async batchMessages(messageList, threadId, memoryConfig) {
199
+ if (!threadId) return;
200
+ const earliest = messageList.getEarliestUnsavedMessageTimestamp();
201
+ const now = Date.now();
202
+ if (earliest && now - earliest > _SaveQueueManager.MAX_STALENESS_MS) {
203
+ return this.flushMessages(messageList, threadId, memoryConfig);
204
+ } else {
205
+ return this.debounceSave(threadId, messageList, memoryConfig);
206
+ }
207
+ }
208
+ /**
209
+ * Forces an immediate save of unsaved messages for a thread, bypassing any debounce delay.
210
+ * This is used when a flush to persistent storage is required (e.g., on shutdown or critical transitions).
211
+ *
212
+ * @param messageList - The MessageList instance containing unsaved messages.
213
+ * @param threadId - The ID of the thread whose messages are being saved.
214
+ * @param memoryConfig - Optional memory configuration for saving.
215
+ */
216
+ async flushMessages(messageList, threadId, memoryConfig) {
217
+ if (!threadId) return;
218
+ this.clearDebounce(threadId);
219
+ return this.enqueueSave(threadId, messageList, memoryConfig);
220
+ }
221
+ };
222
+
223
+ // src/agent/index.ts
224
+ function resolveMaybePromise(value, cb) {
225
+ if (value instanceof Promise) {
226
+ return value.then(cb);
227
+ }
228
+ return cb(value);
229
+ }
230
+ function resolveThreadIdFromArgs(args) {
231
+ if (args?.memory?.thread) {
232
+ if (typeof args.memory.thread === "string") return {
233
+ id: args.memory.thread
234
+ };
235
+ if (typeof args.memory.thread === "object" && args.memory.thread.id) return args.memory.thread;
236
+ }
237
+ if (args?.threadId) return {
238
+ id: args.threadId
239
+ };
240
+ return void 0;
241
+ }
242
+ var _Agent_decorators, _init, _a;
243
+ _Agent_decorators = [chunkQQ5K5TZE_cjs.InstrumentClass({
244
+ prefix: "agent",
245
+ excludeMethods: ["hasOwnMemory", "getMemory", "__primitive", "__registerMastra", "__registerPrimitives", "__setTools", "__setLogger", "__setTelemetry", "log", "getModel", "getInstructions", "getTools", "getLLM", "getWorkflows", "getDefaultGenerateOptions", "getDefaultStreamOptions", "getDescription"]
246
+ })];
247
+ exports.Agent = class Agent extends (_a = chunkP3Q73CAW_cjs.MastraBase) {
248
+ id;
249
+ name;
250
+ #instructions;
251
+ #description;
252
+ model;
253
+ #mastra;
254
+ #memory;
255
+ #workflows;
256
+ #defaultGenerateOptions;
257
+ #defaultStreamOptions;
258
+ #tools;
259
+ /** @deprecated This property is deprecated. Use evals instead. */
260
+ metrics;
261
+ evals;
262
+ #voice;
263
+ constructor(config) {
264
+ super({
265
+ component: chunkZIZ3CVHN_cjs.RegisteredLogger.AGENT
266
+ });
267
+ this.name = config.name;
268
+ this.id = config.name;
269
+ this.#instructions = config.instructions;
270
+ this.#description = config.description;
271
+ if (!config.model) {
272
+ const mastraError = new chunkB6TOBUS6_cjs.MastraError({
273
+ id: "AGENT_CONSTRUCTOR_MODEL_REQUIRED",
274
+ domain: "AGENT" /* AGENT */,
275
+ category: "USER" /* USER */,
276
+ details: {
277
+ agentName: config.name
278
+ },
279
+ text: `LanguageModel is required to create an Agent. Please provide the 'model'.`
280
+ });
281
+ this.logger.trackException(mastraError);
282
+ this.logger.error(mastraError.toString());
283
+ throw mastraError;
284
+ }
285
+ this.model = config.model;
286
+ if (config.workflows) {
287
+ this.#workflows = config.workflows;
288
+ }
289
+ this.#defaultGenerateOptions = config.defaultGenerateOptions || {};
290
+ this.#defaultStreamOptions = config.defaultStreamOptions || {};
291
+ this.#tools = config.tools || {};
292
+ this.metrics = {};
293
+ this.evals = {};
294
+ if (config.mastra) {
295
+ this.__registerMastra(config.mastra);
296
+ this.__registerPrimitives({
297
+ telemetry: config.mastra.getTelemetry(),
298
+ logger: config.mastra.getLogger()
299
+ });
300
+ }
301
+ if (config.metrics) {
302
+ this.logger.warn("The metrics property is deprecated. Please use evals instead to add evaluation metrics.");
303
+ this.metrics = config.metrics;
304
+ this.evals = config.metrics;
305
+ }
306
+ if (config.evals) {
307
+ this.evals = config.evals;
308
+ }
309
+ if (config.memory) {
310
+ this.#memory = config.memory;
311
+ }
312
+ if (config.voice) {
313
+ this.#voice = config.voice;
314
+ if (typeof config.tools !== "function") {
315
+ this.#voice?.addTools(this.tools);
316
+ }
317
+ if (typeof config.instructions === "string") {
318
+ this.#voice?.addInstructions(config.instructions);
319
+ }
320
+ } else {
321
+ this.#voice = new chunkZPOUMTTH_cjs.DefaultVoice();
322
+ }
323
+ }
324
+ hasOwnMemory() {
325
+ return Boolean(this.#memory);
326
+ }
327
+ getMemory() {
328
+ const memory = this.#memory;
329
+ if (memory && !memory.hasOwnStorage && this.#mastra) {
330
+ const storage = this.#mastra.getStorage();
331
+ if (storage) {
332
+ memory.setStorage(storage);
333
+ }
334
+ }
335
+ return memory;
336
+ }
337
+ get voice() {
338
+ if (typeof this.#instructions === "function") {
339
+ const mastraError = new chunkB6TOBUS6_cjs.MastraError({
340
+ id: "AGENT_VOICE_INCOMPATIBLE_WITH_FUNCTION_INSTRUCTIONS",
341
+ domain: "AGENT" /* AGENT */,
342
+ category: "USER" /* USER */,
343
+ details: {
344
+ agentName: this.name
345
+ },
346
+ text: "Voice is not compatible when instructions are a function. Please use getVoice() instead."
347
+ });
348
+ this.logger.trackException(mastraError);
349
+ this.logger.error(mastraError.toString());
350
+ throw mastraError;
351
+ }
352
+ return this.#voice;
353
+ }
354
+ async getWorkflows({
355
+ runtimeContext = new chunkLABUWBKX_cjs.RuntimeContext()
356
+ } = {}) {
357
+ let workflowRecord;
358
+ if (typeof this.#workflows === "function") {
359
+ workflowRecord = await Promise.resolve(this.#workflows({
360
+ runtimeContext
361
+ }));
362
+ } else {
363
+ workflowRecord = this.#workflows ?? {};
364
+ }
365
+ Object.entries(workflowRecord || {}).forEach(([_workflowName, workflow]) => {
366
+ if (this.#mastra) {
367
+ workflow.__registerMastra(this.#mastra);
368
+ }
369
+ });
370
+ return workflowRecord;
371
+ }
372
+ async getVoice({
373
+ runtimeContext
374
+ } = {}) {
375
+ if (this.#voice) {
376
+ const voice = this.#voice;
377
+ voice?.addTools(await this.getTools({
378
+ runtimeContext
379
+ }));
380
+ voice?.addInstructions(await this.getInstructions({
381
+ runtimeContext
382
+ }));
383
+ return voice;
384
+ } else {
385
+ return new chunkZPOUMTTH_cjs.DefaultVoice();
386
+ }
387
+ }
388
+ get instructions() {
389
+ this.logger.warn("The instructions property is deprecated. Please use getInstructions() instead.");
390
+ if (typeof this.#instructions === "function") {
391
+ const mastraError = new chunkB6TOBUS6_cjs.MastraError({
392
+ id: "AGENT_INSTRUCTIONS_INCOMPATIBLE_WITH_FUNCTION_INSTRUCTIONS",
393
+ domain: "AGENT" /* AGENT */,
394
+ category: "USER" /* USER */,
395
+ details: {
396
+ agentName: this.name
397
+ },
398
+ text: "Instructions are not compatible when instructions are a function. Please use getInstructions() instead."
399
+ });
400
+ this.logger.trackException(mastraError);
401
+ this.logger.error(mastraError.toString());
402
+ throw mastraError;
403
+ }
404
+ return this.#instructions;
405
+ }
406
+ getInstructions({
407
+ runtimeContext = new chunkLABUWBKX_cjs.RuntimeContext()
408
+ } = {}) {
409
+ if (typeof this.#instructions === "string") {
410
+ return this.#instructions;
411
+ }
412
+ const result = this.#instructions({
413
+ runtimeContext
414
+ });
415
+ return resolveMaybePromise(result, instructions => {
416
+ if (!instructions) {
417
+ const mastraError = new chunkB6TOBUS6_cjs.MastraError({
418
+ id: "AGENT_GET_INSTRUCTIONS_FUNCTION_EMPTY_RETURN",
419
+ domain: "AGENT" /* AGENT */,
420
+ category: "USER" /* USER */,
421
+ details: {
422
+ agentName: this.name
423
+ },
424
+ text: "Instructions are required to use an Agent. The function-based instructions returned an empty value."
425
+ });
426
+ this.logger.trackException(mastraError);
427
+ this.logger.error(mastraError.toString());
428
+ throw mastraError;
429
+ }
430
+ return instructions;
431
+ });
432
+ }
433
+ getDescription() {
434
+ return this.#description ?? "";
435
+ }
436
+ getDefaultGenerateOptions({
437
+ runtimeContext = new chunkLABUWBKX_cjs.RuntimeContext()
438
+ } = {}) {
439
+ if (typeof this.#defaultGenerateOptions !== "function") {
440
+ return this.#defaultGenerateOptions;
441
+ }
442
+ const result = this.#defaultGenerateOptions({
443
+ runtimeContext
444
+ });
445
+ return resolveMaybePromise(result, options => {
446
+ if (!options) {
447
+ const mastraError = new chunkB6TOBUS6_cjs.MastraError({
448
+ id: "AGENT_GET_DEFAULT_GENERATE_OPTIONS_FUNCTION_EMPTY_RETURN",
449
+ domain: "AGENT" /* AGENT */,
450
+ category: "USER" /* USER */,
451
+ details: {
452
+ agentName: this.name
453
+ },
454
+ text: `[Agent:${this.name}] - Function-based default generate options returned empty value`
455
+ });
456
+ this.logger.trackException(mastraError);
457
+ this.logger.error(mastraError.toString());
458
+ throw mastraError;
459
+ }
460
+ return options;
461
+ });
462
+ }
463
+ getDefaultStreamOptions({
464
+ runtimeContext = new chunkLABUWBKX_cjs.RuntimeContext()
465
+ } = {}) {
466
+ if (typeof this.#defaultStreamOptions !== "function") {
467
+ return this.#defaultStreamOptions;
468
+ }
469
+ const result = this.#defaultStreamOptions({
470
+ runtimeContext
471
+ });
472
+ return resolveMaybePromise(result, options => {
473
+ if (!options) {
474
+ const mastraError = new chunkB6TOBUS6_cjs.MastraError({
475
+ id: "AGENT_GET_DEFAULT_STREAM_OPTIONS_FUNCTION_EMPTY_RETURN",
476
+ domain: "AGENT" /* AGENT */,
477
+ category: "USER" /* USER */,
478
+ details: {
479
+ agentName: this.name
480
+ },
481
+ text: `[Agent:${this.name}] - Function-based default stream options returned empty value`
482
+ });
483
+ this.logger.trackException(mastraError);
484
+ this.logger.error(mastraError.toString());
485
+ throw mastraError;
486
+ }
487
+ return options;
488
+ });
489
+ }
490
+ get tools() {
491
+ this.logger.warn("The tools property is deprecated. Please use getTools() instead.");
492
+ if (typeof this.#tools === "function") {
493
+ const mastraError = new chunkB6TOBUS6_cjs.MastraError({
494
+ id: "AGENT_GET_TOOLS_FUNCTION_INCOMPATIBLE_WITH_TOOL_FUNCTION_TYPE",
495
+ domain: "AGENT" /* AGENT */,
496
+ category: "USER" /* USER */,
497
+ details: {
498
+ agentName: this.name
499
+ },
500
+ text: "Tools are not compatible when tools are a function. Please use getTools() instead."
501
+ });
502
+ this.logger.trackException(mastraError);
503
+ this.logger.error(mastraError.toString());
504
+ throw mastraError;
505
+ }
506
+ return chunkLBUQ6YNU_cjs.ensureToolProperties(this.#tools);
507
+ }
508
+ getTools({
509
+ runtimeContext = new chunkLABUWBKX_cjs.RuntimeContext()
510
+ } = {}) {
511
+ if (typeof this.#tools !== "function") {
512
+ return chunkLBUQ6YNU_cjs.ensureToolProperties(this.#tools);
513
+ }
514
+ const result = this.#tools({
515
+ runtimeContext
516
+ });
517
+ return resolveMaybePromise(result, tools => {
518
+ if (!tools) {
519
+ const mastraError = new chunkB6TOBUS6_cjs.MastraError({
520
+ id: "AGENT_GET_TOOLS_FUNCTION_EMPTY_RETURN",
521
+ domain: "AGENT" /* AGENT */,
522
+ category: "USER" /* USER */,
523
+ details: {
524
+ agentName: this.name
525
+ },
526
+ text: `[Agent:${this.name}] - Function-based tools returned empty value`
527
+ });
528
+ this.logger.trackException(mastraError);
529
+ this.logger.error(mastraError.toString());
530
+ throw mastraError;
531
+ }
532
+ return chunkLBUQ6YNU_cjs.ensureToolProperties(tools);
533
+ });
534
+ }
535
+ get llm() {
536
+ this.logger.warn("The llm property is deprecated. Please use getLLM() instead.");
537
+ if (typeof this.model === "function") {
538
+ const mastraError = new chunkB6TOBUS6_cjs.MastraError({
539
+ id: "AGENT_LLM_GETTER_INCOMPATIBLE_WITH_FUNCTION_MODEL",
540
+ domain: "AGENT" /* AGENT */,
541
+ category: "USER" /* USER */,
542
+ details: {
543
+ agentName: this.name
544
+ },
545
+ text: "LLM is not compatible when model is a function. Please use getLLM() instead."
546
+ });
547
+ this.logger.trackException(mastraError);
548
+ this.logger.error(mastraError.toString());
549
+ throw mastraError;
550
+ }
551
+ return this.getLLM();
552
+ }
553
+ /**
554
+ * Gets or creates an LLM instance based on the current model
555
+ * @param options Options for getting the LLM
556
+ * @returns A promise that resolves to the LLM instance
557
+ */
558
+ getLLM({
559
+ runtimeContext = new chunkLABUWBKX_cjs.RuntimeContext(),
560
+ model
561
+ } = {}) {
562
+ const modelToUse = model ? typeof model === "function" ? model({
563
+ runtimeContext
564
+ }) : model : this.getModel({
565
+ runtimeContext
566
+ });
567
+ return resolveMaybePromise(modelToUse, resolvedModel => {
568
+ const llm = new chunkID5LG5CQ_cjs.MastraLLM({
569
+ model: resolvedModel,
570
+ mastra: this.#mastra
571
+ });
572
+ if (this.#primitives) {
573
+ llm.__registerPrimitives(this.#primitives);
574
+ }
575
+ if (this.#mastra) {
576
+ llm.__registerMastra(this.#mastra);
577
+ }
578
+ return llm;
579
+ });
580
+ }
581
+ /**
582
+ * Gets the model, resolving it if it's a function
583
+ * @param options Options for getting the model
584
+ * @returns A promise that resolves to the model
585
+ */
586
+ getModel({
587
+ runtimeContext = new chunkLABUWBKX_cjs.RuntimeContext()
588
+ } = {}) {
589
+ if (typeof this.model !== "function") {
590
+ if (!this.model) {
591
+ const mastraError = new chunkB6TOBUS6_cjs.MastraError({
592
+ id: "AGENT_GET_MODEL_MISSING_MODEL_INSTANCE",
593
+ domain: "AGENT" /* AGENT */,
594
+ category: "USER" /* USER */,
595
+ details: {
596
+ agentName: this.name
597
+ },
598
+ text: `[Agent:${this.name}] - No model provided`
599
+ });
600
+ this.logger.trackException(mastraError);
601
+ this.logger.error(mastraError.toString());
602
+ throw mastraError;
603
+ }
604
+ return this.model;
605
+ }
606
+ const result = this.model({
607
+ runtimeContext
608
+ });
609
+ return resolveMaybePromise(result, model => {
610
+ if (!model) {
611
+ const mastraError = new chunkB6TOBUS6_cjs.MastraError({
612
+ id: "AGENT_GET_MODEL_FUNCTION_EMPTY_RETURN",
613
+ domain: "AGENT" /* AGENT */,
614
+ category: "USER" /* USER */,
615
+ details: {
616
+ agentName: this.name
617
+ },
618
+ text: `[Agent:${this.name}] - Function-based model returned empty value`
619
+ });
620
+ this.logger.trackException(mastraError);
621
+ this.logger.error(mastraError.toString());
622
+ throw mastraError;
623
+ }
624
+ return model;
625
+ });
626
+ }
627
+ __updateInstructions(newInstructions) {
628
+ this.#instructions = newInstructions;
629
+ this.logger.debug(`[Agents:${this.name}] Instructions updated.`, {
630
+ model: this.model,
631
+ name: this.name
632
+ });
633
+ }
634
+ #primitives;
635
+ __registerPrimitives(p) {
636
+ if (p.telemetry) {
637
+ this.__setTelemetry(p.telemetry);
638
+ }
639
+ if (p.logger) {
640
+ this.__setLogger(p.logger);
641
+ }
642
+ this.#primitives = p;
643
+ this.logger.debug(`[Agents:${this.name}] initialized.`, {
644
+ model: this.model,
645
+ name: this.name
646
+ });
647
+ }
648
+ __registerMastra(mastra) {
649
+ this.#mastra = mastra;
650
+ }
651
+ /**
652
+ * Set the concrete tools for the agent
653
+ * @param tools
654
+ */
655
+ __setTools(tools) {
656
+ this.#tools = tools;
657
+ this.logger.debug(`[Agents:${this.name}] Tools set for agent ${this.name}`, {
658
+ model: this.model,
659
+ name: this.name
660
+ });
661
+ }
662
+ async generateTitleFromUserMessage({
663
+ message,
664
+ runtimeContext = new chunkLABUWBKX_cjs.RuntimeContext(),
665
+ model,
666
+ instructions
667
+ }) {
668
+ const llm = await this.getLLM({
669
+ runtimeContext,
670
+ model
671
+ });
672
+ const normMessage = new chunkZTPPDHQK_cjs.MessageList().add(message, "user").get.all.ui().at(-1);
673
+ if (!normMessage) {
674
+ throw new Error(`Could not generate title from input ${JSON.stringify(message)}`);
675
+ }
676
+ const partsToGen = [];
677
+ for (const part of normMessage.parts) {
678
+ if (part.type === `text`) {
679
+ partsToGen.push(part);
680
+ } else if (part.type === `source`) {
681
+ partsToGen.push({
682
+ type: "text",
683
+ text: `User added URL: ${part.source.url.substring(0, 100)}`
684
+ });
685
+ } else if (part.type === `file`) {
686
+ partsToGen.push({
687
+ type: "text",
688
+ text: `User added ${part.mimeType} file: ${part.data.substring(0, 100)}`
689
+ });
690
+ }
691
+ }
692
+ const systemInstructions = await this.resolveTitleInstructions(runtimeContext, instructions);
693
+ const {
694
+ text
695
+ } = await llm.__text({
696
+ runtimeContext,
697
+ messages: [{
698
+ role: "system",
699
+ content: systemInstructions
700
+ }, {
701
+ role: "user",
702
+ content: JSON.stringify(partsToGen)
703
+ }]
704
+ });
705
+ const cleanedText = text.replace(/<think>[\s\S]*?<\/think>/g, "").trim();
706
+ return cleanedText;
707
+ }
708
+ getMostRecentUserMessage(messages) {
709
+ const userMessages = messages.filter(message => message.role === "user");
710
+ return userMessages.at(-1);
711
+ }
712
+ async genTitle(userMessage, runtimeContext, model, instructions) {
713
+ try {
714
+ if (userMessage) {
715
+ const normMessage = new chunkZTPPDHQK_cjs.MessageList().add(userMessage, "user").get.all.ui().at(-1);
716
+ if (normMessage) {
717
+ return await this.generateTitleFromUserMessage({
718
+ message: normMessage,
719
+ runtimeContext,
720
+ model,
721
+ instructions
722
+ });
723
+ }
724
+ }
725
+ return `New Thread ${(/* @__PURE__ */new Date()).toISOString()}`;
726
+ } catch (e) {
727
+ this.logger.error("Error generating title:", e);
728
+ return void 0;
729
+ }
730
+ }
731
+ /* @deprecated use agent.getMemory() and query memory directly */
732
+ async fetchMemory({
733
+ threadId,
734
+ thread: passedThread,
735
+ memoryConfig,
736
+ resourceId,
737
+ runId,
738
+ userMessages,
739
+ systemMessage,
740
+ messageList = new chunkZTPPDHQK_cjs.MessageList({
741
+ threadId,
742
+ resourceId
743
+ })
744
+ }) {
745
+ const memory = this.getMemory();
746
+ if (memory) {
747
+ const thread = passedThread ?? (await memory.getThreadById({
748
+ threadId
749
+ }));
750
+ if (!thread) {
751
+ return {
752
+ threadId: threadId || "",
753
+ messages: userMessages || []
754
+ };
755
+ }
756
+ if (userMessages && userMessages.length > 0) {
757
+ messageList.add(userMessages, "memory");
758
+ }
759
+ if (systemMessage?.role === "system") {
760
+ messageList.addSystem(systemMessage, "memory");
761
+ }
762
+ const [memoryMessages, memorySystemMessage] = threadId && memory ? await Promise.all([memory.rememberMessages({
763
+ threadId,
764
+ resourceId,
765
+ config: memoryConfig,
766
+ vectorMessageSearch: messageList.getLatestUserContent() || ""
767
+ }).then(r => r.messagesV2), memory.getSystemMessage({
768
+ threadId,
769
+ memoryConfig
770
+ })]) : [[], null];
771
+ this.logger.debug("Fetched messages from memory", {
772
+ threadId,
773
+ runId,
774
+ fetchedCount: memoryMessages.length
775
+ });
776
+ if (memorySystemMessage) {
777
+ messageList.addSystem(memorySystemMessage, "memory");
778
+ }
779
+ messageList.add(memoryMessages, "memory");
780
+ const systemMessages = messageList.getSystemMessages()?.map(m => m.content)?.join(`
781
+ `) ?? void 0;
782
+ const newMessages = messageList.get.input.v1();
783
+ const processedMemoryMessages = memory.processMessages({
784
+ // these will be processed
785
+ messages: messageList.get.remembered.v1(),
786
+ // these are here for inspecting but shouldn't be returned by the processor
787
+ // - ex TokenLimiter needs to measure all tokens even though it's only processing remembered messages
788
+ newMessages,
789
+ systemMessage: systemMessages,
790
+ memorySystemMessage: memorySystemMessage || void 0
791
+ });
792
+ const returnList = new chunkZTPPDHQK_cjs.MessageList().addSystem(systemMessages).add(processedMemoryMessages, "memory").add(newMessages, "user");
793
+ return {
794
+ threadId: thread.id,
795
+ messages: returnList.get.all.prompt()
796
+ };
797
+ }
798
+ return {
799
+ threadId: threadId || "",
800
+ messages: userMessages || []
801
+ };
802
+ }
803
+ async getMemoryTools({
804
+ runId,
805
+ resourceId,
806
+ threadId,
807
+ runtimeContext,
808
+ mastraProxy
809
+ }) {
810
+ let convertedMemoryTools = {};
811
+ const memory = this.getMemory();
812
+ const memoryTools = memory?.getTools?.();
813
+ if (memoryTools) {
814
+ const memoryToolEntries = await Promise.all(Object.entries(memoryTools).map(async ([k, tool]) => {
815
+ return [k, {
816
+ description: tool.description,
817
+ parameters: tool.parameters,
818
+ execute: typeof tool?.execute === "function" ? async (args, options) => {
819
+ try {
820
+ this.logger.debug(`[Agent:${this.name}] - Executing memory tool ${k}`, {
821
+ name: k,
822
+ description: tool.description,
823
+ args,
824
+ runId,
825
+ threadId,
826
+ resourceId
827
+ });
828
+ return tool?.execute?.({
829
+ context: args,
830
+ mastra: mastraProxy,
831
+ memory,
832
+ runId,
833
+ threadId,
834
+ resourceId,
835
+ logger: this.logger,
836
+ agentName: this.name,
837
+ runtimeContext
838
+ }, options) ?? void 0;
839
+ } catch (err) {
840
+ const mastraError = new chunkB6TOBUS6_cjs.MastraError({
841
+ id: "AGENT_MEMORY_TOOL_EXECUTION_FAILED",
842
+ domain: "AGENT" /* AGENT */,
843
+ category: "USER" /* USER */,
844
+ details: {
845
+ agentName: this.name,
846
+ runId: runId || "",
847
+ threadId: threadId || "",
848
+ resourceId: resourceId || ""
849
+ },
850
+ text: `[Agent:${this.name}] - Failed memory tool execution`
851
+ }, err);
852
+ this.logger.trackException(mastraError);
853
+ this.logger.error(mastraError.toString());
854
+ throw mastraError;
855
+ }
856
+ } : void 0
857
+ }];
858
+ }));
859
+ convertedMemoryTools = Object.fromEntries(memoryToolEntries.filter(entry => Boolean(entry)));
860
+ }
861
+ return convertedMemoryTools;
862
+ }
863
+ async getMemoryMessages({
864
+ resourceId,
865
+ threadId,
866
+ vectorMessageSearch,
867
+ memoryConfig
868
+ }) {
869
+ const memory = this.getMemory();
870
+ if (!memory) {
871
+ return [];
872
+ }
873
+ return memory.rememberMessages({
874
+ threadId,
875
+ resourceId,
876
+ config: memoryConfig,
877
+ // The new user messages aren't in the list yet cause we add memory messages first to try to make sure ordering is correct (memory comes before new user messages)
878
+ vectorMessageSearch
879
+ }).then(r => r.messagesV2);
880
+ }
881
+ async getAssignedTools({
882
+ runtimeContext,
883
+ runId,
884
+ resourceId,
885
+ threadId,
886
+ mastraProxy
887
+ }) {
888
+ let toolsForRequest = {};
889
+ this.logger.debug(`[Agents:${this.name}] - Assembling assigned tools`, {
890
+ runId,
891
+ threadId,
892
+ resourceId
893
+ });
894
+ const memory = this.getMemory();
895
+ const assignedTools = await this.getTools({
896
+ runtimeContext
897
+ });
898
+ const assignedToolEntries = Object.entries(assignedTools || {});
899
+ const assignedCoreToolEntries = await Promise.all(assignedToolEntries.map(async ([k, tool]) => {
900
+ if (!tool) {
901
+ return;
902
+ }
903
+ const options = {
904
+ name: k,
905
+ runId,
906
+ threadId,
907
+ resourceId,
908
+ logger: this.logger,
909
+ mastra: mastraProxy,
910
+ memory,
911
+ agentName: this.name,
912
+ runtimeContext,
913
+ model: typeof this.model === "function" ? await this.getModel({
914
+ runtimeContext
915
+ }) : this.model
916
+ };
917
+ return [k, chunkLBUQ6YNU_cjs.makeCoreTool(tool, options)];
918
+ }));
919
+ const assignedToolEntriesConverted = Object.fromEntries(assignedCoreToolEntries.filter(entry => Boolean(entry)));
920
+ toolsForRequest = {
921
+ ...assignedToolEntriesConverted
922
+ };
923
+ return toolsForRequest;
924
+ }
925
+ async getToolsets({
926
+ runId,
927
+ threadId,
928
+ resourceId,
929
+ toolsets,
930
+ runtimeContext,
931
+ mastraProxy
932
+ }) {
933
+ let toolsForRequest = {};
934
+ const memory = this.getMemory();
935
+ const toolsFromToolsets = Object.values(toolsets || {});
936
+ if (toolsFromToolsets.length > 0) {
937
+ this.logger.debug(`[Agent:${this.name}] - Adding tools from toolsets ${Object.keys(toolsets || {}).join(", ")}`, {
938
+ runId
939
+ });
940
+ for (const toolset of toolsFromToolsets) {
941
+ for (const [toolName, tool] of Object.entries(toolset)) {
942
+ const toolObj = tool;
943
+ const options = {
944
+ name: toolName,
945
+ runId,
946
+ threadId,
947
+ resourceId,
948
+ logger: this.logger,
949
+ mastra: mastraProxy,
950
+ memory,
951
+ agentName: this.name,
952
+ runtimeContext,
953
+ model: typeof this.model === "function" ? await this.getModel({
954
+ runtimeContext
955
+ }) : this.model
956
+ };
957
+ const convertedToCoreTool = chunkLBUQ6YNU_cjs.makeCoreTool(toolObj, options, "toolset");
958
+ toolsForRequest[toolName] = convertedToCoreTool;
959
+ }
960
+ }
961
+ }
962
+ return toolsForRequest;
963
+ }
964
+ async getClientTools({
965
+ runId,
966
+ threadId,
967
+ resourceId,
968
+ runtimeContext,
969
+ mastraProxy,
970
+ clientTools
971
+ }) {
972
+ let toolsForRequest = {};
973
+ const memory = this.getMemory();
974
+ const clientToolsForInput = Object.entries(clientTools || {});
975
+ if (clientToolsForInput.length > 0) {
976
+ this.logger.debug(`[Agent:${this.name}] - Adding client tools ${Object.keys(clientTools || {}).join(", ")}`, {
977
+ runId
978
+ });
979
+ for (const [toolName, tool] of clientToolsForInput) {
980
+ const {
981
+ execute,
982
+ ...rest
983
+ } = tool;
984
+ const options = {
985
+ name: toolName,
986
+ runId,
987
+ threadId,
988
+ resourceId,
989
+ logger: this.logger,
990
+ mastra: mastraProxy,
991
+ memory,
992
+ agentName: this.name,
993
+ runtimeContext,
994
+ model: typeof this.model === "function" ? await this.getModel({
995
+ runtimeContext
996
+ }) : this.model
997
+ };
998
+ const convertedToCoreTool = chunkLBUQ6YNU_cjs.makeCoreTool(rest, options, "client-tool");
999
+ toolsForRequest[toolName] = convertedToCoreTool;
1000
+ }
1001
+ }
1002
+ return toolsForRequest;
1003
+ }
1004
+ async getWorkflowTools({
1005
+ runId,
1006
+ threadId,
1007
+ resourceId,
1008
+ runtimeContext
1009
+ }) {
1010
+ let convertedWorkflowTools = {};
1011
+ const workflows = await this.getWorkflows({
1012
+ runtimeContext
1013
+ });
1014
+ if (Object.keys(workflows).length > 0) {
1015
+ convertedWorkflowTools = Object.entries(workflows).reduce((memo, [workflowName, workflow]) => {
1016
+ memo[workflowName] = {
1017
+ description: workflow.description || `Workflow: ${workflowName}`,
1018
+ parameters: workflow.inputSchema || {
1019
+ type: "object",
1020
+ properties: {}
1021
+ },
1022
+ execute: async args => {
1023
+ try {
1024
+ this.logger.debug(`[Agent:${this.name}] - Executing workflow as tool ${workflowName}`, {
1025
+ name: workflowName,
1026
+ description: workflow.description,
1027
+ args,
1028
+ runId,
1029
+ threadId,
1030
+ resourceId
1031
+ });
1032
+ const run = workflow.createRun();
1033
+ const result = await run.start({
1034
+ inputData: args,
1035
+ runtimeContext
1036
+ });
1037
+ return result;
1038
+ } catch (err) {
1039
+ const mastraError = new chunkB6TOBUS6_cjs.MastraError({
1040
+ id: "AGENT_WORKFLOW_TOOL_EXECUTION_FAILED",
1041
+ domain: "AGENT" /* AGENT */,
1042
+ category: "USER" /* USER */,
1043
+ details: {
1044
+ agentName: this.name,
1045
+ runId: runId || "",
1046
+ threadId: threadId || "",
1047
+ resourceId: resourceId || ""
1048
+ },
1049
+ text: `[Agent:${this.name}] - Failed workflow tool execution`
1050
+ }, err);
1051
+ this.logger.trackException(mastraError);
1052
+ this.logger.error(mastraError.toString());
1053
+ throw mastraError;
1054
+ }
1055
+ }
1056
+ };
1057
+ return memo;
1058
+ }, {});
1059
+ }
1060
+ return convertedWorkflowTools;
1061
+ }
1062
+ async convertTools({
1063
+ toolsets,
1064
+ clientTools,
1065
+ threadId,
1066
+ resourceId,
1067
+ runId,
1068
+ runtimeContext
1069
+ }) {
1070
+ let mastraProxy = void 0;
1071
+ const logger = this.logger;
1072
+ if (this.#mastra) {
1073
+ mastraProxy = chunkLBUQ6YNU_cjs.createMastraProxy({
1074
+ mastra: this.#mastra,
1075
+ logger
1076
+ });
1077
+ }
1078
+ const assignedTools = await this.getAssignedTools({
1079
+ runId,
1080
+ resourceId,
1081
+ threadId,
1082
+ runtimeContext,
1083
+ mastraProxy
1084
+ });
1085
+ const memoryTools = await this.getMemoryTools({
1086
+ runId,
1087
+ resourceId,
1088
+ threadId,
1089
+ runtimeContext,
1090
+ mastraProxy
1091
+ });
1092
+ const toolsetTools = await this.getToolsets({
1093
+ runId,
1094
+ resourceId,
1095
+ threadId,
1096
+ runtimeContext,
1097
+ mastraProxy,
1098
+ toolsets
1099
+ });
1100
+ const clientsideTools = await this.getClientTools({
1101
+ runId,
1102
+ resourceId,
1103
+ threadId,
1104
+ runtimeContext,
1105
+ mastraProxy,
1106
+ clientTools
1107
+ });
1108
+ const workflowTools = await this.getWorkflowTools({
1109
+ runId,
1110
+ resourceId,
1111
+ threadId,
1112
+ runtimeContext
1113
+ });
1114
+ return {
1115
+ ...assignedTools,
1116
+ ...memoryTools,
1117
+ ...toolsetTools,
1118
+ ...clientsideTools,
1119
+ ...workflowTools
1120
+ };
1121
+ }
1122
+ /**
1123
+ * Adds response messages from a step to the MessageList and schedules persistence.
1124
+ * This is used for incremental saving: after each agent step, messages are added to a save queue
1125
+ * and a debounced save operation is triggered to avoid redundant writes.
1126
+ *
1127
+ * @param result - The step result containing response messages.
1128
+ * @param messageList - The MessageList instance for the current thread.
1129
+ * @param threadId - The thread ID.
1130
+ * @param memoryConfig - The memory configuration for saving.
1131
+ * @param runId - (Optional) The run ID for logging.
1132
+ */
1133
+ async saveStepMessages({
1134
+ saveQueueManager,
1135
+ result,
1136
+ messageList,
1137
+ threadId,
1138
+ memoryConfig,
1139
+ runId
1140
+ }) {
1141
+ try {
1142
+ messageList.add(result.response.messages, "response");
1143
+ await saveQueueManager.batchMessages(messageList, threadId, memoryConfig);
1144
+ } catch (e) {
1145
+ await saveQueueManager.flushMessages(messageList, threadId, memoryConfig);
1146
+ this.logger.error("Error saving memory on step finish", {
1147
+ error: e,
1148
+ runId
1149
+ });
1150
+ throw e;
1151
+ }
1152
+ }
1153
+ __primitive({
1154
+ instructions,
1155
+ messages,
1156
+ context,
1157
+ thread,
1158
+ memoryConfig,
1159
+ resourceId,
1160
+ runId,
1161
+ toolsets,
1162
+ clientTools,
1163
+ runtimeContext,
1164
+ generateMessageId,
1165
+ saveQueueManager
1166
+ }) {
1167
+ return {
1168
+ before: async () => {
1169
+ if (process.env.NODE_ENV !== "test") {
1170
+ this.logger.debug(`[Agents:${this.name}] - Starting generation`, {
1171
+ runId
1172
+ });
1173
+ }
1174
+ const memory = this.getMemory();
1175
+ const toolEnhancements = [
1176
+ // toolsets
1177
+ toolsets && Object.keys(toolsets || {}).length > 0 ? `toolsets present (${Object.keys(toolsets || {}).length} tools)` : void 0,
1178
+ // memory tools
1179
+ memory && resourceId ? "memory and resourceId available" : void 0].filter(Boolean).join(", ");
1180
+ this.logger.debug(`[Agent:${this.name}] - Enhancing tools: ${toolEnhancements}`, {
1181
+ runId,
1182
+ toolsets: toolsets ? Object.keys(toolsets) : void 0,
1183
+ clientTools: clientTools ? Object.keys(clientTools) : void 0,
1184
+ hasMemory: !!this.getMemory(),
1185
+ hasResourceId: !!resourceId
1186
+ });
1187
+ const threadId = thread?.id;
1188
+ const convertedTools = await this.convertTools({
1189
+ toolsets,
1190
+ clientTools,
1191
+ threadId,
1192
+ resourceId,
1193
+ runId,
1194
+ runtimeContext
1195
+ });
1196
+ const messageList = new chunkZTPPDHQK_cjs.MessageList({
1197
+ threadId,
1198
+ resourceId,
1199
+ generateMessageId
1200
+ }).addSystem({
1201
+ role: "system",
1202
+ content: instructions || `${this.instructions}.`
1203
+ }).add(context || [], "context");
1204
+ if (!memory || !threadId && !resourceId) {
1205
+ messageList.add(messages, "user");
1206
+ return {
1207
+ messageObjects: messageList.get.all.prompt(),
1208
+ convertedTools,
1209
+ messageList
1210
+ };
1211
+ }
1212
+ if (!threadId || !resourceId) {
1213
+ const mastraError = new chunkB6TOBUS6_cjs.MastraError({
1214
+ id: "AGENT_MEMORY_MISSING_RESOURCE_ID",
1215
+ domain: "AGENT" /* AGENT */,
1216
+ category: "USER" /* USER */,
1217
+ details: {
1218
+ agentName: this.name,
1219
+ threadId: threadId || "",
1220
+ resourceId: resourceId || ""
1221
+ },
1222
+ text: `A resourceId must be provided when passing a threadId and using Memory. Saw threadId ${threadId} but resourceId is ${resourceId}`
1223
+ });
1224
+ this.logger.trackException(mastraError);
1225
+ this.logger.error(mastraError.toString());
1226
+ throw mastraError;
1227
+ }
1228
+ const store = memory.constructor.name;
1229
+ this.logger.debug(`[Agent:${this.name}] - Memory persistence enabled: store=${store}, resourceId=${resourceId}`, {
1230
+ runId,
1231
+ resourceId,
1232
+ threadId,
1233
+ memoryStore: store
1234
+ });
1235
+ let threadObject = void 0;
1236
+ const existingThread = await memory.getThreadById({
1237
+ threadId
1238
+ });
1239
+ if (existingThread) {
1240
+ if (!existingThread.metadata && thread.metadata || thread.metadata && !(0, import_fast_deep_equal.default)(existingThread.metadata, thread.metadata)) {
1241
+ threadObject = await memory.saveThread({
1242
+ thread: {
1243
+ ...existingThread,
1244
+ metadata: thread.metadata
1245
+ },
1246
+ memoryConfig
1247
+ });
1248
+ } else {
1249
+ threadObject = existingThread;
1250
+ }
1251
+ } else {
1252
+ threadObject = await memory.createThread({
1253
+ threadId,
1254
+ metadata: thread.metadata,
1255
+ title: thread.title,
1256
+ memoryConfig,
1257
+ resourceId
1258
+ });
1259
+ }
1260
+ let [memoryMessages, memorySystemMessage] = thread.id && memory ? await Promise.all([this.getMemoryMessages({
1261
+ resourceId,
1262
+ threadId: threadObject.id,
1263
+ vectorMessageSearch: new chunkZTPPDHQK_cjs.MessageList().add(messages, `user`).getLatestUserContent() || "",
1264
+ memoryConfig
1265
+ }), memory.getSystemMessage({
1266
+ threadId: threadObject.id,
1267
+ resourceId,
1268
+ memoryConfig
1269
+ })]) : [[], null];
1270
+ this.logger.debug("Fetched messages from memory", {
1271
+ threadId: threadObject.id,
1272
+ runId,
1273
+ fetchedCount: memoryMessages.length
1274
+ });
1275
+ const resultsFromOtherThreads = memoryMessages.filter(m => m.threadId !== threadObject.id);
1276
+ if (resultsFromOtherThreads.length && !memorySystemMessage) {
1277
+ memorySystemMessage = ``;
1278
+ }
1279
+ if (resultsFromOtherThreads.length) {
1280
+ memorySystemMessage += `
1281
+ The following messages were remembered from a different conversation:
1282
+ <remembered_from_other_conversation>
1283
+ ${(() => {
1284
+ let result = ``;
1285
+ const messages2 = new chunkZTPPDHQK_cjs.MessageList().add(resultsFromOtherThreads, "memory").get.all.v1();
1286
+ let lastYmd = null;
1287
+ for (const msg of messages2) {
1288
+ const date = msg.createdAt;
1289
+ const year = date.getUTCFullYear();
1290
+ const month = date.toLocaleString("default", {
1291
+ month: "short"
1292
+ });
1293
+ const day = date.getUTCDate();
1294
+ const ymd = `${year}, ${month}, ${day}`;
1295
+ const utcHour = date.getUTCHours();
1296
+ const utcMinute = date.getUTCMinutes();
1297
+ const hour12 = utcHour % 12 || 12;
1298
+ const ampm = utcHour < 12 ? "AM" : "PM";
1299
+ const timeofday = `${hour12}:${utcMinute < 10 ? "0" : ""}${utcMinute} ${ampm}`;
1300
+ if (!lastYmd || lastYmd !== ymd) {
1301
+ result += `
1302
+ the following messages are from ${ymd}
1303
+ `;
1304
+ }
1305
+ result += `
1306
+ Message ${msg.threadId && msg.threadId !== threadObject.id ? "from previous conversation" : ""} at ${timeofday}: ${JSON.stringify(msg)}`;
1307
+ lastYmd = ymd;
1308
+ }
1309
+ return result;
1310
+ })()}
1311
+ <end_remembered_from_other_conversation>`;
1312
+ }
1313
+ if (memorySystemMessage) {
1314
+ messageList.addSystem(memorySystemMessage, "memory");
1315
+ }
1316
+ messageList.add(memoryMessages.filter(m => m.threadId === threadObject.id),
1317
+ // filter out messages from other threads. those are added to system message above
1318
+ "memory").add(messages, "user");
1319
+ const systemMessage = [...messageList.getSystemMessages(), ...messageList.getSystemMessages("memory")]?.map(m => m.content)?.join(`
1320
+ `) ?? void 0;
1321
+ const processedMemoryMessages = memory.processMessages({
1322
+ // these will be processed
1323
+ messages: messageList.get.remembered.v1(),
1324
+ // these are here for inspecting but shouldn't be returned by the processor
1325
+ // - ex TokenLimiter needs to measure all tokens even though it's only processing remembered messages
1326
+ newMessages: messageList.get.input.v1(),
1327
+ systemMessage,
1328
+ memorySystemMessage: memorySystemMessage || void 0
1329
+ });
1330
+ const processedList = new chunkZTPPDHQK_cjs.MessageList({
1331
+ threadId: threadObject.id,
1332
+ resourceId
1333
+ }).addSystem(instructions || `${this.instructions}.`).addSystem(memorySystemMessage).add(context || [], "context").add(processedMemoryMessages, "memory").add(messageList.get.input.v2(), "user").get.all.prompt();
1334
+ return {
1335
+ convertedTools,
1336
+ thread: threadObject,
1337
+ messageList,
1338
+ // add old processed messages + new input messages
1339
+ messageObjects: processedList
1340
+ };
1341
+ },
1342
+ after: async ({
1343
+ result,
1344
+ thread: threadAfter,
1345
+ threadId,
1346
+ memoryConfig: memoryConfig2,
1347
+ outputText,
1348
+ runId: runId2,
1349
+ messageList
1350
+ }) => {
1351
+ const resToLog = {
1352
+ text: result?.text,
1353
+ object: result?.object,
1354
+ toolResults: result?.toolResults,
1355
+ toolCalls: result?.toolCalls,
1356
+ usage: result?.usage,
1357
+ steps: result?.steps?.map(s => {
1358
+ return {
1359
+ stepType: s?.stepType,
1360
+ text: result?.text,
1361
+ object: result?.object,
1362
+ toolResults: result?.toolResults,
1363
+ toolCalls: result?.toolCalls,
1364
+ usage: result?.usage
1365
+ };
1366
+ })
1367
+ };
1368
+ this.logger.debug(`[Agent:${this.name}] - Post processing LLM response`, {
1369
+ runId: runId2,
1370
+ result: resToLog,
1371
+ threadId
1372
+ });
1373
+ const memory = this.getMemory();
1374
+ const messageListResponses = new chunkZTPPDHQK_cjs.MessageList({
1375
+ threadId,
1376
+ resourceId
1377
+ }).add(result.response.messages, "response").get.all.core();
1378
+ const usedWorkingMemory = messageListResponses?.some(m => m.role === "tool" && m?.content?.some(c => c?.toolName === "updateWorkingMemory"));
1379
+ const thread2 = usedWorkingMemory ? threadId ? await memory?.getThreadById({
1380
+ threadId
1381
+ }) : void 0 : threadAfter;
1382
+ if (memory && resourceId && thread2) {
1383
+ try {
1384
+ let responseMessages = result.response.messages;
1385
+ if (!responseMessages && result.object) {
1386
+ responseMessages = [{
1387
+ role: "assistant",
1388
+ content: [{
1389
+ type: "text",
1390
+ text: outputText
1391
+ // outputText contains the stringified object
1392
+ }]
1393
+ }];
1394
+ }
1395
+ if (responseMessages) {
1396
+ messageList.add(responseMessages, "response");
1397
+ }
1398
+ const promises = [saveQueueManager.flushMessages(messageList, threadId, memoryConfig2)];
1399
+ if (thread2.title?.startsWith("New Thread")) {
1400
+ const config = memory.getMergedThreadConfig(memoryConfig2);
1401
+ const userMessage = this.getMostRecentUserMessage(messageList.get.all.ui());
1402
+ const {
1403
+ shouldGenerate,
1404
+ model: titleModel,
1405
+ instructions: titleInstructions
1406
+ } = this.resolveTitleGenerationConfig(config?.threads?.generateTitle);
1407
+ if (shouldGenerate && userMessage) {
1408
+ promises.push(this.genTitle(userMessage, runtimeContext, titleModel, titleInstructions).then(title => {
1409
+ if (title) {
1410
+ return memory.createThread({
1411
+ threadId: thread2.id,
1412
+ resourceId,
1413
+ memoryConfig: memoryConfig2,
1414
+ title,
1415
+ metadata: thread2.metadata
1416
+ });
1417
+ }
1418
+ }));
1419
+ }
1420
+ }
1421
+ await Promise.all(promises);
1422
+ } catch (e) {
1423
+ await saveQueueManager.flushMessages(messageList, threadId, memoryConfig2);
1424
+ if (e instanceof chunkB6TOBUS6_cjs.MastraError) {
1425
+ throw e;
1426
+ }
1427
+ const mastraError = new chunkB6TOBUS6_cjs.MastraError({
1428
+ id: "AGENT_MEMORY_PERSIST_RESPONSE_MESSAGES_FAILED",
1429
+ domain: "AGENT" /* AGENT */,
1430
+ category: "SYSTEM" /* SYSTEM */,
1431
+ details: {
1432
+ agentName: this.name,
1433
+ runId: runId2 || "",
1434
+ threadId: threadId || "",
1435
+ result: JSON.stringify(resToLog)
1436
+ }
1437
+ }, e);
1438
+ this.logger.trackException(mastraError);
1439
+ this.logger.error(mastraError.toString());
1440
+ throw mastraError;
1441
+ }
1442
+ }
1443
+ if (Object.keys(this.evals || {}).length > 0) {
1444
+ const userInputMessages = messageList.get.all.ui().filter(m => m.role === "user");
1445
+ const input = userInputMessages.map(message => typeof message.content === "string" ? message.content : "").join("\n");
1446
+ const runIdToUse = runId2 || crypto.randomUUID();
1447
+ for (const metric of Object.values(this.evals || {})) {
1448
+ chunkST5RMVLG_cjs.executeHook("onGeneration" /* ON_GENERATION */, {
1449
+ input,
1450
+ output: outputText,
1451
+ runId: runIdToUse,
1452
+ metric,
1453
+ agentName: this.name,
1454
+ instructions: instructions || this.instructions
1455
+ });
1456
+ }
1457
+ }
1458
+ }
1459
+ };
1460
+ }
1461
+ async generate(messages, generateOptions = {}) {
1462
+ const defaultGenerateOptions = await this.getDefaultGenerateOptions({
1463
+ runtimeContext: generateOptions.runtimeContext
1464
+ });
1465
+ const {
1466
+ context,
1467
+ memoryOptions: memoryConfigFromArgs,
1468
+ resourceId: resourceIdFromArgs,
1469
+ maxSteps,
1470
+ onStepFinish,
1471
+ output,
1472
+ toolsets,
1473
+ clientTools,
1474
+ temperature,
1475
+ toolChoice = "auto",
1476
+ experimental_output,
1477
+ telemetry,
1478
+ runtimeContext = new chunkLABUWBKX_cjs.RuntimeContext(),
1479
+ savePerStep = false,
1480
+ ...args
1481
+ } = Object.assign({}, defaultGenerateOptions, generateOptions);
1482
+ const generateMessageId = `experimental_generateMessageId` in args && typeof args.experimental_generateMessageId === `function` ? args.experimental_generateMessageId : void 0;
1483
+ const threadFromArgs = resolveThreadIdFromArgs({
1484
+ ...args,
1485
+ ...generateOptions
1486
+ });
1487
+ const resourceId = args.memory?.resource || resourceIdFromArgs;
1488
+ const memoryConfig = args.memory?.options || memoryConfigFromArgs;
1489
+ if (resourceId && threadFromArgs && !this.getMemory()) {
1490
+ this.logger.warn(`[Agent:${this.name}] - No memory is configured but resourceId and threadId were passed in args. This will not work.`);
1491
+ }
1492
+ const runId = args.runId || crypto$1.randomUUID();
1493
+ const instructions = args.instructions || (await this.getInstructions({
1494
+ runtimeContext
1495
+ }));
1496
+ const llm = await this.getLLM({
1497
+ runtimeContext
1498
+ });
1499
+ const memory = this.getMemory();
1500
+ const saveQueueManager = new SaveQueueManager({
1501
+ logger: this.logger,
1502
+ memory
1503
+ });
1504
+ const {
1505
+ before,
1506
+ after
1507
+ } = this.__primitive({
1508
+ messages,
1509
+ instructions,
1510
+ context,
1511
+ thread: threadFromArgs,
1512
+ memoryConfig,
1513
+ resourceId,
1514
+ runId,
1515
+ toolsets,
1516
+ clientTools,
1517
+ runtimeContext,
1518
+ generateMessageId,
1519
+ saveQueueManager
1520
+ });
1521
+ const {
1522
+ thread,
1523
+ messageObjects,
1524
+ convertedTools,
1525
+ messageList
1526
+ } = await before();
1527
+ const threadId = thread?.id;
1528
+ if (!output && experimental_output) {
1529
+ const result2 = await llm.__text({
1530
+ messages: messageObjects,
1531
+ tools: convertedTools,
1532
+ onStepFinish: async result3 => {
1533
+ if (savePerStep) {
1534
+ await this.saveStepMessages({
1535
+ saveQueueManager,
1536
+ result: result3,
1537
+ messageList,
1538
+ threadId,
1539
+ memoryConfig,
1540
+ runId
1541
+ });
1542
+ }
1543
+ return onStepFinish?.({
1544
+ ...result3,
1545
+ runId
1546
+ });
1547
+ },
1548
+ maxSteps,
1549
+ runId,
1550
+ temperature,
1551
+ toolChoice: toolChoice || "auto",
1552
+ experimental_output,
1553
+ threadId,
1554
+ resourceId,
1555
+ memory: this.getMemory(),
1556
+ runtimeContext,
1557
+ telemetry,
1558
+ ...args
1559
+ });
1560
+ const outputText2 = result2.text;
1561
+ await after({
1562
+ result: result2,
1563
+ threadId,
1564
+ thread,
1565
+ memoryConfig,
1566
+ outputText: outputText2,
1567
+ runId,
1568
+ messageList
1569
+ });
1570
+ const newResult = result2;
1571
+ newResult.object = result2.experimental_output;
1572
+ return newResult;
1573
+ }
1574
+ if (!output) {
1575
+ const result2 = await llm.__text({
1576
+ messages: messageObjects,
1577
+ tools: convertedTools,
1578
+ onStepFinish: async result3 => {
1579
+ if (savePerStep) {
1580
+ await this.saveStepMessages({
1581
+ saveQueueManager,
1582
+ result: result3,
1583
+ messageList,
1584
+ threadId,
1585
+ memoryConfig,
1586
+ runId
1587
+ });
1588
+ }
1589
+ return onStepFinish?.({
1590
+ ...result3,
1591
+ runId
1592
+ });
1593
+ },
1594
+ maxSteps,
1595
+ runId,
1596
+ temperature,
1597
+ toolChoice,
1598
+ telemetry,
1599
+ threadId,
1600
+ resourceId,
1601
+ memory: this.getMemory(),
1602
+ runtimeContext,
1603
+ ...args
1604
+ });
1605
+ const outputText2 = result2.text;
1606
+ await after({
1607
+ result: result2,
1608
+ thread,
1609
+ threadId,
1610
+ memoryConfig,
1611
+ outputText: outputText2,
1612
+ runId,
1613
+ messageList
1614
+ });
1615
+ return result2;
1616
+ }
1617
+ const result = await llm.__textObject({
1618
+ messages: messageObjects,
1619
+ tools: convertedTools,
1620
+ structuredOutput: output,
1621
+ onStepFinish: async result2 => {
1622
+ if (savePerStep) {
1623
+ await this.saveStepMessages({
1624
+ saveQueueManager,
1625
+ result: result2,
1626
+ messageList,
1627
+ threadId,
1628
+ memoryConfig,
1629
+ runId
1630
+ });
1631
+ }
1632
+ return onStepFinish?.({
1633
+ ...result2,
1634
+ runId
1635
+ });
1636
+ },
1637
+ maxSteps,
1638
+ runId,
1639
+ temperature,
1640
+ toolChoice,
1641
+ telemetry,
1642
+ memory: this.getMemory(),
1643
+ runtimeContext,
1644
+ ...args
1645
+ });
1646
+ const outputText = JSON.stringify(result.object);
1647
+ await after({
1648
+ result,
1649
+ thread,
1650
+ threadId,
1651
+ memoryConfig,
1652
+ outputText,
1653
+ runId,
1654
+ messageList
1655
+ });
1656
+ return result;
1657
+ }
1658
+ async stream(messages, streamOptions = {}) {
1659
+ const defaultStreamOptions = await this.getDefaultStreamOptions({
1660
+ runtimeContext: streamOptions.runtimeContext
1661
+ });
1662
+ const {
1663
+ context,
1664
+ memoryOptions: memoryConfigFromArgs,
1665
+ resourceId: resourceIdFromArgs,
1666
+ maxSteps,
1667
+ onFinish,
1668
+ onStepFinish,
1669
+ toolsets,
1670
+ clientTools,
1671
+ output,
1672
+ temperature,
1673
+ toolChoice = "auto",
1674
+ experimental_output,
1675
+ telemetry,
1676
+ runtimeContext = new chunkLABUWBKX_cjs.RuntimeContext(),
1677
+ savePerStep = false,
1678
+ ...args
1679
+ } = Object.assign({}, defaultStreamOptions, streamOptions);
1680
+ const generateMessageId = `experimental_generateMessageId` in args && typeof args.experimental_generateMessageId === `function` ? args.experimental_generateMessageId : void 0;
1681
+ const threadFromArgs = resolveThreadIdFromArgs({
1682
+ ...args,
1683
+ ...streamOptions
1684
+ });
1685
+ const resourceId = args.memory?.resource || resourceIdFromArgs;
1686
+ const memoryConfig = args.memory?.options || memoryConfigFromArgs;
1687
+ if (resourceId && threadFromArgs && !this.getMemory()) {
1688
+ this.logger.warn(`[Agent:${this.name}] - No memory is configured but resourceId and threadId were passed in args. This will not work.`);
1689
+ }
1690
+ const runId = args.runId || crypto$1.randomUUID();
1691
+ const instructions = args.instructions || (await this.getInstructions({
1692
+ runtimeContext
1693
+ }));
1694
+ const llm = await this.getLLM({
1695
+ runtimeContext
1696
+ });
1697
+ const memory = this.getMemory();
1698
+ const saveQueueManager = new SaveQueueManager({
1699
+ logger: this.logger,
1700
+ memory
1701
+ });
1702
+ const {
1703
+ before,
1704
+ after
1705
+ } = this.__primitive({
1706
+ instructions,
1707
+ messages,
1708
+ context,
1709
+ thread: threadFromArgs,
1710
+ memoryConfig,
1711
+ resourceId,
1712
+ runId,
1713
+ toolsets,
1714
+ clientTools,
1715
+ runtimeContext,
1716
+ generateMessageId,
1717
+ saveQueueManager
1718
+ });
1719
+ const {
1720
+ thread,
1721
+ messageObjects,
1722
+ convertedTools,
1723
+ messageList
1724
+ } = await before();
1725
+ const threadId = thread?.id;
1726
+ if (!output && experimental_output) {
1727
+ this.logger.debug(`Starting agent ${this.name} llm stream call`, {
1728
+ runId
1729
+ });
1730
+ const streamResult = llm.__stream({
1731
+ messages: messageObjects,
1732
+ temperature,
1733
+ tools: convertedTools,
1734
+ onStepFinish: async result => {
1735
+ if (savePerStep) {
1736
+ await this.saveStepMessages({
1737
+ saveQueueManager,
1738
+ result,
1739
+ messageList,
1740
+ threadId,
1741
+ memoryConfig,
1742
+ runId
1743
+ });
1744
+ }
1745
+ return onStepFinish?.({
1746
+ ...result,
1747
+ runId
1748
+ });
1749
+ },
1750
+ onFinish: async result => {
1751
+ try {
1752
+ const outputText = result.text;
1753
+ await after({
1754
+ result,
1755
+ thread,
1756
+ threadId,
1757
+ memoryConfig,
1758
+ outputText,
1759
+ runId,
1760
+ messageList
1761
+ });
1762
+ } catch (e) {
1763
+ this.logger.error("Error saving memory on finish", {
1764
+ error: e,
1765
+ runId
1766
+ });
1767
+ }
1768
+ await onFinish?.({
1769
+ ...result,
1770
+ runId
1771
+ });
1772
+ },
1773
+ maxSteps,
1774
+ runId,
1775
+ toolChoice,
1776
+ experimental_output,
1777
+ telemetry,
1778
+ memory: this.getMemory(),
1779
+ runtimeContext,
1780
+ threadId: thread?.id,
1781
+ resourceId,
1782
+ ...args
1783
+ });
1784
+ const newStreamResult = streamResult;
1785
+ newStreamResult.partialObjectStream = streamResult.experimental_partialOutputStream;
1786
+ return newStreamResult;
1787
+ } else if (!output) {
1788
+ this.logger.debug(`Starting agent ${this.name} llm stream call`, {
1789
+ runId
1790
+ });
1791
+ return llm.__stream({
1792
+ messages: messageObjects,
1793
+ temperature,
1794
+ tools: convertedTools,
1795
+ onStepFinish: async result => {
1796
+ if (savePerStep) {
1797
+ await this.saveStepMessages({
1798
+ saveQueueManager,
1799
+ result,
1800
+ messageList,
1801
+ threadId,
1802
+ memoryConfig,
1803
+ runId
1804
+ });
1805
+ }
1806
+ return onStepFinish?.({
1807
+ ...result,
1808
+ runId
1809
+ });
1810
+ },
1811
+ onFinish: async result => {
1812
+ try {
1813
+ const outputText = result.text;
1814
+ await after({
1815
+ result,
1816
+ thread,
1817
+ threadId,
1818
+ memoryConfig,
1819
+ outputText,
1820
+ runId,
1821
+ messageList
1822
+ });
1823
+ } catch (e) {
1824
+ this.logger.error("Error saving memory on finish", {
1825
+ error: e,
1826
+ runId
1827
+ });
1828
+ }
1829
+ await onFinish?.({
1830
+ ...result,
1831
+ runId
1832
+ });
1833
+ },
1834
+ maxSteps,
1835
+ runId,
1836
+ toolChoice,
1837
+ telemetry,
1838
+ memory: this.getMemory(),
1839
+ runtimeContext,
1840
+ threadId: thread?.id,
1841
+ resourceId,
1842
+ ...args
1843
+ });
1844
+ }
1845
+ this.logger.debug(`Starting agent ${this.name} llm streamObject call`, {
1846
+ runId
1847
+ });
1848
+ return llm.__streamObject({
1849
+ messages: messageObjects,
1850
+ tools: convertedTools,
1851
+ temperature,
1852
+ structuredOutput: output,
1853
+ onStepFinish: async result => {
1854
+ if (savePerStep) {
1855
+ await this.saveStepMessages({
1856
+ saveQueueManager,
1857
+ result,
1858
+ messageList,
1859
+ threadId,
1860
+ memoryConfig,
1861
+ runId
1862
+ });
1863
+ }
1864
+ return onStepFinish?.({
1865
+ ...result,
1866
+ runId
1867
+ });
1868
+ },
1869
+ onFinish: async result => {
1870
+ try {
1871
+ const outputText = JSON.stringify(result.object);
1872
+ await after({
1873
+ result,
1874
+ thread,
1875
+ threadId,
1876
+ memoryConfig,
1877
+ outputText,
1878
+ runId,
1879
+ messageList
1880
+ });
1881
+ } catch (e) {
1882
+ this.logger.error("Error saving memory on finish", {
1883
+ error: e,
1884
+ runId
1885
+ });
1886
+ }
1887
+ await onFinish?.({
1888
+ ...result,
1889
+ runId
1890
+ });
1891
+ },
1892
+ runId,
1893
+ toolChoice,
1894
+ telemetry,
1895
+ memory: this.getMemory(),
1896
+ runtimeContext,
1897
+ threadId: thread?.id,
1898
+ resourceId,
1899
+ ...args
1900
+ });
1901
+ }
1902
+ /**
1903
+ * Convert text to speech using the configured voice provider
1904
+ * @param input Text or text stream to convert to speech
1905
+ * @param options Speech options including speaker and provider-specific options
1906
+ * @returns Audio stream
1907
+ * @deprecated Use agent.voice.speak() instead
1908
+ */
1909
+ async speak(input, options) {
1910
+ if (!this.voice) {
1911
+ const mastraError = new chunkB6TOBUS6_cjs.MastraError({
1912
+ id: "AGENT_SPEAK_METHOD_VOICE_NOT_CONFIGURED",
1913
+ domain: "AGENT" /* AGENT */,
1914
+ category: "USER" /* USER */,
1915
+ details: {
1916
+ agentName: this.name
1917
+ },
1918
+ text: "No voice provider configured"
1919
+ });
1920
+ this.logger.trackException(mastraError);
1921
+ this.logger.error(mastraError.toString());
1922
+ throw mastraError;
1923
+ }
1924
+ this.logger.warn("Warning: agent.speak() is deprecated. Please use agent.voice.speak() instead.");
1925
+ try {
1926
+ return this.voice.speak(input, options);
1927
+ } catch (e) {
1928
+ let err;
1929
+ if (e instanceof chunkB6TOBUS6_cjs.MastraError) {
1930
+ err = e;
1931
+ } else {
1932
+ err = new chunkB6TOBUS6_cjs.MastraError({
1933
+ id: "AGENT_SPEAK_METHOD_ERROR",
1934
+ domain: "AGENT" /* AGENT */,
1935
+ category: "UNKNOWN" /* UNKNOWN */,
1936
+ details: {
1937
+ agentName: this.name
1938
+ },
1939
+ text: "Error during agent speak"
1940
+ }, e);
1941
+ }
1942
+ this.logger.trackException(err);
1943
+ this.logger.error(err.toString());
1944
+ throw err;
1945
+ }
1946
+ }
1947
+ /**
1948
+ * Convert speech to text using the configured voice provider
1949
+ * @param audioStream Audio stream to transcribe
1950
+ * @param options Provider-specific transcription options
1951
+ * @returns Text or text stream
1952
+ * @deprecated Use agent.voice.listen() instead
1953
+ */
1954
+ async listen(audioStream, options) {
1955
+ if (!this.voice) {
1956
+ const mastraError = new chunkB6TOBUS6_cjs.MastraError({
1957
+ id: "AGENT_LISTEN_METHOD_VOICE_NOT_CONFIGURED",
1958
+ domain: "AGENT" /* AGENT */,
1959
+ category: "USER" /* USER */,
1960
+ details: {
1961
+ agentName: this.name
1962
+ },
1963
+ text: "No voice provider configured"
1964
+ });
1965
+ this.logger.trackException(mastraError);
1966
+ this.logger.error(mastraError.toString());
1967
+ throw mastraError;
1968
+ }
1969
+ this.logger.warn("Warning: agent.listen() is deprecated. Please use agent.voice.listen() instead");
1970
+ try {
1971
+ return this.voice.listen(audioStream, options);
1972
+ } catch (e) {
1973
+ let err;
1974
+ if (e instanceof chunkB6TOBUS6_cjs.MastraError) {
1975
+ err = e;
1976
+ } else {
1977
+ err = new chunkB6TOBUS6_cjs.MastraError({
1978
+ id: "AGENT_LISTEN_METHOD_ERROR",
1979
+ domain: "AGENT" /* AGENT */,
1980
+ category: "UNKNOWN" /* UNKNOWN */,
1981
+ details: {
1982
+ agentName: this.name
1983
+ },
1984
+ text: "Error during agent listen"
1985
+ }, e);
1986
+ }
1987
+ this.logger.trackException(err);
1988
+ this.logger.error(err.toString());
1989
+ throw err;
1990
+ }
1991
+ }
1992
+ /**
1993
+ * Get a list of available speakers from the configured voice provider
1994
+ * @throws {Error} If no voice provider is configured
1995
+ * @returns {Promise<Array<{voiceId: string}>>} List of available speakers
1996
+ * @deprecated Use agent.voice.getSpeakers() instead
1997
+ */
1998
+ async getSpeakers() {
1999
+ if (!this.voice) {
2000
+ const mastraError = new chunkB6TOBUS6_cjs.MastraError({
2001
+ id: "AGENT_SPEAKERS_METHOD_VOICE_NOT_CONFIGURED",
2002
+ domain: "AGENT" /* AGENT */,
2003
+ category: "USER" /* USER */,
2004
+ details: {
2005
+ agentName: this.name
2006
+ },
2007
+ text: "No voice provider configured"
2008
+ });
2009
+ this.logger.trackException(mastraError);
2010
+ this.logger.error(mastraError.toString());
2011
+ throw mastraError;
2012
+ }
2013
+ this.logger.warn("Warning: agent.getSpeakers() is deprecated. Please use agent.voice.getSpeakers() instead.");
2014
+ try {
2015
+ return await this.voice.getSpeakers();
2016
+ } catch (e) {
2017
+ let err;
2018
+ if (e instanceof chunkB6TOBUS6_cjs.MastraError) {
2019
+ err = e;
2020
+ } else {
2021
+ err = new chunkB6TOBUS6_cjs.MastraError({
2022
+ id: "AGENT_GET_SPEAKERS_METHOD_ERROR",
2023
+ domain: "AGENT" /* AGENT */,
2024
+ category: "UNKNOWN" /* UNKNOWN */,
2025
+ details: {
2026
+ agentName: this.name
2027
+ },
2028
+ text: "Error during agent getSpeakers"
2029
+ }, e);
2030
+ }
2031
+ this.logger.trackException(err);
2032
+ this.logger.error(err.toString());
2033
+ throw err;
2034
+ }
2035
+ }
2036
+ toStep() {
2037
+ const x = agentToStep(this);
2038
+ return new LegacyStep(x);
2039
+ }
2040
+ /**
2041
+ * Resolves the configuration for title generation.
2042
+ * @private
2043
+ */
2044
+ resolveTitleGenerationConfig(generateTitleConfig) {
2045
+ if (typeof generateTitleConfig === "boolean") {
2046
+ return {
2047
+ shouldGenerate: generateTitleConfig
2048
+ };
2049
+ }
2050
+ if (typeof generateTitleConfig === "object" && generateTitleConfig !== null) {
2051
+ return {
2052
+ shouldGenerate: true,
2053
+ model: generateTitleConfig.model,
2054
+ instructions: generateTitleConfig.instructions
2055
+ };
2056
+ }
2057
+ return {
2058
+ shouldGenerate: false
2059
+ };
2060
+ }
2061
+ /**
2062
+ * Resolves title generation instructions, handling both static strings and dynamic functions
2063
+ * @private
2064
+ */
2065
+ async resolveTitleInstructions(runtimeContext, instructions) {
2066
+ const DEFAULT_TITLE_INSTRUCTIONS = `
2067
+ - you will generate a short title based on the first message a user begins a conversation with
2068
+ - ensure it is not more than 80 characters long
2069
+ - the title should be a summary of the user's message
2070
+ - do not use quotes or colons
2071
+ - the entire text you return will be used as the title`;
2072
+ if (!instructions) {
2073
+ return DEFAULT_TITLE_INSTRUCTIONS;
2074
+ }
2075
+ if (typeof instructions === "string") {
2076
+ return instructions;
2077
+ } else {
2078
+ const result = instructions({
2079
+ runtimeContext
2080
+ });
2081
+ return resolveMaybePromise(result, resolvedInstructions => {
2082
+ return resolvedInstructions || DEFAULT_TITLE_INSTRUCTIONS;
2083
+ });
2084
+ }
2085
+ }
2086
+ };
2087
+ exports.Agent = /*@__PURE__*/(_ => {
2088
+ _init = chunkU64IJDC5_cjs.__decoratorStart(_a);
2089
+ exports.Agent = chunkU64IJDC5_cjs.__decorateElement(_init, 0, "Agent", _Agent_decorators, exports.Agent);
2090
+ chunkU64IJDC5_cjs.__runInitializers(_init, 1, exports.Agent);
2091
+
2092
+ // src/workflows/legacy/utils.ts
2093
+ return exports.Agent;
2094
+ })();
2095
+ // src/workflows/legacy/utils.ts
2096
+ function isErrorEvent(stateEvent) {
2097
+ return stateEvent.type.startsWith("xstate.error.actor.");
2098
+ }
2099
+ function isTransitionEvent(stateEvent) {
2100
+ return stateEvent.type.startsWith("xstate.done.actor.");
2101
+ }
2102
+ function isVariableReference(value) {
2103
+ return typeof value === "object" && "step" in value && "path" in value;
2104
+ }
2105
+ function getStepResult(result) {
2106
+ if (result?.status === "success") return result.output;
2107
+ return void 0;
2108
+ }
2109
+ function getSuspendedPaths({
2110
+ value,
2111
+ path,
2112
+ suspendedPaths
2113
+ }) {
2114
+ if (typeof value === "string") {
2115
+ if (value === "suspended") {
2116
+ suspendedPaths.add(path);
2117
+ }
2118
+ } else {
2119
+ Object.keys(value).forEach(key => getSuspendedPaths({
2120
+ value: value[key],
2121
+ path: path ? `${path}.${key}` : key,
2122
+ suspendedPaths
2123
+ }));
2124
+ }
2125
+ }
2126
+ function isFinalState(status) {
2127
+ return ["completed", "failed"].includes(status);
2128
+ }
2129
+ function isLimboState(status) {
2130
+ return status === "limbo";
2131
+ }
2132
+ function recursivelyCheckForFinalState({
2133
+ value,
2134
+ suspendedPaths,
2135
+ path
2136
+ }) {
2137
+ if (typeof value === "string") {
2138
+ return isFinalState(value) || isLimboState(value) || suspendedPaths.has(path);
2139
+ }
2140
+ return Object.keys(value).every(key => recursivelyCheckForFinalState({
2141
+ value: value[key],
2142
+ suspendedPaths,
2143
+ path: path ? `${path}.${key}` : key
2144
+ }));
2145
+ }
2146
+ function getActivePathsAndStatus(value) {
2147
+ const paths = [];
2148
+ const traverse = (current, path = []) => {
2149
+ for (const [key, value2] of Object.entries(current)) {
2150
+ const currentPath = [...path, key];
2151
+ if (typeof value2 === "string") {
2152
+ paths.push({
2153
+ stepPath: currentPath,
2154
+ stepId: key,
2155
+ status: value2
2156
+ });
2157
+ } else if (typeof value2 === "object" && value2 !== null) {
2158
+ traverse(value2, currentPath);
2159
+ }
2160
+ }
2161
+ };
2162
+ traverse(value);
2163
+ return paths;
2164
+ }
2165
+ function mergeChildValue(startStepId, parent, child) {
2166
+ const traverse = current => {
2167
+ const obj = {};
2168
+ for (const [key, value] of Object.entries(current)) {
2169
+ if (key === startStepId) {
2170
+ obj[key] = {
2171
+ ...child
2172
+ };
2173
+ } else if (typeof value === "string") {
2174
+ obj[key] = value;
2175
+ } else if (typeof value === "object" && value !== null) {
2176
+ obj[key] = traverse(value);
2177
+ }
2178
+ }
2179
+ return obj;
2180
+ };
2181
+ return traverse(parent);
2182
+ }
2183
+ var updateStepInHierarchy = (value, targetStepId) => {
2184
+ const result = {};
2185
+ for (const key of Object.keys(value)) {
2186
+ const currentValue = value[key];
2187
+ if (key === targetStepId) {
2188
+ result[key] = "pending";
2189
+ } else if (typeof currentValue === "object" && currentValue !== null) {
2190
+ result[key] = updateStepInHierarchy(currentValue, targetStepId);
2191
+ } else {
2192
+ result[key] = currentValue;
2193
+ }
2194
+ }
2195
+ return result;
2196
+ };
2197
+ function getResultActivePaths(state) {
2198
+ const activePaths = getActivePathsAndStatus(state.value);
2199
+ const activePathsAndStatus = activePaths.reduce((acc, curr) => {
2200
+ const entry = {
2201
+ status: curr.status,
2202
+ stepPath: curr.stepPath
2203
+ };
2204
+ if (curr.status === "suspended") {
2205
+ entry.suspendPayload = state.context.steps[curr.stepId].suspendPayload;
2206
+ entry.stepPath = curr.stepPath;
2207
+ }
2208
+ acc.set(curr.stepId, entry);
2209
+ return acc;
2210
+ }, /* @__PURE__ */new Map());
2211
+ return activePathsAndStatus;
2212
+ }
2213
+ function isWorkflow(step) {
2214
+ return step instanceof LegacyWorkflow;
2215
+ }
2216
+ function isAgent(step) {
2217
+ return step instanceof exports.Agent;
2218
+ }
2219
+ function resolveVariables({
2220
+ runId,
2221
+ logger,
2222
+ variables,
2223
+ context
2224
+ }) {
2225
+ const resolvedData = {};
2226
+ for (const [key, variable] of Object.entries(variables)) {
2227
+ const sourceData = variable.step === "trigger" ? context.triggerData : getStepResult(context.steps[variable.step.id ?? variable.step.name]);
2228
+ logger.debug(`Got source data for ${key} variable from ${variable.step === "trigger" ? "trigger" : variable.step.id ?? variable.step.name}`, {
2229
+ sourceData,
2230
+ path: variable.path,
2231
+ runId
2232
+ });
2233
+ if (!sourceData && variable.step !== "trigger") {
2234
+ resolvedData[key] = void 0;
2235
+ continue;
2236
+ }
2237
+ const value = variable.path === "" || variable.path === "." ? sourceData : radash.get(sourceData, variable.path);
2238
+ logger.debug(`Resolved variable ${key}`, {
2239
+ value,
2240
+ runId
2241
+ });
2242
+ resolvedData[key] = value;
2243
+ }
2244
+ return resolvedData;
2245
+ }
2246
+ function agentToStep(agent, {
2247
+ mastra
2248
+ } = {}) {
2249
+ return {
2250
+ id: agent.name,
2251
+ inputSchema: zod.z.object({
2252
+ prompt: zod.z.string(),
2253
+ resourceId: zod.z.string().optional(),
2254
+ threadId: zod.z.string().optional()
2255
+ }),
2256
+ outputSchema: zod.z.object({
2257
+ text: zod.z.string()
2258
+ }),
2259
+ execute: async ({
2260
+ context,
2261
+ runId,
2262
+ mastra: mastraFromExecute
2263
+ }) => {
2264
+ const realMastra = mastraFromExecute ?? mastra;
2265
+ if (!realMastra) {
2266
+ throw new Error("Mastra instance not found");
2267
+ }
2268
+ agent.__registerMastra(realMastra);
2269
+ agent.__registerPrimitives({
2270
+ logger: realMastra.getLogger(),
2271
+ telemetry: realMastra.getTelemetry()
2272
+ });
2273
+ const result = await agent.generate(context.inputData.prompt, {
2274
+ runId,
2275
+ resourceId: context.inputData.resourceId,
2276
+ threadId: context.inputData.threadId
2277
+ });
2278
+ return {
2279
+ text: result.text
2280
+ };
2281
+ }
2282
+ };
2283
+ }
2284
+ function workflowToStep(workflow, {
2285
+ mastra
2286
+ }) {
2287
+ workflow.setNested(true);
2288
+ return {
2289
+ id: workflow.name,
2290
+ workflow,
2291
+ workflowId: toCamelCaseWithRandomSuffix(workflow.name),
2292
+ execute: async ({
2293
+ context,
2294
+ suspend,
2295
+ emit,
2296
+ mastra: mastraFromExecute,
2297
+ runtimeContext
2298
+ }) => {
2299
+ const realMastra = mastraFromExecute ?? mastra;
2300
+ if (realMastra) {
2301
+ workflow.__registerMastra(realMastra);
2302
+ workflow.__registerPrimitives({
2303
+ logger: realMastra.getLogger(),
2304
+ telemetry: realMastra.getTelemetry()
2305
+ });
2306
+ }
2307
+ const run = context.isResume ? workflow.createRun({
2308
+ runId: context.isResume.runId
2309
+ }) : workflow.createRun();
2310
+ const unwatch = run.watch(state => {
2311
+ emit("state-update", workflow.name, state.results, {
2312
+ ...context,
2313
+ ...{
2314
+ [workflow.name]: state.results
2315
+ }
2316
+ });
2317
+ });
2318
+ const awaitedResult = context.isResume && context.isResume.stepId.includes(".") ? await run.resume({
2319
+ stepId: context.isResume.stepId.split(".").slice(1).join("."),
2320
+ context: context.inputData,
2321
+ runtimeContext
2322
+ }) : await run.start({
2323
+ triggerData: context.inputData,
2324
+ runtimeContext
2325
+ });
2326
+ unwatch();
2327
+ if (!awaitedResult) {
2328
+ throw new Error("LegacyWorkflow run failed");
2329
+ }
2330
+ if (awaitedResult.activePaths?.size > 0) {
2331
+ const suspendedStep = [...awaitedResult.activePaths.entries()].find(([, {
2332
+ status
2333
+ }]) => {
2334
+ return status === "suspended";
2335
+ });
2336
+ if (suspendedStep) {
2337
+ await suspend(suspendedStep[1].suspendPayload, {
2338
+ ...awaitedResult,
2339
+ runId: run.runId
2340
+ });
2341
+ }
2342
+ }
2343
+ return {
2344
+ ...awaitedResult,
2345
+ runId: run.runId
2346
+ };
2347
+ }
2348
+ };
2349
+ }
2350
+ function toCamelCaseWithRandomSuffix(str) {
2351
+ if (!str) return "";
2352
+ const normalizedStr = str.replace(/[-_]/g, " ");
2353
+ const words = normalizedStr.split(" ").filter(word => word.length > 0);
2354
+ const camelCase = words.map((word, index) => {
2355
+ word = word.replace(/[^a-zA-Z0-9]/g, "");
2356
+ if (index === 0) {
2357
+ return word.toLowerCase();
2358
+ }
2359
+ return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
2360
+ }).join("");
2361
+ const randomString = generateRandomLetters(3);
2362
+ return camelCase + randomString;
2363
+ }
2364
+ function generateRandomLetters(length) {
2365
+ const characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
2366
+ let result = "";
2367
+ for (let i = 0; i < length; i++) {
2368
+ const randomIndex = Math.floor(Math.random() * characters.length);
2369
+ result += characters.charAt(randomIndex);
2370
+ }
2371
+ return result;
2372
+ }
2373
+ function isConditionalKey(key) {
2374
+ return key.startsWith("__") && (key.includes("_if") || key.includes("_else"));
2375
+ }
2376
+ var Machine = class extends EventEmitter__default.default {
2377
+ logger;
2378
+ #mastra;
2379
+ #runtimeContext;
2380
+ #workflowInstance;
2381
+ #executionSpan;
2382
+ #stepGraph;
2383
+ #machine;
2384
+ #runId;
2385
+ #startStepId;
2386
+ name;
2387
+ #actor = null;
2388
+ #steps = {};
2389
+ #retryConfig;
2390
+ constructor({
2391
+ logger,
2392
+ mastra,
2393
+ runtimeContext,
2394
+ workflowInstance,
2395
+ executionSpan,
2396
+ name,
2397
+ runId,
2398
+ steps,
2399
+ stepGraph,
2400
+ retryConfig,
2401
+ startStepId
2402
+ }) {
2403
+ super();
2404
+ this.#mastra = mastra;
2405
+ this.#workflowInstance = workflowInstance;
2406
+ this.#runtimeContext = runtimeContext;
2407
+ this.#executionSpan = executionSpan;
2408
+ this.logger = logger;
2409
+ this.#runId = runId;
2410
+ this.#startStepId = startStepId;
2411
+ this.name = name;
2412
+ this.#stepGraph = stepGraph;
2413
+ this.#steps = steps;
2414
+ this.#retryConfig = retryConfig;
2415
+ this.initializeMachine();
2416
+ }
2417
+ get startStepId() {
2418
+ return this.#startStepId;
2419
+ }
2420
+ async execute({
2421
+ stepId,
2422
+ input,
2423
+ snapshot,
2424
+ resumeData
2425
+ } = {}) {
2426
+ if (snapshot) {
2427
+ this.logger.debug(`Workflow snapshot received`, {
2428
+ runId: this.#runId,
2429
+ snapshot
2430
+ });
2431
+ }
2432
+ const origSteps = input.steps;
2433
+ const isResumedInitialStep = this.#stepGraph?.initial[0]?.step?.id === stepId;
2434
+ if (isResumedInitialStep) {
2435
+ snapshot = void 0;
2436
+ input.steps = {};
2437
+ }
2438
+ this.logger.debug(`Machine input prepared`, {
2439
+ runId: this.#runId,
2440
+ input
2441
+ });
2442
+ const actorSnapshot = snapshot ? {
2443
+ ...snapshot,
2444
+ context: {
2445
+ ...input,
2446
+ inputData: {
2447
+ ...(snapshot?.context?.inputData || {}),
2448
+ ...resumeData
2449
+ },
2450
+ // ts-ignore is needed here because our snapshot types don't really match xstate snapshot types right now. We should fix this in general.
2451
+ // @ts-ignore
2452
+ isResume: {
2453
+ runId: snapshot?.context?.steps[stepId.split(".")?.[0]]?.output?.runId || this.#runId,
2454
+ stepId
2455
+ }
2456
+ }
2457
+ } : void 0;
2458
+ this.logger.debug(`Creating actor with configuration`, {
2459
+ input,
2460
+ actorSnapshot,
2461
+ runId: this.#runId,
2462
+ machineStates: this.#machine.config.states
2463
+ });
2464
+ this.#actor = xstate.createActor(this.#machine, {
2465
+ inspect: inspectionEvent => {
2466
+ this.logger.debug("XState inspection event", {
2467
+ type: inspectionEvent.type,
2468
+ event: inspectionEvent.event,
2469
+ runId: this.#runId
2470
+ });
2471
+ },
2472
+ input: {
2473
+ ...input,
2474
+ inputData: {
2475
+ ...(snapshot?.context?.inputData || {}),
2476
+ ...resumeData
2477
+ }
2478
+ },
2479
+ snapshot: actorSnapshot
2480
+ });
2481
+ this.#actor.start();
2482
+ if (stepId) {
2483
+ this.#actor.send({
2484
+ type: "RESET_TO_PENDING",
2485
+ stepId
2486
+ });
2487
+ }
2488
+ this.logger.debug("Actor started", {
2489
+ runId: this.#runId
2490
+ });
2491
+ return new Promise((resolve, reject) => {
2492
+ if (!this.#actor) {
2493
+ this.logger.error("Actor not initialized", {
2494
+ runId: this.#runId
2495
+ });
2496
+ const e = new Error("Actor not initialized");
2497
+ this.#executionSpan?.recordException(e);
2498
+ this.#executionSpan?.end();
2499
+ reject(e);
2500
+ return;
2501
+ }
2502
+ const suspendedPaths = /* @__PURE__ */new Set();
2503
+ this.#actor.subscribe(async state => {
2504
+ this.emit("state-update", this.#startStepId, state);
2505
+ getSuspendedPaths({
2506
+ value: state.value,
2507
+ path: "",
2508
+ suspendedPaths
2509
+ });
2510
+ const allStatesValue = state.value;
2511
+ const allStatesComplete = recursivelyCheckForFinalState({
2512
+ value: allStatesValue,
2513
+ suspendedPaths,
2514
+ path: ""
2515
+ });
2516
+ this.logger.debug("State completion check", {
2517
+ allStatesComplete,
2518
+ suspendedPaths: Array.from(suspendedPaths),
2519
+ runId: this.#runId
2520
+ });
2521
+ if (!allStatesComplete) {
2522
+ this.logger.debug("Not all states complete", {
2523
+ allStatesComplete,
2524
+ suspendedPaths: Array.from(suspendedPaths),
2525
+ runId: this.#runId
2526
+ });
2527
+ return;
2528
+ }
2529
+ try {
2530
+ this.logger.debug("All states complete", {
2531
+ runId: this.#runId
2532
+ });
2533
+ await this.#workflowInstance.persistWorkflowSnapshot();
2534
+ this.#cleanup();
2535
+ this.#executionSpan?.end();
2536
+ resolve({
2537
+ runId: this.#runId,
2538
+ results: isResumedInitialStep ? {
2539
+ ...origSteps,
2540
+ ...state.context.steps
2541
+ } : state.context.steps,
2542
+ activePaths: getResultActivePaths(state),
2543
+ timestamp: Date.now()
2544
+ });
2545
+ } catch (error) {
2546
+ this.logger.debug("Failed to persist final snapshot", {
2547
+ error
2548
+ });
2549
+ this.#cleanup();
2550
+ this.#executionSpan?.end();
2551
+ resolve({
2552
+ runId: this.#runId,
2553
+ results: isResumedInitialStep ? {
2554
+ ...origSteps,
2555
+ ...state.context.steps
2556
+ } : state.context.steps,
2557
+ activePaths: getResultActivePaths(state),
2558
+ timestamp: Date.now()
2559
+ });
2560
+ }
2561
+ });
2562
+ });
2563
+ }
2564
+ #cleanup() {
2565
+ if (this.#actor) {
2566
+ this.#actor.stop();
2567
+ this.#actor = null;
2568
+ }
2569
+ this.removeAllListeners();
2570
+ }
2571
+ #makeDelayMap() {
2572
+ const delayMap = {};
2573
+ Object.keys(this.#steps).forEach(stepId => {
2574
+ delayMap[stepId] = this.#steps[stepId]?.step?.retryConfig?.delay || this.#retryConfig?.delay || 1e3;
2575
+ });
2576
+ return delayMap;
2577
+ }
2578
+ #getDefaultActions() {
2579
+ return {
2580
+ updateStepResult: xstate.assign({
2581
+ steps: ({
2582
+ context,
2583
+ event
2584
+ }) => {
2585
+ if (!isTransitionEvent(event)) return context.steps;
2586
+ const {
2587
+ stepId,
2588
+ result
2589
+ } = event.output;
2590
+ return {
2591
+ ...context.steps,
2592
+ [stepId]: {
2593
+ status: "success",
2594
+ output: result
2595
+ }
2596
+ };
2597
+ }
2598
+ }),
2599
+ setStepError: xstate.assign({
2600
+ steps: ({
2601
+ context,
2602
+ event
2603
+ }, params) => {
2604
+ if (!isErrorEvent(event)) return context.steps;
2605
+ const {
2606
+ stepId
2607
+ } = params;
2608
+ if (!stepId) return context.steps;
2609
+ return {
2610
+ ...context.steps,
2611
+ [stepId]: {
2612
+ status: "failed",
2613
+ error: event.error.message
2614
+ }
2615
+ };
2616
+ }
2617
+ }),
2618
+ notifyStepCompletion: async (_, params) => {
2619
+ const {
2620
+ stepId
2621
+ } = params;
2622
+ this.logger.debug(`Step ${stepId} completed`);
2623
+ },
2624
+ snapshotStep: xstate.assign({
2625
+ _snapshot: ({}, params) => {
2626
+ const {
2627
+ stepId
2628
+ } = params;
2629
+ return {
2630
+ stepId
2631
+ };
2632
+ }
2633
+ }),
2634
+ persistSnapshot: async ({
2635
+ context
2636
+ }) => {
2637
+ if (context._snapshot) {
2638
+ await this.#workflowInstance.persistWorkflowSnapshot();
2639
+ }
2640
+ return;
2641
+ },
2642
+ decrementAttemptCount: xstate.assign({
2643
+ attempts: ({
2644
+ context,
2645
+ event
2646
+ }, params) => {
2647
+ if (!isTransitionEvent(event)) return context.attempts;
2648
+ const {
2649
+ stepId
2650
+ } = params;
2651
+ const attemptCount = context.attempts[stepId];
2652
+ if (attemptCount === void 0) return context.attempts;
2653
+ return {
2654
+ ...context.attempts,
2655
+ [stepId]: attemptCount - 1
2656
+ };
2657
+ }
2658
+ })
2659
+ };
2660
+ }
2661
+ #getDefaultActors() {
2662
+ return {
2663
+ resolverFunction: xstate.fromPromise(async ({
2664
+ input
2665
+ }) => {
2666
+ const {
2667
+ stepNode,
2668
+ context
2669
+ } = input;
2670
+ const attemptCount = context.attempts[stepNode.id];
2671
+ const resolvedData = this.#resolveVariables({
2672
+ stepConfig: stepNode.config,
2673
+ context,
2674
+ stepId: stepNode.id
2675
+ });
2676
+ this.logger.debug(`Resolved variables for ${stepNode.id}`, {
2677
+ resolvedData,
2678
+ runId: this.#runId
2679
+ });
2680
+ const logger = this.logger;
2681
+ let mastraProxy = void 0;
2682
+ if (this.#mastra) {
2683
+ mastraProxy = chunkLBUQ6YNU_cjs.createMastraProxy({
2684
+ mastra: this.#mastra,
2685
+ logger
2686
+ });
2687
+ }
2688
+ let result = void 0;
2689
+ try {
2690
+ result = await stepNode.config.handler({
2691
+ context: {
2692
+ ...context,
2693
+ inputData: {
2694
+ ...(context?.inputData || {}),
2695
+ ...resolvedData
2696
+ },
2697
+ getStepResult: stepId => {
2698
+ const resolvedStepId = typeof stepId === "string" ? stepId : stepId.id;
2699
+ if (resolvedStepId === "trigger") {
2700
+ return context.triggerData;
2701
+ }
2702
+ const result2 = context.steps[resolvedStepId];
2703
+ if (result2 && result2.status === "success") {
2704
+ return result2.output;
2705
+ }
2706
+ return void 0;
2707
+ }
2708
+ },
2709
+ emit: (event, ...args) => {
2710
+ this.emit(event, ...args);
2711
+ },
2712
+ suspend: async (payload, softSuspend) => {
2713
+ await this.#workflowInstance.suspend(stepNode.id, this);
2714
+ if (this.#actor) {
2715
+ context.steps[stepNode.id] = {
2716
+ status: "suspended",
2717
+ suspendPayload: payload,
2718
+ output: softSuspend
2719
+ };
2720
+ this.logger.debug(`Sending SUSPENDED event for step ${stepNode.id}`);
2721
+ this.#actor?.send({
2722
+ type: "SUSPENDED",
2723
+ suspendPayload: payload,
2724
+ stepId: stepNode.id,
2725
+ softSuspend
2726
+ });
2727
+ } else {
2728
+ this.logger.debug(`Actor not available for step ${stepNode.id}`);
2729
+ }
2730
+ },
2731
+ runId: this.#runId,
2732
+ mastra: mastraProxy,
2733
+ runtimeContext: this.#runtimeContext
2734
+ });
2735
+ } catch (error) {
2736
+ this.logger.debug(`Step ${stepNode.id} failed`, {
2737
+ stepId: stepNode.id,
2738
+ error,
2739
+ runId: this.#runId
2740
+ });
2741
+ this.logger.debug(`Attempt count for step ${stepNode.id}`, {
2742
+ attemptCount,
2743
+ attempts: context.attempts,
2744
+ runId: this.#runId,
2745
+ stepId: stepNode.id
2746
+ });
2747
+ if (!attemptCount || attemptCount < 0) {
2748
+ return {
2749
+ type: "STEP_FAILED",
2750
+ error: error instanceof Error ? error.message : `Step:${stepNode.id} failed with error: ${error}`,
2751
+ stepId: stepNode.id
2752
+ };
2753
+ }
2754
+ return {
2755
+ type: "STEP_WAITING",
2756
+ stepId: stepNode.id
2757
+ };
2758
+ }
2759
+ this.logger.debug(`Step ${stepNode.id} result`, {
2760
+ stepId: stepNode.id,
2761
+ result,
2762
+ runId: this.#runId
2763
+ });
2764
+ return {
2765
+ type: "STEP_SUCCESS",
2766
+ result,
2767
+ stepId: stepNode.id
2768
+ };
2769
+ }),
2770
+ conditionCheck: xstate.fromPromise(async ({
2771
+ input
2772
+ }) => {
2773
+ const {
2774
+ context,
2775
+ stepNode
2776
+ } = input;
2777
+ const stepConfig = stepNode.config;
2778
+ this.logger.debug(`Checking conditions for step ${stepNode.id}`, {
2779
+ stepId: stepNode.id,
2780
+ runId: this.#runId
2781
+ });
2782
+ if (!stepConfig?.when) {
2783
+ return {
2784
+ type: "CONDITIONS_MET"
2785
+ };
2786
+ }
2787
+ this.logger.debug(`Checking conditions for step ${stepNode.id}`, {
2788
+ stepId: stepNode.id,
2789
+ runId: this.#runId
2790
+ });
2791
+ if (typeof stepConfig?.when === "function") {
2792
+ let conditionMet = await stepConfig.when({
2793
+ context: {
2794
+ ...context,
2795
+ getStepResult: stepId => {
2796
+ const resolvedStepId = typeof stepId === "string" ? stepId : stepId.id;
2797
+ if (resolvedStepId === "trigger") {
2798
+ return context.triggerData;
2799
+ }
2800
+ const result = context.steps[resolvedStepId];
2801
+ if (result && result.status === "success") {
2802
+ return result.output;
2803
+ }
2804
+ return void 0;
2805
+ }
2806
+ },
2807
+ mastra: this.#mastra
2808
+ });
2809
+ if (conditionMet === "abort" /* ABORT */) {
2810
+ conditionMet = false;
2811
+ } else if (conditionMet === "continue_failed" /* CONTINUE_FAILED */) {
2812
+ return {
2813
+ type: "CONDITIONS_SKIP_TO_COMPLETED"
2814
+ };
2815
+ } else if (conditionMet === "limbo" /* LIMBO */) {
2816
+ return {
2817
+ type: "CONDITIONS_LIMBO"
2818
+ };
2819
+ } else if (conditionMet) {
2820
+ this.logger.debug(`Condition met for step ${stepNode.id}`, {
2821
+ stepId: stepNode.id,
2822
+ runId: this.#runId
2823
+ });
2824
+ return {
2825
+ type: "CONDITIONS_MET"
2826
+ };
2827
+ }
2828
+ if (isConditionalKey(stepNode.id)) {
2829
+ return {
2830
+ type: "CONDITIONS_LIMBO"
2831
+ };
2832
+ }
2833
+ return this.#workflowInstance.hasSubscribers(stepNode.id) ? {
2834
+ type: "CONDITIONS_SKIPPED"
2835
+ } : {
2836
+ type: "CONDITIONS_LIMBO"
2837
+ };
2838
+ } else {
2839
+ const conditionMet = this.#evaluateCondition(stepConfig.when, context);
2840
+ if (!conditionMet) {
2841
+ return {
2842
+ type: "CONDITION_FAILED",
2843
+ error: `Step:${stepNode.id} condition check failed`
2844
+ };
2845
+ }
2846
+ }
2847
+ return {
2848
+ type: "CONDITIONS_MET"
2849
+ };
2850
+ }),
2851
+ spawnSubscriberFunction: xstate.fromPromise(async ({
2852
+ input
2853
+ }) => {
2854
+ const {
2855
+ parentStepId,
2856
+ context
2857
+ } = input;
2858
+ const result = await this.#workflowInstance.runMachine(parentStepId, context, this.#runtimeContext);
2859
+ return Promise.resolve({
2860
+ steps: result.reduce((acc, r) => {
2861
+ return {
2862
+ ...acc,
2863
+ ...r?.results
2864
+ };
2865
+ }, {})
2866
+ });
2867
+ })
2868
+ };
2869
+ }
2870
+ #resolveVariables({
2871
+ stepConfig,
2872
+ context,
2873
+ stepId
2874
+ }) {
2875
+ this.logger.debug(`Resolving variables for step ${stepId}`, {
2876
+ stepId,
2877
+ runId: this.#runId
2878
+ });
2879
+ const resolvedData = {};
2880
+ for (const [key, variable] of Object.entries(stepConfig.data)) {
2881
+ const sourceData = variable.step === "trigger" ? context.triggerData : getStepResult(context.steps[variable.step.id]);
2882
+ this.logger.debug(`Got source data for ${key} variable from ${variable.step === "trigger" ? "trigger" : variable.step.id}`, {
2883
+ sourceData,
2884
+ path: variable.path,
2885
+ runId: this.#runId
2886
+ });
2887
+ if (!sourceData && variable.step !== "trigger") {
2888
+ resolvedData[key] = void 0;
2889
+ continue;
2890
+ }
2891
+ const value = variable.path === "" || variable.path === "." ? sourceData : radash.get(sourceData, variable.path);
2892
+ this.logger.debug(`Resolved variable ${key}`, {
2893
+ value,
2894
+ runId: this.#runId
2895
+ });
2896
+ resolvedData[key] = value;
2897
+ }
2898
+ return resolvedData;
2899
+ }
2900
+ initializeMachine() {
2901
+ const machine = xstate.setup({
2902
+ types: {},
2903
+ delays: this.#makeDelayMap(),
2904
+ actions: this.#getDefaultActions(),
2905
+ actors: this.#getDefaultActors()
2906
+ }).createMachine({
2907
+ id: this.name,
2908
+ type: "parallel",
2909
+ context: ({
2910
+ input
2911
+ }) => ({
2912
+ ...input
2913
+ }),
2914
+ states: this.#buildStateHierarchy(this.#stepGraph)
2915
+ });
2916
+ this.#machine = machine;
2917
+ return machine;
2918
+ }
2919
+ #buildStateHierarchy(stepGraph) {
2920
+ const states = {};
2921
+ stepGraph.initial.forEach(stepNode => {
2922
+ const nextSteps = [...(stepGraph[stepNode.id] || [])];
2923
+ states[stepNode.id] = {
2924
+ ...this.#buildBaseState(stepNode, nextSteps)
2925
+ };
2926
+ });
2927
+ return states;
2928
+ }
2929
+ #buildBaseState(stepNode, nextSteps = []) {
2930
+ const nextStep = nextSteps.shift();
2931
+ return {
2932
+ initial: "pending",
2933
+ on: {
2934
+ RESET_TO_PENDING: {
2935
+ target: ".pending"
2936
+ // Note the dot to target child state
2937
+ }
2938
+ },
2939
+ states: {
2940
+ pending: {
2941
+ entry: () => {
2942
+ this.logger.debug(`Step ${stepNode.id} pending`, {
2943
+ stepId: stepNode.id,
2944
+ runId: this.#runId
2945
+ });
2946
+ },
2947
+ exit: () => {
2948
+ this.logger.debug(`Step ${stepNode.id} finished pending`, {
2949
+ stepId: stepNode.id,
2950
+ runId: this.#runId
2951
+ });
2952
+ },
2953
+ invoke: {
2954
+ src: "conditionCheck",
2955
+ input: ({
2956
+ context
2957
+ }) => {
2958
+ return {
2959
+ context,
2960
+ stepNode
2961
+ };
2962
+ },
2963
+ onDone: [{
2964
+ guard: ({
2965
+ event
2966
+ }) => {
2967
+ return event.output.type === "SUSPENDED";
2968
+ },
2969
+ target: "suspended",
2970
+ actions: [xstate.assign({
2971
+ steps: ({
2972
+ context,
2973
+ event
2974
+ }) => {
2975
+ if (event.output.type !== "SUSPENDED") return context.steps;
2976
+ if (event.output.softSuspend) {
2977
+ return {
2978
+ ...context.steps,
2979
+ [stepNode.id]: {
2980
+ status: "suspended",
2981
+ ...(context.steps?.[stepNode.id] || {}),
2982
+ output: event.output.softSuspend
2983
+ }
2984
+ };
2985
+ }
2986
+ return {
2987
+ ...context.steps,
2988
+ [stepNode.id]: {
2989
+ status: "suspended",
2990
+ ...(context.steps?.[stepNode.id] || {})
2991
+ }
2992
+ };
2993
+ },
2994
+ attempts: ({
2995
+ context,
2996
+ event
2997
+ }) => {
2998
+ if (event.output.type !== "SUSPENDED") return context.attempts;
2999
+ return {
3000
+ ...context.attempts,
3001
+ [stepNode.id]: stepNode.step.retryConfig?.attempts || 0
3002
+ };
3003
+ }
3004
+ })]
3005
+ }, {
3006
+ guard: ({
3007
+ event
3008
+ }) => {
3009
+ return event.output.type === "WAITING";
3010
+ },
3011
+ target: "waiting",
3012
+ actions: [{
3013
+ type: "decrementAttemptCount",
3014
+ params: {
3015
+ stepId: stepNode.id
3016
+ }
3017
+ }, xstate.assign({
3018
+ steps: ({
3019
+ context,
3020
+ event
3021
+ }) => {
3022
+ if (event.output.type !== "WAITING") return context.steps;
3023
+ return {
3024
+ ...context.steps,
3025
+ [stepNode.id]: {
3026
+ status: "waiting"
3027
+ }
3028
+ };
3029
+ }
3030
+ })]
3031
+ }, {
3032
+ guard: ({
3033
+ event
3034
+ }) => {
3035
+ return event.output.type === "CONDITIONS_MET";
3036
+ },
3037
+ target: "executing"
3038
+ }, {
3039
+ guard: ({
3040
+ event
3041
+ }) => {
3042
+ return event.output.type === "CONDITIONS_SKIP_TO_COMPLETED";
3043
+ },
3044
+ target: "completed"
3045
+ }, {
3046
+ guard: ({
3047
+ event
3048
+ }) => {
3049
+ return event.output.type === "CONDITIONS_SKIPPED";
3050
+ },
3051
+ actions: xstate.assign({
3052
+ steps: ({
3053
+ context
3054
+ }) => {
3055
+ const newStep = {
3056
+ ...context.steps,
3057
+ [stepNode.id]: {
3058
+ status: "skipped"
3059
+ }
3060
+ };
3061
+ this.logger.debug(`Step ${stepNode.id} skipped`, {
3062
+ stepId: stepNode.id,
3063
+ runId: this.#runId
3064
+ });
3065
+ return newStep;
3066
+ }
3067
+ }),
3068
+ target: "runningSubscribers"
3069
+ }, {
3070
+ guard: ({
3071
+ event
3072
+ }) => {
3073
+ return event.output.type === "CONDITIONS_LIMBO";
3074
+ },
3075
+ target: "limbo",
3076
+ actions: xstate.assign({
3077
+ steps: ({
3078
+ context
3079
+ }) => {
3080
+ const newStep = {
3081
+ ...context.steps,
3082
+ [stepNode.id]: {
3083
+ status: "skipped"
3084
+ }
3085
+ };
3086
+ this.logger.debug(`Step ${stepNode.id} skipped`, {
3087
+ stepId: stepNode.id,
3088
+ runId: this.#runId
3089
+ });
3090
+ return newStep;
3091
+ }
3092
+ })
3093
+ }, {
3094
+ guard: ({
3095
+ event
3096
+ }) => {
3097
+ return event.output.type === "CONDITION_FAILED";
3098
+ },
3099
+ target: "failed",
3100
+ actions: xstate.assign({
3101
+ steps: ({
3102
+ context,
3103
+ event
3104
+ }) => {
3105
+ if (event.output.type !== "CONDITION_FAILED") return context.steps;
3106
+ this.logger.debug(`Workflow condition check failed`, {
3107
+ error: event.output.error,
3108
+ stepId: stepNode.id
3109
+ });
3110
+ return {
3111
+ ...context.steps,
3112
+ [stepNode.id]: {
3113
+ status: "failed",
3114
+ error: event.output.error
3115
+ }
3116
+ };
3117
+ }
3118
+ })
3119
+ }]
3120
+ }
3121
+ },
3122
+ waiting: {
3123
+ entry: () => {
3124
+ this.logger.debug(`Step ${stepNode.id} waiting`, {
3125
+ stepId: stepNode.id,
3126
+ timestamp: (/* @__PURE__ */new Date()).toISOString(),
3127
+ runId: this.#runId
3128
+ });
3129
+ },
3130
+ exit: () => {
3131
+ this.logger.debug(`Step ${stepNode.id} finished waiting`, {
3132
+ stepId: stepNode.id,
3133
+ timestamp: (/* @__PURE__ */new Date()).toISOString(),
3134
+ runId: this.#runId
3135
+ });
3136
+ },
3137
+ after: {
3138
+ [stepNode.id]: {
3139
+ target: "pending"
3140
+ }
3141
+ }
3142
+ },
3143
+ limbo: {
3144
+ // no target, will stay in limbo indefinitely
3145
+ entry: () => {
3146
+ this.logger.debug(`Step ${stepNode.id} limbo`, {
3147
+ stepId: stepNode.id,
3148
+ timestamp: (/* @__PURE__ */new Date()).toISOString(),
3149
+ runId: this.#runId
3150
+ });
3151
+ },
3152
+ exit: () => {
3153
+ this.logger.debug(`Step ${stepNode.id} finished limbo`, {
3154
+ stepId: stepNode.id,
3155
+ timestamp: (/* @__PURE__ */new Date()).toISOString(),
3156
+ runId: this.#runId
3157
+ });
3158
+ }
3159
+ },
3160
+ suspended: {
3161
+ type: "final",
3162
+ entry: [() => {
3163
+ this.logger.debug(`Step ${stepNode.id} suspended`, {
3164
+ stepId: stepNode.id,
3165
+ runId: this.#runId
3166
+ });
3167
+ }, xstate.assign({
3168
+ steps: ({
3169
+ context,
3170
+ event
3171
+ }) => {
3172
+ return {
3173
+ ...context.steps,
3174
+ [stepNode.id]: {
3175
+ ...(context?.steps?.[stepNode.id] || {}),
3176
+ status: "suspended",
3177
+ suspendPayload: event.type === "SUSPENDED" ? event.suspendPayload : void 0,
3178
+ output: event.type === "SUSPENDED" ? event.softSuspend : void 0
3179
+ }
3180
+ };
3181
+ }
3182
+ })]
3183
+ },
3184
+ executing: {
3185
+ entry: () => {
3186
+ this.logger.debug(`Step ${stepNode.id} executing`, {
3187
+ stepId: stepNode.id,
3188
+ runId: this.#runId
3189
+ });
3190
+ },
3191
+ on: {
3192
+ SUSPENDED: {
3193
+ target: "suspended",
3194
+ actions: [xstate.assign({
3195
+ steps: ({
3196
+ context,
3197
+ event
3198
+ }) => {
3199
+ return {
3200
+ ...context.steps,
3201
+ [stepNode.id]: {
3202
+ status: "suspended",
3203
+ suspendPayload: event.type === "SUSPENDED" ? event.suspendPayload : void 0,
3204
+ output: event.type === "SUSPENDED" ? event.softSuspend : void 0
3205
+ }
3206
+ };
3207
+ }
3208
+ })]
3209
+ }
3210
+ },
3211
+ invoke: {
3212
+ src: "resolverFunction",
3213
+ input: ({
3214
+ context
3215
+ }) => ({
3216
+ context,
3217
+ stepNode
3218
+ }),
3219
+ onDone: [{
3220
+ guard: ({
3221
+ event
3222
+ }) => {
3223
+ return event.output.type === "STEP_FAILED";
3224
+ },
3225
+ target: "failed",
3226
+ actions: xstate.assign({
3227
+ steps: ({
3228
+ context,
3229
+ event
3230
+ }) => {
3231
+ if (event.output.type !== "STEP_FAILED") return context.steps;
3232
+ const newStep = {
3233
+ ...context.steps,
3234
+ [stepNode.id]: {
3235
+ status: "failed",
3236
+ error: event.output.error
3237
+ }
3238
+ };
3239
+ this.logger.debug(`Step ${stepNode.id} failed`, {
3240
+ error: event.output.error,
3241
+ stepId: stepNode.id
3242
+ });
3243
+ return newStep;
3244
+ }
3245
+ })
3246
+ }, {
3247
+ guard: ({
3248
+ event
3249
+ }) => {
3250
+ return event.output.type === "STEP_SUCCESS";
3251
+ },
3252
+ actions: [({
3253
+ event
3254
+ }) => {
3255
+ this.logger.debug(`Step ${stepNode.id} finished executing`, {
3256
+ stepId: stepNode.id,
3257
+ output: event.output,
3258
+ runId: this.#runId
3259
+ });
3260
+ }, {
3261
+ type: "updateStepResult",
3262
+ params: {
3263
+ stepId: stepNode.id
3264
+ }
3265
+ }, {
3266
+ type: "spawnSubscribers",
3267
+ params: {
3268
+ stepId: stepNode.id
3269
+ }
3270
+ }],
3271
+ target: "runningSubscribers"
3272
+ }, {
3273
+ guard: ({
3274
+ event
3275
+ }) => {
3276
+ return event.output.type === "STEP_WAITING";
3277
+ },
3278
+ target: "waiting",
3279
+ actions: [{
3280
+ type: "decrementAttemptCount",
3281
+ params: {
3282
+ stepId: stepNode.id
3283
+ }
3284
+ }, xstate.assign({
3285
+ steps: ({
3286
+ context,
3287
+ event
3288
+ }) => {
3289
+ if (event.output.type !== "STEP_WAITING") return context.steps;
3290
+ return {
3291
+ ...context.steps,
3292
+ [stepNode.id]: {
3293
+ status: "waiting"
3294
+ }
3295
+ };
3296
+ }
3297
+ })]
3298
+ }],
3299
+ onError: {
3300
+ target: "failed",
3301
+ actions: [{
3302
+ type: "setStepError",
3303
+ params: {
3304
+ stepId: stepNode.id
3305
+ }
3306
+ }]
3307
+ }
3308
+ }
3309
+ },
3310
+ runningSubscribers: {
3311
+ entry: () => {
3312
+ this.logger.debug(`Step ${stepNode.id} running subscribers`, {
3313
+ stepId: stepNode.id,
3314
+ runId: this.#runId
3315
+ });
3316
+ },
3317
+ exit: () => {
3318
+ this.logger.debug(`Step ${stepNode.id} finished running subscribers`, {
3319
+ stepId: stepNode.id,
3320
+ runId: this.#runId
3321
+ });
3322
+ },
3323
+ invoke: {
3324
+ src: "spawnSubscriberFunction",
3325
+ input: ({
3326
+ context
3327
+ }) => ({
3328
+ parentStepId: stepNode.id,
3329
+ context
3330
+ }),
3331
+ onDone: {
3332
+ target: nextStep ? nextStep.id : "completed",
3333
+ actions: [xstate.assign({
3334
+ steps: ({
3335
+ context,
3336
+ event
3337
+ }) => ({
3338
+ ...context.steps,
3339
+ ...event.output.steps
3340
+ })
3341
+ }), () => this.logger.debug(`Subscriber execution completed`, {
3342
+ stepId: stepNode.id
3343
+ })]
3344
+ },
3345
+ onError: {
3346
+ target: nextStep ? nextStep.id : "completed",
3347
+ actions: ({
3348
+ event
3349
+ }) => {
3350
+ this.logger.debug(`Subscriber execution failed`, {
3351
+ error: event.error,
3352
+ stepId: stepNode.id
3353
+ });
3354
+ }
3355
+ }
3356
+ }
3357
+ },
3358
+ completed: {
3359
+ type: "final",
3360
+ entry: [{
3361
+ type: "notifyStepCompletion",
3362
+ params: {
3363
+ stepId: stepNode.id
3364
+ }
3365
+ }, {
3366
+ type: "snapshotStep",
3367
+ params: {
3368
+ stepId: stepNode.id
3369
+ }
3370
+ }, {
3371
+ type: "persistSnapshot"
3372
+ }]
3373
+ },
3374
+ failed: {
3375
+ type: "final",
3376
+ entry: [{
3377
+ type: "notifyStepCompletion",
3378
+ params: {
3379
+ stepId: stepNode.id
3380
+ }
3381
+ }, {
3382
+ type: "snapshotStep",
3383
+ params: {
3384
+ stepId: stepNode.id
3385
+ }
3386
+ }, {
3387
+ type: "persistSnapshot"
3388
+ }]
3389
+ },
3390
+ // build chain of next steps recursively
3391
+ ...(nextStep ? {
3392
+ [nextStep.id]: {
3393
+ ...this.#buildBaseState(nextStep, nextSteps)
3394
+ }
3395
+ } : {})
3396
+ }
3397
+ };
3398
+ }
3399
+ #evaluateCondition(condition, context) {
3400
+ let andBranchResult = true;
3401
+ let baseResult = true;
3402
+ let orBranchResult = true;
3403
+ const simpleCondition = Object.entries(condition).find(([key]) => key.includes("."));
3404
+ if (simpleCondition) {
3405
+ const [key, queryValue] = simpleCondition;
3406
+ const [stepId, ...pathParts] = key.split(".");
3407
+ const path = pathParts.join(".");
3408
+ const sourceData = stepId === "trigger" ? context.triggerData : getStepResult(context.steps[stepId]);
3409
+ this.logger.debug(`Got condition data from step ${stepId}`, {
3410
+ stepId,
3411
+ sourceData,
3412
+ runId: this.#runId
3413
+ });
3414
+ if (!sourceData) {
3415
+ return false;
3416
+ }
3417
+ let value = radash.get(sourceData, path);
3418
+ if (stepId !== "trigger" && path === "status" && !value) {
3419
+ value = "success";
3420
+ }
3421
+ if (typeof queryValue === "object" && queryValue !== null) {
3422
+ baseResult = sift__default.default(queryValue)(value);
3423
+ } else {
3424
+ baseResult = value === queryValue;
3425
+ }
3426
+ }
3427
+ if ("ref" in condition) {
3428
+ const {
3429
+ ref,
3430
+ query
3431
+ } = condition;
3432
+ const sourceData = ref.step === "trigger" ? context.triggerData : getStepResult(context.steps[ref.step.id]);
3433
+ this.logger.debug(`Got condition data from ${ref.step === "trigger" ? "trigger" : ref.step.id}`, {
3434
+ sourceData,
3435
+ runId: this.#runId
3436
+ });
3437
+ if (!sourceData) {
3438
+ return false;
3439
+ }
3440
+ let value = radash.get(sourceData, ref.path);
3441
+ if (ref.step !== "trigger" && ref.path === "status" && !value) {
3442
+ value = "success";
3443
+ }
3444
+ baseResult = sift__default.default(query)(value);
3445
+ }
3446
+ if ("and" in condition) {
3447
+ andBranchResult = condition.and.every(cond => this.#evaluateCondition(cond, context));
3448
+ this.logger.debug(`Evaluated AND condition`, {
3449
+ andBranchResult,
3450
+ runId: this.#runId
3451
+ });
3452
+ }
3453
+ if ("or" in condition) {
3454
+ orBranchResult = condition.or.some(cond => this.#evaluateCondition(cond, context));
3455
+ this.logger.debug(`Evaluated OR condition`, {
3456
+ orBranchResult,
3457
+ runId: this.#runId
3458
+ });
3459
+ }
3460
+ if ("not" in condition) {
3461
+ baseResult = !this.#evaluateCondition(condition.not, context);
3462
+ this.logger.debug(`Evaluated NOT condition`, {
3463
+ baseResult,
3464
+ runId: this.#runId
3465
+ });
3466
+ }
3467
+ const finalResult = baseResult && andBranchResult && orBranchResult;
3468
+ this.logger.debug(`Evaluated condition`, {
3469
+ finalResult,
3470
+ runId: this.#runId
3471
+ });
3472
+ return finalResult;
3473
+ }
3474
+ getSnapshot() {
3475
+ const snapshot = this.#actor?.getSnapshot();
3476
+ return snapshot;
3477
+ }
3478
+ };
3479
+
3480
+ // src/workflows/legacy/workflow-instance.ts
3481
+ var WorkflowInstance = class {
3482
+ name;
3483
+ #mastra;
3484
+ #machines = {};
3485
+ logger;
3486
+ #steps = {};
3487
+ #stepGraph;
3488
+ #stepSubscriberGraph = {};
3489
+ #retryConfig;
3490
+ events;
3491
+ #runId;
3492
+ #state = null;
3493
+ #executionSpan;
3494
+ #onStepTransition = /* @__PURE__ */new Set();
3495
+ #onFinish;
3496
+ #resultMapping;
3497
+ // indexed by stepId
3498
+ #suspendedMachines = {};
3499
+ // {step1&&step2: {step1: true, step2: true}}
3500
+ #compoundDependencies = {};
3501
+ constructor({
3502
+ name,
3503
+ logger,
3504
+ steps,
3505
+ runId,
3506
+ retryConfig,
3507
+ mastra,
3508
+ stepGraph,
3509
+ stepSubscriberGraph,
3510
+ onFinish,
3511
+ onStepTransition,
3512
+ resultMapping,
3513
+ events
3514
+ }) {
3515
+ this.name = name;
3516
+ this.logger = logger;
3517
+ this.#steps = steps;
3518
+ this.#stepGraph = stepGraph;
3519
+ this.#stepSubscriberGraph = stepSubscriberGraph;
3520
+ this.#retryConfig = retryConfig;
3521
+ this.#mastra = mastra;
3522
+ this.#runId = runId ?? crypto.randomUUID();
3523
+ this.#onFinish = onFinish;
3524
+ this.#resultMapping = resultMapping;
3525
+ this.events = events;
3526
+ onStepTransition?.forEach(handler => this.#onStepTransition.add(handler));
3527
+ this.#initializeCompoundDependencies();
3528
+ }
3529
+ setState(state) {
3530
+ this.#state = state;
3531
+ }
3532
+ get runId() {
3533
+ return this.#runId;
3534
+ }
3535
+ get executionSpan() {
3536
+ return this.#executionSpan;
3537
+ }
3538
+ watch(onTransition) {
3539
+ this.#onStepTransition.add(onTransition);
3540
+ return () => {
3541
+ this.#onStepTransition.delete(onTransition);
3542
+ };
3543
+ }
3544
+ async start({
3545
+ triggerData,
3546
+ runtimeContext
3547
+ } = {}) {
3548
+ const results = await this.execute({
3549
+ triggerData,
3550
+ runtimeContext: runtimeContext ?? new chunkLABUWBKX_cjs.RuntimeContext()
3551
+ });
3552
+ if (this.#onFinish) {
3553
+ const activePathsObj = Object.fromEntries(results.activePaths);
3554
+ const hasSuspendedActivePaths = Object.values(activePathsObj).some(value => value.status === "suspended");
3555
+ if (!hasSuspendedActivePaths) {
3556
+ this.#onFinish();
3557
+ }
3558
+ }
3559
+ return {
3560
+ ...results,
3561
+ runId: this.runId
3562
+ };
3563
+ }
3564
+ isCompoundDependencyMet(stepKey) {
3565
+ if (!this.#isCompoundKey(stepKey)) return true;
3566
+ const dependencies = this.#compoundDependencies[stepKey];
3567
+ return dependencies ? Object.values(dependencies).every(status => status === true) : true;
3568
+ }
3569
+ async execute({
3570
+ triggerData,
3571
+ snapshot,
3572
+ stepId,
3573
+ resumeData,
3574
+ runtimeContext
3575
+ } = {
3576
+ runtimeContext: new chunkLABUWBKX_cjs.RuntimeContext()
3577
+ }) {
3578
+ this.#executionSpan = this.#mastra?.getTelemetry()?.tracer.startSpan(`workflow.${this.name}.execute`, {
3579
+ attributes: {
3580
+ componentName: this.name,
3581
+ runId: this.runId
3582
+ }
3583
+ });
3584
+ let machineInput = {
3585
+ // Maintain the original step results and their output
3586
+ steps: {},
3587
+ triggerData: triggerData || {},
3588
+ attempts: Object.keys(this.#steps).reduce((acc, stepKey) => {
3589
+ acc[stepKey] = this.#steps[stepKey]?.step?.retryConfig?.attempts || this.#retryConfig?.attempts || 0;
3590
+ return acc;
3591
+ }, {})
3592
+ };
3593
+ let stepGraph = this.#stepGraph;
3594
+ let startStepId = "trigger";
3595
+ if (snapshot) {
3596
+ const runState = snapshot;
3597
+ if (stepId && runState?.suspendedSteps?.[stepId]) {
3598
+ startStepId = runState.suspendedSteps[stepId];
3599
+ stepGraph = this.#stepSubscriberGraph[startStepId] ?? this.#stepGraph;
3600
+ machineInput = runState.context;
3601
+ }
3602
+ }
3603
+ const defaultMachine = new Machine({
3604
+ logger: this.logger,
3605
+ mastra: this.#mastra,
3606
+ runtimeContext,
3607
+ workflowInstance: this,
3608
+ name: this.name,
3609
+ runId: this.runId,
3610
+ steps: this.#steps,
3611
+ stepGraph,
3612
+ executionSpan: this.#executionSpan,
3613
+ startStepId,
3614
+ retryConfig: this.#retryConfig
3615
+ });
3616
+ this.#machines[startStepId] = defaultMachine;
3617
+ const stateUpdateHandler = (startStepId2, state, ctx) => {
3618
+ let fullState = {
3619
+ value: {},
3620
+ context: {}
3621
+ };
3622
+ if (ctx) {
3623
+ fullState["value"] = state;
3624
+ fullState["context"] = ctx;
3625
+ } else {
3626
+ fullState = state;
3627
+ }
3628
+ if (startStepId2 === "trigger") {
3629
+ this.#state = fullState.value;
3630
+ } else {
3631
+ this.#state = mergeChildValue(startStepId2, this.#state, fullState.value);
3632
+ }
3633
+ const now = Date.now();
3634
+ if (this.#onStepTransition) {
3635
+ this.#onStepTransition.forEach(onTransition => {
3636
+ void onTransition({
3637
+ runId: this.#runId,
3638
+ results: fullState.context.steps,
3639
+ activePaths: getResultActivePaths(fullState),
3640
+ timestamp: now
3641
+ });
3642
+ });
3643
+ }
3644
+ };
3645
+ defaultMachine.on("state-update", stateUpdateHandler);
3646
+ const {
3647
+ results,
3648
+ activePaths
3649
+ } = await defaultMachine.execute({
3650
+ snapshot,
3651
+ stepId,
3652
+ input: machineInput,
3653
+ resumeData
3654
+ });
3655
+ await this.persistWorkflowSnapshot();
3656
+ const result = {
3657
+ results,
3658
+ activePaths,
3659
+ timestamp: Date.now()
3660
+ };
3661
+ if (this.#resultMapping) {
3662
+ result.result = resolveVariables({
3663
+ runId: this.#runId,
3664
+ logger: this.logger,
3665
+ variables: this.#resultMapping,
3666
+ context: {
3667
+ steps: results,
3668
+ triggerData}
3669
+ });
3670
+ }
3671
+ return result;
3672
+ }
3673
+ hasSubscribers(stepId) {
3674
+ return Object.keys(this.#stepSubscriberGraph).some(key => key.split("&&").includes(stepId));
3675
+ }
3676
+ async runMachine(parentStepId, input, runtimeContext = new chunkLABUWBKX_cjs.RuntimeContext()) {
3677
+ const stepStatus = input.steps[parentStepId]?.status;
3678
+ const subscriberKeys = Object.keys(this.#stepSubscriberGraph).filter(key => key.split("&&").includes(parentStepId));
3679
+ subscriberKeys.forEach(key => {
3680
+ if (["success", "failure", "skipped"].includes(stepStatus) && this.#isCompoundKey(key)) {
3681
+ this.#compoundDependencies[key][parentStepId] = true;
3682
+ }
3683
+ });
3684
+ const stateUpdateHandler = (startStepId, state, ctx) => {
3685
+ let fullState = {
3686
+ value: {},
3687
+ context: {}
3688
+ };
3689
+ if (ctx) {
3690
+ fullState["value"] = state;
3691
+ fullState["context"] = ctx;
3692
+ } else {
3693
+ fullState = state;
3694
+ }
3695
+ if (startStepId === "trigger") {
3696
+ this.#state = fullState.value;
3697
+ } else {
3698
+ this.#state = mergeChildValue(startStepId, this.#state, fullState.value);
3699
+ }
3700
+ const now = Date.now();
3701
+ if (this.#onStepTransition) {
3702
+ this.#onStepTransition.forEach(onTransition => {
3703
+ void onTransition({
3704
+ runId: this.#runId,
3705
+ results: fullState.context.steps,
3706
+ activePaths: getResultActivePaths(fullState),
3707
+ timestamp: now
3708
+ });
3709
+ });
3710
+ }
3711
+ };
3712
+ const results = await Promise.all(subscriberKeys.map(async key => {
3713
+ if (!this.#stepSubscriberGraph[key] || !this.isCompoundDependencyMet(key)) {
3714
+ return;
3715
+ }
3716
+ this.#resetCompoundDependency(key);
3717
+ const machine = new Machine({
3718
+ logger: this.logger,
3719
+ mastra: this.#mastra,
3720
+ runtimeContext,
3721
+ workflowInstance: this,
3722
+ name: parentStepId === "trigger" ? this.name : `${this.name}-${parentStepId}`,
3723
+ runId: this.runId,
3724
+ steps: this.#steps,
3725
+ stepGraph: this.#stepSubscriberGraph[key],
3726
+ executionSpan: this.#executionSpan,
3727
+ startStepId: parentStepId
3728
+ });
3729
+ machine.on("state-update", stateUpdateHandler);
3730
+ this.#machines[parentStepId] = machine;
3731
+ return machine.execute({
3732
+ input
3733
+ });
3734
+ }));
3735
+ return results;
3736
+ }
3737
+ async suspend(stepId, machine) {
3738
+ this.#suspendedMachines[stepId] = machine;
3739
+ }
3740
+ /**
3741
+ * Persists the workflow state to the database
3742
+ */
3743
+ async persistWorkflowSnapshot() {
3744
+ const storage = this.#mastra?.getStorage();
3745
+ if (!storage) {
3746
+ this.logger.debug("Snapshot cannot be persisted. Mastra engine is not initialized", {
3747
+ runId: this.#runId
3748
+ });
3749
+ return;
3750
+ }
3751
+ const existingSnapshot = await storage.loadWorkflowSnapshot({
3752
+ workflowName: this.name,
3753
+ runId: this.#runId
3754
+ });
3755
+ const machineSnapshots = {};
3756
+ for (const [stepId, machine] of Object.entries(this.#machines)) {
3757
+ const machineSnapshot = machine?.getSnapshot();
3758
+ if (machineSnapshot) {
3759
+ machineSnapshots[stepId] = {
3760
+ ...machineSnapshot
3761
+ };
3762
+ }
3763
+ }
3764
+ let snapshot = machineSnapshots["trigger"];
3765
+ delete machineSnapshots["trigger"];
3766
+ const suspendedSteps = Object.entries(this.#suspendedMachines).reduce((acc, [stepId, machine]) => {
3767
+ acc[stepId] = machine.startStepId;
3768
+ return acc;
3769
+ }, {});
3770
+ if (!snapshot && existingSnapshot) {
3771
+ existingSnapshot.childStates = {
3772
+ ...existingSnapshot.childStates,
3773
+ ...machineSnapshots
3774
+ };
3775
+ existingSnapshot.suspendedSteps = {
3776
+ ...existingSnapshot.suspendedSteps,
3777
+ ...suspendedSteps
3778
+ };
3779
+ await storage.persistWorkflowSnapshot({
3780
+ workflowName: this.name,
3781
+ runId: this.#runId,
3782
+ snapshot: existingSnapshot
3783
+ });
3784
+ return;
3785
+ } else if (snapshot && !existingSnapshot) {
3786
+ snapshot.suspendedSteps = suspendedSteps;
3787
+ snapshot.childStates = {
3788
+ ...machineSnapshots
3789
+ };
3790
+ await storage.persistWorkflowSnapshot({
3791
+ workflowName: this.name,
3792
+ runId: this.#runId,
3793
+ snapshot
3794
+ });
3795
+ return;
3796
+ } else if (!snapshot) {
3797
+ this.logger.debug("Snapshot cannot be persisted. No snapshot received.", {
3798
+ runId: this.#runId
3799
+ });
3800
+ return;
3801
+ }
3802
+ snapshot.suspendedSteps = {
3803
+ ...existingSnapshot.suspendedSteps,
3804
+ ...suspendedSteps
3805
+ };
3806
+ if (!existingSnapshot || snapshot === existingSnapshot) {
3807
+ await storage.persistWorkflowSnapshot({
3808
+ workflowName: this.name,
3809
+ runId: this.#runId,
3810
+ snapshot
3811
+ });
3812
+ return;
3813
+ }
3814
+ if (existingSnapshot?.childStates) {
3815
+ snapshot.childStates = {
3816
+ ...existingSnapshot.childStates,
3817
+ ...machineSnapshots
3818
+ };
3819
+ } else {
3820
+ snapshot.childStates = machineSnapshots;
3821
+ }
3822
+ await storage.persistWorkflowSnapshot({
3823
+ workflowName: this.name,
3824
+ runId: this.#runId,
3825
+ snapshot
3826
+ });
3827
+ }
3828
+ async getState() {
3829
+ const storedSnapshot = await this.#mastra?.storage?.loadWorkflowSnapshot({
3830
+ workflowName: this.name,
3831
+ runId: this.runId
3832
+ });
3833
+ const prevSnapshot = storedSnapshot ? {
3834
+ trigger: storedSnapshot,
3835
+ ...Object.entries(storedSnapshot?.childStates ?? {}).reduce((acc, [stepId, snapshot2]) => ({
3836
+ ...acc,
3837
+ [stepId]: snapshot2
3838
+ }), {})
3839
+ } : {};
3840
+ const currentSnapshot = Object.entries(this.#machines).reduce((acc, [stepId, machine]) => {
3841
+ const snapshot2 = machine.getSnapshot();
3842
+ if (!snapshot2) {
3843
+ return acc;
3844
+ }
3845
+ return {
3846
+ ...acc,
3847
+ [stepId]: snapshot2
3848
+ };
3849
+ }, {});
3850
+ Object.assign(prevSnapshot, currentSnapshot);
3851
+ const trigger = prevSnapshot.trigger;
3852
+ delete prevSnapshot.trigger;
3853
+ const snapshot = {
3854
+ ...trigger};
3855
+ const m = getActivePathsAndStatus(prevSnapshot.value);
3856
+ return {
3857
+ runId: this.runId,
3858
+ value: snapshot.value,
3859
+ context: snapshot.context,
3860
+ activePaths: m,
3861
+ timestamp: Date.now()
3862
+ };
3863
+ }
3864
+ async resumeWithEvent(eventName, data, runtimeContext = new chunkLABUWBKX_cjs.RuntimeContext()) {
3865
+ const event = this.events?.[eventName];
3866
+ if (!event) {
3867
+ throw new Error(`Event ${eventName} not found`);
3868
+ }
3869
+ const results = await this.resume({
3870
+ stepId: `__${eventName}_event`,
3871
+ context: {
3872
+ resumedEvent: data
3873
+ },
3874
+ runtimeContext
3875
+ });
3876
+ return results;
3877
+ }
3878
+ async resume({
3879
+ stepId,
3880
+ context: resumeContext,
3881
+ runtimeContext = new chunkLABUWBKX_cjs.RuntimeContext()
3882
+ }) {
3883
+ await new Promise(resolve => setTimeout(resolve, 0));
3884
+ return this._resume({
3885
+ stepId,
3886
+ context: resumeContext,
3887
+ runtimeContext
3888
+ });
3889
+ }
3890
+ async #loadWorkflowSnapshot(runId) {
3891
+ const storage = this.#mastra?.getStorage();
3892
+ if (!storage) {
3893
+ this.logger.debug("Snapshot cannot be loaded. Mastra engine is not initialized", {
3894
+ runId
3895
+ });
3896
+ return;
3897
+ }
3898
+ await this.persistWorkflowSnapshot();
3899
+ return storage.loadWorkflowSnapshot({
3900
+ runId,
3901
+ workflowName: this.name
3902
+ });
3903
+ }
3904
+ async _resume({
3905
+ stepId,
3906
+ context: resumeContext,
3907
+ runtimeContext
3908
+ }) {
3909
+ const snapshot = await this.#loadWorkflowSnapshot(this.runId);
3910
+ if (!snapshot) {
3911
+ throw new Error(`No snapshot found for workflow run ${this.runId}`);
3912
+ }
3913
+ const stepParts = stepId.split(".");
3914
+ const stepPath = stepParts.join(".");
3915
+ if (stepParts.length > 1) {
3916
+ stepId = stepParts[0] ?? stepId;
3917
+ }
3918
+ let parsedSnapshot;
3919
+ try {
3920
+ parsedSnapshot = typeof snapshot === "string" ? JSON.parse(snapshot) : snapshot;
3921
+ } catch (error) {
3922
+ this.logger.debug("Failed to parse workflow snapshot for resume", {
3923
+ error,
3924
+ runId: this.runId
3925
+ });
3926
+ throw new Error("Failed to parse workflow snapshot");
3927
+ }
3928
+ const startStepId = parsedSnapshot.suspendedSteps?.[stepId];
3929
+ if (!startStepId) {
3930
+ return;
3931
+ }
3932
+ parsedSnapshot = startStepId === "trigger" ? parsedSnapshot : {
3933
+ ...parsedSnapshot?.childStates?.[startStepId],
3934
+ ...{
3935
+ suspendedSteps: parsedSnapshot.suspendedSteps
3936
+ }
3937
+ };
3938
+ if (!parsedSnapshot) {
3939
+ throw new Error(`No snapshot found for step: ${stepId} starting at ${startStepId}`);
3940
+ }
3941
+ if (resumeContext) {
3942
+ parsedSnapshot.context.steps[stepId] = {
3943
+ status: "success",
3944
+ output: {
3945
+ ...(parsedSnapshot?.context?.steps?.[stepId]?.output || {}),
3946
+ ...resumeContext
3947
+ }
3948
+ };
3949
+ }
3950
+ if (parsedSnapshot.children) {
3951
+ Object.entries(parsedSnapshot.children).forEach(([, child]) => {
3952
+ if (child.snapshot?.input?.stepNode) {
3953
+ const stepDef = this.#makeStepDef(child.snapshot.input.stepNode.step.id);
3954
+ child.snapshot.input.stepNode.config = {
3955
+ ...child.snapshot.input.stepNode.config,
3956
+ ...stepDef
3957
+ };
3958
+ child.snapshot.input.context = parsedSnapshot.context;
3959
+ }
3960
+ });
3961
+ }
3962
+ parsedSnapshot.value = updateStepInHierarchy(parsedSnapshot.value, stepId);
3963
+ if (parsedSnapshot.context?.attempts) {
3964
+ parsedSnapshot.context.attempts[stepId] = this.#steps[stepId]?.step?.retryConfig?.attempts || this.#retryConfig?.attempts || 0;
3965
+ }
3966
+ this.logger.debug("Resuming workflow with updated snapshot", {
3967
+ updatedSnapshot: parsedSnapshot,
3968
+ runId: this.runId,
3969
+ stepId
3970
+ });
3971
+ return this.execute({
3972
+ snapshot: parsedSnapshot,
3973
+ stepId: stepPath,
3974
+ resumeData: resumeContext,
3975
+ runtimeContext
3976
+ });
3977
+ }
3978
+ #initializeCompoundDependencies() {
3979
+ Object.keys(this.#stepSubscriberGraph).forEach(stepKey => {
3980
+ if (this.#isCompoundKey(stepKey)) {
3981
+ const requiredSteps = stepKey.split("&&");
3982
+ this.#compoundDependencies[stepKey] = requiredSteps.reduce((acc, step) => {
3983
+ acc[step] = false;
3984
+ return acc;
3985
+ }, {});
3986
+ }
3987
+ });
3988
+ }
3989
+ #resetCompoundDependency(key) {
3990
+ if (this.#isCompoundKey(key)) {
3991
+ const requiredSteps = key.split("&&");
3992
+ this.#compoundDependencies[key] = requiredSteps.reduce((acc, step) => {
3993
+ acc[step] = false;
3994
+ return acc;
3995
+ }, {});
3996
+ }
3997
+ }
3998
+ #makeStepDef(stepId) {
3999
+ const executeStep = (handler2, spanName, attributes) => {
4000
+ return async data => {
4001
+ return await api.context.with(api.trace.setSpan(api.context.active(), this.#executionSpan), async () => {
4002
+ if (this.#mastra?.getTelemetry()) {
4003
+ return this.#mastra.getTelemetry()?.traceMethod(handler2, {
4004
+ spanName,
4005
+ attributes
4006
+ })(data);
4007
+ } else {
4008
+ return handler2(data);
4009
+ }
4010
+ });
4011
+ };
4012
+ };
4013
+ const handler = async ({
4014
+ context,
4015
+ ...rest
4016
+ }) => {
4017
+ const targetStep = this.#steps[stepId];
4018
+ if (!targetStep) throw new Error(`Step not found`);
4019
+ const {
4020
+ payload = {},
4021
+ execute = async () => {}
4022
+ } = targetStep.step;
4023
+ const mergedData = {
4024
+ ...payload,
4025
+ ...context
4026
+ };
4027
+ const finalAction = this.#mastra?.getTelemetry() ? executeStep(execute, `workflow.${this.name}.action.${stepId}`, {
4028
+ componentName: this.name,
4029
+ runId: rest.runId
4030
+ }) : execute;
4031
+ return finalAction ? await finalAction({
4032
+ context: mergedData,
4033
+ ...rest
4034
+ }) : {};
4035
+ };
4036
+ const finalHandler = ({
4037
+ context,
4038
+ ...rest
4039
+ }) => {
4040
+ if (this.#executionSpan) {
4041
+ return executeStep(handler, `workflow.${this.name}.step.${stepId}`, {
4042
+ componentName: this.name,
4043
+ runId: rest?.runId
4044
+ })({
4045
+ context,
4046
+ ...rest
4047
+ });
4048
+ }
4049
+ return handler({
4050
+ context,
4051
+ ...rest
4052
+ });
4053
+ };
4054
+ return {
4055
+ handler: finalHandler,
4056
+ data: {}
4057
+ };
4058
+ }
4059
+ #isCompoundKey(key) {
4060
+ return key.includes("&&");
4061
+ }
4062
+ };
4063
+
4064
+ // src/workflows/legacy/workflow.ts
4065
+ var LegacyWorkflow = class extends chunkP3Q73CAW_cjs.MastraBase {
4066
+ name;
4067
+ triggerSchema;
4068
+ resultSchema;
4069
+ resultMapping;
4070
+ events;
4071
+ #retryConfig;
4072
+ #mastra;
4073
+ #runs = /* @__PURE__ */new Map();
4074
+ isNested = false;
4075
+ #onStepTransition = /* @__PURE__ */new Set();
4076
+ // registers stepIds on `after` calls
4077
+ #afterStepStack = [];
4078
+ #lastStepStack = [];
4079
+ #lastBuilderType = null;
4080
+ #ifStack = [];
4081
+ #stepGraph = {
4082
+ initial: []
4083
+ };
4084
+ #serializedStepGraph = {
4085
+ initial: []
4086
+ };
4087
+ #stepSubscriberGraph = {};
4088
+ #serializedStepSubscriberGraph = {};
4089
+ #steps = {};
4090
+ #ifCount = 0;
4091
+ /**
4092
+ * Creates a new LegacyWorkflow instance
4093
+ * @param name - Identifier for the workflow (not necessarily unique)
4094
+ * @param logger - Optional logger instance
4095
+ */
4096
+ constructor({
4097
+ name,
4098
+ triggerSchema,
4099
+ result,
4100
+ retryConfig,
4101
+ mastra,
4102
+ events
4103
+ }) {
4104
+ super({
4105
+ component: "WORKFLOW",
4106
+ name
4107
+ });
4108
+ this.name = name;
4109
+ this.#retryConfig = retryConfig;
4110
+ this.triggerSchema = triggerSchema;
4111
+ this.resultSchema = result?.schema;
4112
+ this.resultMapping = result?.mapping;
4113
+ this.events = events;
4114
+ if (mastra) {
4115
+ this.__registerPrimitives({
4116
+ telemetry: mastra.getTelemetry(),
4117
+ logger: mastra.getLogger()
4118
+ });
4119
+ this.#mastra = mastra;
4120
+ }
4121
+ }
4122
+ step(next, config) {
4123
+ const that = this;
4124
+ if (Array.isArray(next)) {
4125
+ const nextSteps = next.map(step2 => {
4126
+ if (isWorkflow(step2)) {
4127
+ const asStep = step2.toStep();
4128
+ return asStep;
4129
+ } else if (isAgent(step2)) {
4130
+ return agentToStep(step2);
4131
+ } else {
4132
+ return step2;
4133
+ }
4134
+ });
4135
+ nextSteps.forEach(step2 => this.step(step2, config));
4136
+ this.after(nextSteps);
4137
+ this.step(new LegacyStep({
4138
+ id: `__after_${next.map(step2 => config?.id ?? step2?.id ?? step2?.name).join("_")}`,
4139
+ execute: async () => {
4140
+ return {
4141
+ success: true
4142
+ };
4143
+ }
4144
+ }));
4145
+ return this;
4146
+ }
4147
+ const {
4148
+ variables = {}
4149
+ } = config || {};
4150
+ const requiredData = {};
4151
+ for (const [key, variable] of Object.entries(variables)) {
4152
+ if (variable && isVariableReference(variable)) {
4153
+ requiredData[key] = variable;
4154
+ }
4155
+ }
4156
+ const step = isWorkflow(next) ?
4157
+ // @ts-ignore
4158
+ workflowToStep(next, {
4159
+ mastra: this.#mastra
4160
+ }) : isAgent(next) ?
4161
+ // @ts-ignore
4162
+ agentToStep(next, {
4163
+ mastra: this.#mastra
4164
+ }) : next;
4165
+ const stepKey = this.#makeStepKey(step, config);
4166
+ const when = config?.["#internal"]?.when || config?.when;
4167
+ const graphEntry = {
4168
+ step,
4169
+ config: {
4170
+ ...this.#makeStepDef(stepKey),
4171
+ ...config,
4172
+ loopLabel: config?.["#internal"]?.loopLabel,
4173
+ loopType: config?.["#internal"]?.loopType,
4174
+ serializedWhen: typeof when === "function" ? when.toString() : when,
4175
+ data: requiredData
4176
+ },
4177
+ get id() {
4178
+ return that.#makeStepKey(this.step, this.config);
4179
+ }
4180
+ };
4181
+ this.#steps[stepKey] = graphEntry;
4182
+ const parentStepKey = this.#getParentStepKey({
4183
+ loop_check: true
4184
+ });
4185
+ const stepGraph = this.#stepSubscriberGraph[parentStepKey || ""];
4186
+ const serializedStepGraph = this.#serializedStepSubscriberGraph[parentStepKey || ""];
4187
+ if (parentStepKey && stepGraph) {
4188
+ if (!stepGraph.initial.some(step2 => step2.config.id === stepKey || step2.step.id === stepKey)) {
4189
+ stepGraph.initial.push(graphEntry);
4190
+ if (serializedStepGraph) serializedStepGraph.initial.push(graphEntry);
4191
+ }
4192
+ stepGraph[stepKey] = [];
4193
+ if (serializedStepGraph) serializedStepGraph[stepKey] = [];
4194
+ } else {
4195
+ if (!this.#stepGraph[stepKey]) this.#stepGraph[stepKey] = [];
4196
+ this.#stepGraph.initial.push(graphEntry);
4197
+ this.#serializedStepGraph.initial.push(graphEntry);
4198
+ }
4199
+ this.#lastStepStack.push(stepKey);
4200
+ this.#lastBuilderType = "step";
4201
+ return this;
4202
+ }
4203
+ #__internalStep(next, config, internalUse) {
4204
+ const that = this;
4205
+ if (Array.isArray(next)) {
4206
+ const nextSteps = next.map(step2 => {
4207
+ if (isWorkflow(step2)) {
4208
+ const asStep = step2.toStep();
4209
+ return asStep;
4210
+ } else {
4211
+ return step2;
4212
+ }
4213
+ });
4214
+ nextSteps.forEach(step2 => this.#__internalStep(step2, config, internalUse));
4215
+ this.after(nextSteps);
4216
+ this.#__internalStep(new LegacyStep({
4217
+ id: `__after_${next.map(step2 => step2?.id ?? step2?.name).join("_")}`,
4218
+ execute: async () => {
4219
+ return {
4220
+ success: true
4221
+ };
4222
+ }
4223
+ }), void 0, internalUse);
4224
+ return this;
4225
+ }
4226
+ const {
4227
+ variables = {}
4228
+ } = config || {};
4229
+ const requiredData = {};
4230
+ for (const [key, variable] of Object.entries(variables)) {
4231
+ if (variable && isVariableReference(variable)) {
4232
+ requiredData[key] = variable;
4233
+ }
4234
+ }
4235
+ const step = isWorkflow(next) ?
4236
+ // @ts-ignore
4237
+ workflowToStep(next, {
4238
+ mastra: this.#mastra
4239
+ }) : next;
4240
+ const stepKey = this.#makeStepKey(step, config);
4241
+ const when = config?.["#internal"]?.when || config?.when;
4242
+ const graphEntry = {
4243
+ step,
4244
+ config: {
4245
+ ...this.#makeStepDef(stepKey),
4246
+ ...config,
4247
+ loopLabel: config?.["#internal"]?.loopLabel,
4248
+ loopType: config?.["#internal"]?.loopType,
4249
+ serializedWhen: typeof when === "function" ? when.toString() : when,
4250
+ data: requiredData
4251
+ },
4252
+ get id() {
4253
+ return that.#makeStepKey(this.step, this.config);
4254
+ }
4255
+ };
4256
+ this.#steps[stepKey] = graphEntry;
4257
+ const parentStepKey = this.#getParentStepKey();
4258
+ const stepGraph = this.#stepSubscriberGraph[parentStepKey || ""];
4259
+ const serializedStepGraph = this.#serializedStepSubscriberGraph[parentStepKey || ""];
4260
+ if (parentStepKey && stepGraph) {
4261
+ if (!stepGraph.initial.some(step2 => step2.step.id === stepKey)) {
4262
+ stepGraph.initial.push(graphEntry);
4263
+ if (serializedStepGraph) serializedStepGraph.initial.push(graphEntry);
4264
+ }
4265
+ stepGraph[stepKey] = [];
4266
+ if (serializedStepGraph) serializedStepGraph[stepKey] = [];
4267
+ } else {
4268
+ if (!this.#stepGraph[stepKey]) this.#stepGraph[stepKey] = [];
4269
+ this.#stepGraph.initial.push(graphEntry);
4270
+ this.#serializedStepGraph.initial.push(graphEntry);
4271
+ }
4272
+ this.#lastStepStack.push(stepKey);
4273
+ this.#lastBuilderType = "step";
4274
+ return this;
4275
+ }
4276
+ #makeStepKey(step, config) {
4277
+ if (typeof step === "string") return step;
4278
+ return `${config?.id ?? step.id ?? step.name}`;
4279
+ }
4280
+ then(next, config) {
4281
+ const that = this;
4282
+ if (Array.isArray(next)) {
4283
+ const lastStep = this.#steps[this.#lastStepStack[this.#lastStepStack.length - 1] ?? ""];
4284
+ if (!lastStep) {
4285
+ throw new Error("Condition requires a step to be executed after");
4286
+ }
4287
+ this.after(lastStep.step);
4288
+ const nextSteps = next.map(step2 => {
4289
+ if (isWorkflow(step2)) {
4290
+ return workflowToStep(step2, {
4291
+ mastra: this.#mastra
4292
+ });
4293
+ }
4294
+ if (isAgent(step2)) {
4295
+ return agentToStep(step2);
4296
+ }
4297
+ return step2;
4298
+ });
4299
+ nextSteps.forEach(step2 => this.step(step2, config));
4300
+ this.step(new LegacyStep({
4301
+ // @ts-ignore
4302
+ id: `__after_${next.map(step2 => step2?.id ?? step2?.name).join("_")}`,
4303
+ execute: async () => {
4304
+ return {
4305
+ success: true
4306
+ };
4307
+ }
4308
+ }));
4309
+ return this;
4310
+ }
4311
+ const {
4312
+ variables = {}
4313
+ } = config || {};
4314
+ const requiredData = {};
4315
+ for (const [key, variable] of Object.entries(variables)) {
4316
+ if (variable && isVariableReference(variable)) {
4317
+ requiredData[key] = variable;
4318
+ }
4319
+ }
4320
+ const lastStepKey = this.#lastStepStack[this.#lastStepStack.length - 1];
4321
+ const step = isWorkflow(next) ? workflowToStep(next, {
4322
+ mastra: this.#mastra
4323
+ }) : isAgent(next) ? agentToStep(next) : next;
4324
+ const stepKey = this.#makeStepKey(step, config);
4325
+ const when = config?.["#internal"]?.when || config?.when;
4326
+ const graphEntry = {
4327
+ step,
4328
+ config: {
4329
+ ...this.#makeStepDef(stepKey),
4330
+ ...config,
4331
+ loopLabel: config?.["#internal"]?.loopLabel,
4332
+ loopType: config?.["#internal"]?.loopType,
4333
+ serializedWhen: typeof when === "function" ? when.toString() : when,
4334
+ data: requiredData
4335
+ },
4336
+ get id() {
4337
+ return that.#makeStepKey(this.step, this.config);
4338
+ }
4339
+ };
4340
+ this.#steps[stepKey] = graphEntry;
4341
+ if (!lastStepKey) return this;
4342
+ const parentStepKey = this.#getParentStepKey();
4343
+ const stepGraph = this.#stepSubscriberGraph[parentStepKey || ""];
4344
+ const serializedStepGraph = this.#serializedStepSubscriberGraph[parentStepKey || ""];
4345
+ if (parentStepKey && this.#lastBuilderType === "after") {
4346
+ return this.step(step, config);
4347
+ }
4348
+ if (parentStepKey && stepGraph && stepGraph[lastStepKey]) {
4349
+ stepGraph[lastStepKey].push(graphEntry);
4350
+ if (serializedStepGraph && serializedStepGraph[lastStepKey]) serializedStepGraph[lastStepKey].push(graphEntry);
4351
+ } else {
4352
+ if (!this.#stepGraph[lastStepKey]) this.#stepGraph[lastStepKey] = [];
4353
+ if (!this.#serializedStepGraph[lastStepKey]) this.#serializedStepGraph[lastStepKey] = [];
4354
+ this.#stepGraph[lastStepKey].push(graphEntry);
4355
+ this.#serializedStepGraph[lastStepKey].push(graphEntry);
4356
+ }
4357
+ this.#lastBuilderType = "then";
4358
+ return this;
4359
+ }
4360
+ loop(applyOperator, condition, fallbackStep, loopType, variables) {
4361
+ const lastStepKey = this.#lastStepStack[this.#lastStepStack.length - 1];
4362
+ if (!lastStepKey) return this;
4363
+ const fallbackStepKey = this.#makeStepKey(fallbackStep);
4364
+ const fallbackStepNode = {
4365
+ step: fallbackStep,
4366
+ config: {
4367
+ ...this.#makeStepDef(fallbackStepKey)
4368
+ },
4369
+ get id() {
4370
+ return fallbackStepKey;
4371
+ }
4372
+ };
4373
+ this.#steps[fallbackStepKey] = fallbackStepNode;
4374
+ const checkStepKey = `__${fallbackStepKey}_${loopType}_loop_check`;
4375
+ const checkStep = {
4376
+ id: checkStepKey,
4377
+ execute: async ({
4378
+ context
4379
+ }) => {
4380
+ if (typeof condition === "function") {
4381
+ const result = await condition({
4382
+ context
4383
+ });
4384
+ switch (loopType) {
4385
+ case "while":
4386
+ return {
4387
+ status: result ? "continue" : "complete"
4388
+ };
4389
+ case "until":
4390
+ return {
4391
+ status: result ? "complete" : "continue"
4392
+ };
4393
+ default:
4394
+ throw new Error(`Invalid loop type: ${loopType}`);
4395
+ }
4396
+ }
4397
+ if (condition && "ref" in condition) {
4398
+ const {
4399
+ ref,
4400
+ query
4401
+ } = condition;
4402
+ const stepId = typeof ref.step === "string" ? ref.step : "id" in ref.step ? ref.step.id : null;
4403
+ if (!stepId) {
4404
+ return {
4405
+ status: "continue"
4406
+ };
4407
+ }
4408
+ const stepOutput = context.steps?.[stepId]?.output;
4409
+ if (!stepOutput) {
4410
+ return {
4411
+ status: "continue"
4412
+ };
4413
+ }
4414
+ const value = ref.path.split(".").reduce((obj, key) => obj?.[key], stepOutput);
4415
+ const operator = Object.keys(query)[0];
4416
+ const target = query[operator];
4417
+ return applyOperator(operator, value, target);
4418
+ }
4419
+ return {
4420
+ status: "continue"
4421
+ };
4422
+ },
4423
+ outputSchema: zod.z.object({
4424
+ status: zod.z.enum(["continue", "complete"])
4425
+ })
4426
+ };
4427
+ const checkStepNode = {
4428
+ step: checkStep,
4429
+ config: {
4430
+ ...this.#makeStepDef(checkStepKey)
4431
+ },
4432
+ get id() {
4433
+ return checkStepKey;
4434
+ }
4435
+ };
4436
+ this.#steps[checkStepKey] = checkStepNode;
4437
+ const loopFinishedStepKey = `__${fallbackStepKey}_${loopType}_loop_finished`;
4438
+ const loopFinishedStep = {
4439
+ id: loopFinishedStepKey,
4440
+ execute: async () => {
4441
+ return {
4442
+ success: true
4443
+ };
4444
+ }
4445
+ };
4446
+ const loopFinishedStepNode = {
4447
+ step: loopFinishedStep,
4448
+ config: {
4449
+ ...this.#makeStepDef(loopFinishedStepKey)
4450
+ },
4451
+ get id() {
4452
+ return loopFinishedStepKey;
4453
+ }
4454
+ };
4455
+ this.#steps[loopFinishedStepKey] = loopFinishedStepNode;
4456
+ this.then(checkStep, {
4457
+ id: checkStepKey,
4458
+ "#internal": {
4459
+ loopLabel: `${fallbackStepKey} ${loopType} loop check`
4460
+ }
4461
+ });
4462
+ this.after(checkStep);
4463
+ this.#__internalStep(fallbackStep, {
4464
+ when: async ({
4465
+ context
4466
+ }) => {
4467
+ const checkStepResult = context.steps?.[checkStepKey];
4468
+ if (checkStepResult?.status !== "success") {
4469
+ return "abort" /* ABORT */;
4470
+ }
4471
+ const status = checkStepResult?.output?.status;
4472
+ return status === "continue" ? "continue" /* CONTINUE */ : "continue_failed" /* CONTINUE_FAILED */;
4473
+ },
4474
+ variables,
4475
+ "#internal": {
4476
+ // @ts-ignore
4477
+ when: condition,
4478
+ loopType
4479
+ }
4480
+ }).then(checkStep, {
4481
+ id: checkStepKey,
4482
+ "#internal": {
4483
+ loopLabel: `${fallbackStepKey} ${loopType} loop check`
4484
+ }
4485
+ });
4486
+ this.#__internalStep(loopFinishedStep, {
4487
+ id: loopFinishedStepKey,
4488
+ when: async ({
4489
+ context
4490
+ }) => {
4491
+ const checkStepResult = context.steps?.[checkStepKey];
4492
+ if (checkStepResult?.status !== "success") {
4493
+ return "continue_failed" /* CONTINUE_FAILED */;
4494
+ }
4495
+ const status = checkStepResult?.output?.status;
4496
+ return status === "complete" ? "continue" /* CONTINUE */ : "continue_failed" /* CONTINUE_FAILED */;
4497
+ },
4498
+ "#internal": {
4499
+ loopLabel: `${fallbackStepKey} ${loopType} loop finished`,
4500
+ //@ts-ignore
4501
+ loopType
4502
+ }
4503
+ });
4504
+ return this;
4505
+ }
4506
+ while(condition, fallbackStep, variables) {
4507
+ const applyOperator = (operator, value, target) => {
4508
+ switch (operator) {
4509
+ case "$eq":
4510
+ return {
4511
+ status: value !== target ? "complete" : "continue"
4512
+ };
4513
+ case "$ne":
4514
+ return {
4515
+ status: value === target ? "complete" : "continue"
4516
+ };
4517
+ case "$gt":
4518
+ return {
4519
+ status: value <= target ? "complete" : "continue"
4520
+ };
4521
+ case "$gte":
4522
+ return {
4523
+ status: value < target ? "complete" : "continue"
4524
+ };
4525
+ case "$lt":
4526
+ return {
4527
+ status: value >= target ? "complete" : "continue"
4528
+ };
4529
+ case "$lte":
4530
+ return {
4531
+ status: value > target ? "complete" : "continue"
4532
+ };
4533
+ default:
4534
+ return {
4535
+ status: "continue"
4536
+ };
4537
+ }
4538
+ };
4539
+ const res = this.loop(applyOperator, condition, fallbackStep, "while", variables);
4540
+ this.#lastBuilderType = "while";
4541
+ return res;
4542
+ }
4543
+ until(condition, fallbackStep, variables) {
4544
+ const applyOperator = (operator, value, target) => {
4545
+ switch (operator) {
4546
+ case "$eq":
4547
+ return {
4548
+ status: value === target ? "complete" : "continue"
4549
+ };
4550
+ case "$ne":
4551
+ return {
4552
+ status: value !== target ? "complete" : "continue"
4553
+ };
4554
+ case "$gt":
4555
+ return {
4556
+ status: value > target ? "complete" : "continue"
4557
+ };
4558
+ case "$gte":
4559
+ return {
4560
+ status: value >= target ? "complete" : "continue"
4561
+ };
4562
+ case "$lt":
4563
+ return {
4564
+ status: value < target ? "complete" : "continue"
4565
+ };
4566
+ case "$lte":
4567
+ return {
4568
+ status: value <= target ? "complete" : "continue"
4569
+ };
4570
+ default:
4571
+ return {
4572
+ status: "continue"
4573
+ };
4574
+ }
4575
+ };
4576
+ const res = this.loop(applyOperator, condition, fallbackStep, "until", variables);
4577
+ this.#lastBuilderType = "until";
4578
+ return res;
4579
+ }
4580
+ if(condition, ifStep, elseStep) {
4581
+ this.#ifCount++;
4582
+ const lastStep = this.#getLastStep({
4583
+ if_else_check: this.#lastBuilderType !== "else"
4584
+ });
4585
+ if (!lastStep) {
4586
+ throw new Error("Condition requires a step to be executed after");
4587
+ }
4588
+ this.after(lastStep.step);
4589
+ if (ifStep) {
4590
+ const _ifStep = isWorkflow(ifStep) ? workflowToStep(ifStep, {
4591
+ mastra: this.#mastra
4592
+ }) : ifStep;
4593
+ this.step(_ifStep, {
4594
+ id: _ifStep.id,
4595
+ when: condition
4596
+ });
4597
+ if (elseStep) {
4598
+ const _elseStep = isWorkflow(elseStep) ? workflowToStep(elseStep, {
4599
+ mastra: this.#mastra
4600
+ }) : elseStep;
4601
+ this.step(_elseStep, {
4602
+ id: _elseStep.id,
4603
+ when: typeof condition === "function" ? async payload => {
4604
+ const result = await condition(payload);
4605
+ return !result;
4606
+ } : {
4607
+ not: condition
4608
+ }
4609
+ });
4610
+ this.after([_ifStep, _elseStep]);
4611
+ } else {
4612
+ this.after(_ifStep);
4613
+ }
4614
+ this.step(new LegacyStep({
4615
+ id: `${lastStep.id}_if_else`,
4616
+ execute: async () => {
4617
+ return {
4618
+ executed: true
4619
+ };
4620
+ }
4621
+ }));
4622
+ return this;
4623
+ }
4624
+ const ifStepKey = `__${lastStep.id}_if_${this.#ifCount}`;
4625
+ this.step({
4626
+ id: ifStepKey,
4627
+ execute: async () => {
4628
+ return {
4629
+ executed: true
4630
+ };
4631
+ }
4632
+ }, {
4633
+ id: ifStepKey,
4634
+ when: condition
4635
+ });
4636
+ const elseStepKey = `__${lastStep.id}_else_${this.#ifCount}`;
4637
+ this.#ifStack.push({
4638
+ condition,
4639
+ elseStepKey,
4640
+ condStep: lastStep.step
4641
+ });
4642
+ this.#lastBuilderType = "if";
4643
+ return this;
4644
+ }
4645
+ else() {
4646
+ const activeCondition = this.#ifStack.pop();
4647
+ if (!activeCondition) {
4648
+ throw new Error("No active condition found");
4649
+ }
4650
+ this.after(activeCondition.condStep).step({
4651
+ id: activeCondition.elseStepKey,
4652
+ execute: async () => {
4653
+ return {
4654
+ executed: true
4655
+ };
4656
+ }
4657
+ }, {
4658
+ id: activeCondition.elseStepKey,
4659
+ when: typeof activeCondition.condition === "function" ? async payload => {
4660
+ const result = await activeCondition.condition(payload);
4661
+ return !result;
4662
+ } : {
4663
+ not: activeCondition.condition
4664
+ }
4665
+ });
4666
+ this.#lastBuilderType = "else";
4667
+ return this;
4668
+ }
4669
+ after(steps) {
4670
+ const stepsArray = Array.isArray(steps) ? steps : [steps];
4671
+ const stepKeys = stepsArray.map(step => this.#makeStepKey(step));
4672
+ const compoundKey = stepKeys.join("&&");
4673
+ this.#afterStepStack.push(compoundKey);
4674
+ if (!this.#stepSubscriberGraph[compoundKey]) {
4675
+ this.#stepSubscriberGraph[compoundKey] = {
4676
+ initial: []
4677
+ };
4678
+ this.#serializedStepSubscriberGraph[compoundKey] = {
4679
+ initial: []
4680
+ };
4681
+ }
4682
+ this.#lastBuilderType = "after";
4683
+ return this;
4684
+ }
4685
+ afterEvent(eventName) {
4686
+ const event = this.events?.[eventName];
4687
+ if (!event) {
4688
+ throw new Error(`Event ${eventName} not found`);
4689
+ }
4690
+ const lastStep = this.#steps[this.#lastStepStack[this.#lastStepStack.length - 1] ?? ""];
4691
+ if (!lastStep) {
4692
+ throw new Error("Condition requires a step to be executed after");
4693
+ }
4694
+ const eventStepKey = `__${eventName}_event`;
4695
+ const eventStep = new LegacyStep({
4696
+ id: eventStepKey,
4697
+ execute: async ({
4698
+ context,
4699
+ suspend
4700
+ }) => {
4701
+ if (context.inputData?.resumedEvent) {
4702
+ return {
4703
+ executed: true,
4704
+ resumedEvent: context.inputData?.resumedEvent
4705
+ };
4706
+ }
4707
+ await suspend();
4708
+ return {
4709
+ executed: false
4710
+ };
4711
+ }
4712
+ });
4713
+ this.after(lastStep.step).step(eventStep).after(eventStep);
4714
+ this.#lastBuilderType = "afterEvent";
4715
+ return this;
4716
+ }
4717
+ /**
4718
+ * Executes the workflow with the given trigger data
4719
+ * @param triggerData - Initial data to start the workflow with
4720
+ * @returns Promise resolving to workflow results or rejecting with error
4721
+ * @throws Error if trigger schema validation fails
4722
+ */
4723
+ createRun({
4724
+ runId,
4725
+ events
4726
+ } = {}) {
4727
+ const run = new WorkflowInstance({
4728
+ logger: this.logger,
4729
+ name: this.name,
4730
+ mastra: this.#mastra,
4731
+ retryConfig: this.#retryConfig,
4732
+ steps: this.#steps,
4733
+ runId,
4734
+ stepGraph: this.#stepGraph,
4735
+ stepSubscriberGraph: this.#stepSubscriberGraph,
4736
+ onStepTransition: this.#onStepTransition,
4737
+ resultMapping: this.resultMapping,
4738
+ onFinish: () => {
4739
+ this.#runs.delete(run.runId);
4740
+ },
4741
+ events
4742
+ });
4743
+ this.#runs.set(run.runId, run);
4744
+ return {
4745
+ start: run.start.bind(run),
4746
+ runId: run.runId,
4747
+ watch: run.watch.bind(run),
4748
+ resume: run.resume.bind(run),
4749
+ resumeWithEvent: run.resumeWithEvent.bind(run)
4750
+ };
4751
+ }
4752
+ /**
4753
+ * Gets a workflow run instance by ID
4754
+ * @param runId - ID of the run to retrieve
4755
+ * @returns The workflow run instance if found, undefined otherwise
4756
+ */
4757
+ async getRun(runId) {
4758
+ const inMemoryRun = this.#runs.get(runId);
4759
+ if (inMemoryRun) {
4760
+ return inMemoryRun;
4761
+ }
4762
+ const storage = this.#mastra?.getStorage();
4763
+ if (!storage) {
4764
+ this.logger.debug("Cannot get workflow run. Mastra engine is not initialized");
4765
+ return null;
4766
+ }
4767
+ return await storage.getWorkflowRunById({
4768
+ runId,
4769
+ workflowName: this.name
4770
+ });
4771
+ }
4772
+ /**
4773
+ * Gets a workflow run instance by ID, from memory
4774
+ * @param runId - ID of the run to retrieve
4775
+ * @returns The workflow run instance if found, undefined otherwise
4776
+ */
4777
+ getMemoryRun(runId) {
4778
+ return this.#runs.get(runId);
4779
+ }
4780
+ /**
4781
+ * Rebuilds the machine with the current steps configuration and validates the workflow
4782
+ *
4783
+ * This is the last step of a workflow builder method chain
4784
+ * @throws Error if validation fails
4785
+ *
4786
+ * @returns this instance for method chaining
4787
+ */
4788
+ commit() {
4789
+ return this;
4790
+ }
4791
+ // record all object paths that leads to a suspended state
4792
+ #getSuspendedPaths({
4793
+ value,
4794
+ path,
4795
+ suspendedPaths
4796
+ }) {
4797
+ if (typeof value === "string") {
4798
+ if (value === "suspended") {
4799
+ suspendedPaths.add(path);
4800
+ }
4801
+ } else {
4802
+ Object.keys(value).forEach(key => this.#getSuspendedPaths({
4803
+ value: value[key],
4804
+ path: path ? `${path}.${key}` : key,
4805
+ suspendedPaths
4806
+ }));
4807
+ }
4808
+ }
4809
+ async getWorkflowRuns(args) {
4810
+ const storage = this.#mastra?.getStorage();
4811
+ if (!storage) {
4812
+ this.logger.debug("Cannot get workflow runs. Mastra engine is not initialized");
4813
+ return {
4814
+ runs: [],
4815
+ total: 0
4816
+ };
4817
+ }
4818
+ return storage.getWorkflowRuns({
4819
+ workflowName: this.name,
4820
+ ...(args ?? {})
4821
+ });
4822
+ }
4823
+ getExecutionSpan(runId) {
4824
+ return this.#runs.get(runId)?.executionSpan;
4825
+ }
4826
+ #getParentStepKey({
4827
+ loop_check = false,
4828
+ if_else_check = false
4829
+ } = {}) {
4830
+ for (let i = this.#afterStepStack.length - 1; i >= 0; i--) {
4831
+ const stepKey = this.#afterStepStack[i];
4832
+ if (!stepKey) continue;
4833
+ const isValidStep = this.#stepSubscriberGraph[stepKey] && (!loop_check || !stepKey.includes("loop_check")) && (!if_else_check || !isConditionalKey(stepKey));
4834
+ if (isValidStep) {
4835
+ return stepKey;
4836
+ }
4837
+ }
4838
+ return void 0;
4839
+ }
4840
+ #getLastStep({
4841
+ if_else_check
4842
+ }) {
4843
+ for (let i = this.#lastStepStack.length - 1; i >= 0; i--) {
4844
+ const stepKey = this.#lastStepStack[i];
4845
+ if (!stepKey) continue;
4846
+ const step = this.#steps[stepKey];
4847
+ const isInvalidStep = !step || if_else_check && isConditionalKey(stepKey);
4848
+ if (isInvalidStep) continue;
4849
+ return step;
4850
+ }
4851
+ return void 0;
4852
+ }
4853
+ #makeStepDef(stepId) {
4854
+ const executeStep = (handler2, spanName, attributes) => {
4855
+ return async data => {
4856
+ return await api.context.with(api.trace.setSpan(api.context.active(), this.getExecutionSpan(attributes?.runId ?? data?.runId)), async () => {
4857
+ if (this?.telemetry) {
4858
+ return this.telemetry.traceMethod(handler2, {
4859
+ spanName,
4860
+ attributes
4861
+ })(data);
4862
+ } else {
4863
+ return handler2(data);
4864
+ }
4865
+ });
4866
+ };
4867
+ };
4868
+ const handler = async ({
4869
+ context,
4870
+ ...rest
4871
+ }) => {
4872
+ const targetStep = this.#steps[stepId];
4873
+ if (!targetStep) throw new Error(`Step not found`);
4874
+ const {
4875
+ payload = {},
4876
+ execute = async () => {}
4877
+ } = targetStep.step;
4878
+ const finalAction = this.telemetry ? executeStep(execute, `workflow.${this.name}.action.${stepId}`, {
4879
+ componentName: this.name,
4880
+ runId: rest.runId
4881
+ }) : execute;
4882
+ return finalAction ? await finalAction({
4883
+ context: {
4884
+ ...context,
4885
+ inputData: {
4886
+ ...(context?.inputData || {}),
4887
+ ...payload
4888
+ }
4889
+ },
4890
+ ...rest
4891
+ }) : {};
4892
+ };
4893
+ const finalHandler = ({
4894
+ context,
4895
+ ...rest
4896
+ }) => {
4897
+ if (this.getExecutionSpan(rest?.runId)) {
4898
+ return executeStep(handler, `workflow.${this.name}.step.${stepId}`, {
4899
+ componentName: this.name,
4900
+ runId: rest?.runId
4901
+ })({
4902
+ context,
4903
+ ...rest
4904
+ });
4905
+ }
4906
+ return handler({
4907
+ context,
4908
+ ...rest
4909
+ });
4910
+ };
4911
+ return {
4912
+ handler: finalHandler,
4913
+ data: {}
4914
+ };
4915
+ }
4916
+ #getActivePathsAndStatus(value) {
4917
+ const paths = [];
4918
+ const traverse = (current, path = []) => {
4919
+ for (const [key, value2] of Object.entries(current)) {
4920
+ const currentPath = [...path, key];
4921
+ if (typeof value2 === "string") {
4922
+ paths.push({
4923
+ stepPath: currentPath,
4924
+ stepId: key,
4925
+ status: value2
4926
+ });
4927
+ } else if (typeof value2 === "object" && value2 !== null) {
4928
+ traverse(value2, currentPath);
4929
+ }
4930
+ }
4931
+ };
4932
+ traverse(value);
4933
+ return paths;
4934
+ }
4935
+ async getState(runId) {
4936
+ const run = this.#runs.get(runId);
4937
+ if (run) {
4938
+ return run.getState();
4939
+ }
4940
+ const storage = this.#mastra?.getStorage();
4941
+ const storedSnapshot = await storage?.loadWorkflowSnapshot({
4942
+ runId,
4943
+ workflowName: this.name
4944
+ });
4945
+ if (storedSnapshot) {
4946
+ const parsed = storedSnapshot;
4947
+ const m = this.#getActivePathsAndStatus(parsed.value);
4948
+ return {
4949
+ runId,
4950
+ value: parsed.value,
4951
+ context: parsed.context,
4952
+ activePaths: m,
4953
+ timestamp: Date.now()
4954
+ };
4955
+ }
4956
+ return null;
4957
+ }
4958
+ async resume({
4959
+ runId,
4960
+ stepId,
4961
+ context: resumeContext,
4962
+ runtimeContext = new chunkLABUWBKX_cjs.RuntimeContext()
4963
+ }) {
4964
+ this.logger.warn(`Please use 'resume' on the 'createRun' call instead, resume is deprecated`);
4965
+ const activeRun = this.#runs.get(runId);
4966
+ if (activeRun) {
4967
+ return activeRun.resume({
4968
+ stepId,
4969
+ context: resumeContext,
4970
+ runtimeContext
4971
+ });
4972
+ }
4973
+ const run = this.createRun({
4974
+ runId
4975
+ });
4976
+ return run.resume({
4977
+ stepId,
4978
+ context: resumeContext,
4979
+ runtimeContext
4980
+ });
4981
+ }
4982
+ watch(onTransition) {
4983
+ this.logger.warn(`Please use 'watch' on the 'createRun' call instead, watch is deprecated`);
4984
+ this.#onStepTransition.add(onTransition);
4985
+ return () => {
4986
+ this.#onStepTransition.delete(onTransition);
4987
+ };
4988
+ }
4989
+ async resumeWithEvent(runId, eventName, data) {
4990
+ this.logger.warn(`Please use 'resumeWithEvent' on the 'createRun' call instead, resumeWithEvent is deprecated`);
4991
+ const event = this.events?.[eventName];
4992
+ if (!event) {
4993
+ throw new Error(`Event ${eventName} not found`);
4994
+ }
4995
+ const results = await this.resume({
4996
+ runId,
4997
+ stepId: `__${eventName}_event`,
4998
+ context: {
4999
+ resumedEvent: data
5000
+ },
5001
+ runtimeContext: new chunkLABUWBKX_cjs.RuntimeContext()
5002
+ });
5003
+ return results;
5004
+ }
5005
+ __registerMastra(mastra) {
5006
+ this.#mastra = mastra;
5007
+ }
5008
+ __registerPrimitives(p) {
5009
+ if (p.telemetry) {
5010
+ this.__setTelemetry(p.telemetry);
5011
+ }
5012
+ if (p.logger) {
5013
+ this.__setLogger(p.logger);
5014
+ }
5015
+ }
5016
+ get stepGraph() {
5017
+ return this.#stepGraph;
5018
+ }
5019
+ get stepSubscriberGraph() {
5020
+ return this.#stepSubscriberGraph;
5021
+ }
5022
+ get serializedStepGraph() {
5023
+ return this.#serializedStepGraph;
5024
+ }
5025
+ get serializedStepSubscriberGraph() {
5026
+ return this.#serializedStepSubscriberGraph;
5027
+ }
5028
+ get steps() {
5029
+ return Object.entries(this.#steps).reduce((acc, [key, step]) => {
5030
+ acc[key] = step.step;
5031
+ return acc;
5032
+ }, {});
5033
+ }
5034
+ setNested(isNested) {
5035
+ this.isNested = isNested;
5036
+ }
5037
+ toStep() {
5038
+ const x = workflowToStep(this, {
5039
+ mastra: this.#mastra
5040
+ });
5041
+ return new LegacyStep(x);
5042
+ }
5043
+ };
5044
+
5045
+ exports.LegacyStep = LegacyStep;
5046
+ exports.LegacyWorkflow = LegacyWorkflow;
5047
+ exports.WhenConditionReturnValue = WhenConditionReturnValue;
5048
+ exports.agentToStep = agentToStep;
5049
+ exports.getActivePathsAndStatus = getActivePathsAndStatus;
5050
+ exports.getResultActivePaths = getResultActivePaths;
5051
+ exports.getStepResult = getStepResult;
5052
+ exports.getSuspendedPaths = getSuspendedPaths;
5053
+ exports.isAgent = isAgent;
5054
+ exports.isConditionalKey = isConditionalKey;
5055
+ exports.isErrorEvent = isErrorEvent;
5056
+ exports.isFinalState = isFinalState;
5057
+ exports.isLimboState = isLimboState;
5058
+ exports.isTransitionEvent = isTransitionEvent;
5059
+ exports.isVariableReference = isVariableReference;
5060
+ exports.isWorkflow = isWorkflow;
5061
+ exports.mergeChildValue = mergeChildValue;
5062
+ exports.recursivelyCheckForFinalState = recursivelyCheckForFinalState;
5063
+ exports.resolveVariables = resolveVariables;
5064
+ exports.updateStepInHierarchy = updateStepInHierarchy;
5065
+ exports.workflowToStep = workflowToStep;