@mastra/core 1.0.0-beta.13 → 1.0.0-beta.15

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 (442) hide show
  1. package/CHANGELOG.md +477 -0
  2. package/dist/agent/agent-legacy.d.ts.map +1 -1
  3. package/dist/agent/agent.d.ts +2 -2
  4. package/dist/agent/agent.d.ts.map +1 -1
  5. package/dist/agent/agent.types.d.ts +6 -7
  6. package/dist/agent/agent.types.d.ts.map +1 -1
  7. package/dist/agent/index.cjs +17 -9
  8. package/dist/agent/index.d.ts +1 -1
  9. package/dist/agent/index.d.ts.map +1 -1
  10. package/dist/agent/index.js +2 -2
  11. package/dist/agent/message-list/index.cjs +3 -3
  12. package/dist/agent/message-list/index.d.ts +1 -1
  13. package/dist/agent/message-list/index.d.ts.map +1 -1
  14. package/dist/agent/message-list/index.js +1 -1
  15. package/dist/agent/message-list/prompt/attachments-to-parts.d.ts.map +1 -1
  16. package/dist/agent/trip-wire.d.ts +2 -2
  17. package/dist/agent/trip-wire.d.ts.map +1 -1
  18. package/dist/agent/utils.d.ts +4 -1
  19. package/dist/agent/utils.d.ts.map +1 -1
  20. package/dist/agent/workflows/prepare-stream/index.d.ts +3 -3
  21. package/dist/agent/workflows/prepare-stream/index.d.ts.map +1 -1
  22. package/dist/agent/workflows/prepare-stream/map-results-step.d.ts +3 -3
  23. package/dist/agent/workflows/prepare-stream/map-results-step.d.ts.map +1 -1
  24. package/dist/agent/workflows/prepare-stream/prepare-memory-step.d.ts +3 -3
  25. package/dist/agent/workflows/prepare-stream/prepare-memory-step.d.ts.map +1 -1
  26. package/dist/agent/workflows/prepare-stream/prepare-tools-step.d.ts +3 -3
  27. package/dist/agent/workflows/prepare-stream/prepare-tools-step.d.ts.map +1 -1
  28. package/dist/bundler/types.d.ts +1 -0
  29. package/dist/bundler/types.d.ts.map +1 -1
  30. package/dist/chunk-2AU5ZHBL.js +79 -0
  31. package/dist/chunk-2AU5ZHBL.js.map +1 -0
  32. package/dist/{chunk-7HEAVZRS.cjs → chunk-2OOMJRXZ.cjs} +15 -15
  33. package/dist/{chunk-7HEAVZRS.cjs.map → chunk-2OOMJRXZ.cjs.map} +1 -1
  34. package/dist/chunk-37YWZMBX.js +27 -0
  35. package/dist/chunk-37YWZMBX.js.map +1 -0
  36. package/dist/{chunk-VETAQUW3.js → chunk-3HDRO3GG.js} +790 -1206
  37. package/dist/chunk-3HDRO3GG.js.map +1 -0
  38. package/dist/{chunk-MRRFTNF4.js → chunk-4DFWV4IR.js} +3 -4
  39. package/dist/chunk-4DFWV4IR.js.map +1 -0
  40. package/dist/{chunk-373OC54J.js → chunk-4HP7CS6L.js} +7 -6
  41. package/dist/chunk-4HP7CS6L.js.map +1 -0
  42. package/dist/{chunk-62Q7K656.js → chunk-4J4M2Q5R.js} +125 -121
  43. package/dist/chunk-4J4M2Q5R.js.map +1 -0
  44. package/dist/{chunk-HWMMIRIF.cjs → chunk-4U7ZLI36.cjs} +3 -2
  45. package/dist/chunk-4U7ZLI36.cjs.map +1 -0
  46. package/dist/{chunk-Z55SJVEC.cjs → chunk-6HJFCSJ4.cjs} +7 -6
  47. package/dist/chunk-6HJFCSJ4.cjs.map +1 -0
  48. package/dist/{chunk-Y7MZ5LJT.cjs → chunk-AAX7ZOM7.cjs} +101 -102
  49. package/dist/chunk-AAX7ZOM7.cjs.map +1 -0
  50. package/dist/{chunk-WPTTKULS.js → chunk-AR5CF3IN.js} +4 -4
  51. package/dist/{chunk-WPTTKULS.js.map → chunk-AR5CF3IN.js.map} +1 -1
  52. package/dist/{chunk-5VZGJTPR.js → chunk-BAZHNX5P.js} +57 -11
  53. package/dist/chunk-BAZHNX5P.js.map +1 -0
  54. package/dist/{chunk-MLKE7HRS.cjs → chunk-BC2VKOH4.cjs} +43 -21
  55. package/dist/chunk-BC2VKOH4.cjs.map +1 -0
  56. package/dist/{chunk-2IU4RGU5.js → chunk-BCUKD2XG.js} +59 -19
  57. package/dist/chunk-BCUKD2XG.js.map +1 -0
  58. package/dist/{chunk-WYGUWVTF.js → chunk-CBQ6WDUJ.js} +9 -9
  59. package/dist/chunk-CBQ6WDUJ.js.map +1 -0
  60. package/dist/chunk-CBVHOGXX.cjs +674 -0
  61. package/dist/chunk-CBVHOGXX.cjs.map +1 -0
  62. package/dist/{chunk-PJAK4U6R.cjs → chunk-CBY37FTP.cjs} +28 -28
  63. package/dist/chunk-CBY37FTP.cjs.map +1 -0
  64. package/dist/{chunk-BQDZIQ3G.js → chunk-D2IFWD7A.js} +365 -137
  65. package/dist/chunk-D2IFWD7A.js.map +1 -0
  66. package/dist/{chunk-R5AJGM55.cjs → chunk-DDK3URK2.cjs} +987 -519
  67. package/dist/chunk-DDK3URK2.cjs.map +1 -0
  68. package/dist/chunk-DRJTNGI4.cjs +263 -0
  69. package/dist/chunk-DRJTNGI4.cjs.map +1 -0
  70. package/dist/{chunk-X6IBA7FP.cjs → chunk-EMLEZXTQ.cjs} +22 -120
  71. package/dist/chunk-EMLEZXTQ.cjs.map +1 -0
  72. package/dist/{chunk-OWIEOL55.cjs → chunk-F75EQ574.cjs} +695 -254
  73. package/dist/chunk-F75EQ574.cjs.map +1 -0
  74. package/dist/{chunk-YPLZDWG7.js → chunk-FJEVLHJT.js} +3 -2
  75. package/dist/chunk-FJEVLHJT.js.map +1 -0
  76. package/dist/chunk-GVAPYQRO.cjs +252 -0
  77. package/dist/chunk-GVAPYQRO.cjs.map +1 -0
  78. package/dist/{chunk-MXBVP7HX.cjs → chunk-GXMJ5URG.cjs} +227 -181
  79. package/dist/chunk-GXMJ5URG.cjs.map +1 -0
  80. package/dist/chunk-H2NHG7QL.cjs +32 -0
  81. package/dist/chunk-H2NHG7QL.cjs.map +1 -0
  82. package/dist/chunk-HAYBGFPA.js +259 -0
  83. package/dist/chunk-HAYBGFPA.js.map +1 -0
  84. package/dist/{chunk-GIWC35YQ.js → chunk-IHISDRFV.js} +299 -49
  85. package/dist/chunk-IHISDRFV.js.map +1 -0
  86. package/dist/{chunk-VEPP75C4.cjs → chunk-IRTICXRZ.cjs} +101 -61
  87. package/dist/chunk-IRTICXRZ.cjs.map +1 -0
  88. package/dist/{chunk-ARAQIW6E.js → chunk-K66U47VL.js} +617 -188
  89. package/dist/chunk-K66U47VL.js.map +1 -0
  90. package/dist/{chunk-LGB4VNZI.cjs → chunk-LOV5NNGK.cjs} +811 -1235
  91. package/dist/chunk-LOV5NNGK.cjs.map +1 -0
  92. package/dist/{chunk-E5BQRAJK.js → chunk-NGWTSHNA.js} +823 -362
  93. package/dist/chunk-NGWTSHNA.js.map +1 -0
  94. package/dist/{chunk-72YCRTEX.cjs → chunk-O2CAMK4A.cjs} +13 -2
  95. package/dist/chunk-O2CAMK4A.cjs.map +1 -0
  96. package/dist/{chunk-4BC5FUAO.js → chunk-O7M7DR4E.js} +6 -5
  97. package/dist/chunk-O7M7DR4E.js.map +1 -0
  98. package/dist/chunk-OTIGV7CL.js +10215 -0
  99. package/dist/chunk-OTIGV7CL.js.map +1 -0
  100. package/dist/{chunk-WYWRMIQC.js → chunk-QXL3F3T2.js} +9 -105
  101. package/dist/chunk-QXL3F3T2.js.map +1 -0
  102. package/dist/{chunk-U4CSOY6T.cjs → chunk-RA2CHJCY.cjs} +399 -171
  103. package/dist/chunk-RA2CHJCY.cjs.map +1 -0
  104. package/dist/chunk-RMV5HJM7.cjs +10237 -0
  105. package/dist/chunk-RMV5HJM7.cjs.map +1 -0
  106. package/dist/{chunk-AGHLXC4I.cjs → chunk-S23TNDXG.cjs} +300 -50
  107. package/dist/chunk-S23TNDXG.cjs.map +1 -0
  108. package/dist/{chunk-H4VUIOWU.cjs → chunk-SSB4AVHU.cjs} +20 -19
  109. package/dist/chunk-SSB4AVHU.cjs.map +1 -0
  110. package/dist/chunk-ST7NBF4H.cjs +84 -0
  111. package/dist/chunk-ST7NBF4H.cjs.map +1 -0
  112. package/dist/{chunk-SZYSDJTN.cjs → chunk-T2LVULCK.cjs} +142 -137
  113. package/dist/chunk-T2LVULCK.cjs.map +1 -0
  114. package/dist/chunk-VE6HQ7H6.js +250 -0
  115. package/dist/chunk-VE6HQ7H6.js.map +1 -0
  116. package/dist/{chunk-RCJLMMTO.js → chunk-XJB7J4UT.js} +30 -8
  117. package/dist/chunk-XJB7J4UT.js.map +1 -0
  118. package/dist/chunk-YV43YEZ6.js +598 -0
  119. package/dist/chunk-YV43YEZ6.js.map +1 -0
  120. package/dist/{chunk-Y36Y5MTD.js → chunk-ZGIVAQRI.js} +13 -3
  121. package/dist/chunk-ZGIVAQRI.js.map +1 -0
  122. package/dist/error/index.cjs +6 -6
  123. package/dist/error/index.d.ts +1 -0
  124. package/dist/error/index.d.ts.map +1 -1
  125. package/dist/error/index.js +1 -1
  126. package/dist/evals/index.cjs +49 -9
  127. package/dist/evals/index.js +2 -2
  128. package/dist/evals/run/index.d.ts.map +1 -1
  129. package/dist/evals/scoreTraces/index.cjs +70 -22
  130. package/dist/evals/scoreTraces/index.cjs.map +1 -1
  131. package/dist/evals/scoreTraces/index.js +63 -15
  132. package/dist/evals/scoreTraces/index.js.map +1 -1
  133. package/dist/evals/scoreTraces/scoreTracesWorkflow.d.ts.map +1 -1
  134. package/dist/evals/scoreTraces/utils.d.ts.map +1 -1
  135. package/dist/evals/types.d.ts +568 -116
  136. package/dist/evals/types.d.ts.map +1 -1
  137. package/dist/index.cjs +2 -2
  138. package/dist/index.js +1 -1
  139. package/dist/integration/index.cjs +2 -2
  140. package/dist/integration/index.js +1 -1
  141. package/dist/llm/index.cjs +21 -21
  142. package/dist/llm/index.js +5 -5
  143. package/dist/llm/model/aisdk/generate-to-stream.d.ts +20 -0
  144. package/dist/llm/model/aisdk/generate-to-stream.d.ts.map +1 -0
  145. package/dist/llm/model/aisdk/v5/model.d.ts +4 -0
  146. package/dist/llm/model/aisdk/v5/model.d.ts.map +1 -1
  147. package/dist/llm/model/aisdk/v6/model.d.ts +43 -0
  148. package/dist/llm/model/aisdk/v6/model.d.ts.map +1 -0
  149. package/dist/llm/model/embedding-router.d.ts +1 -1
  150. package/dist/llm/model/model.d.ts.map +1 -1
  151. package/dist/llm/model/model.loop.d.ts +1 -1
  152. package/dist/llm/model/model.loop.d.ts.map +1 -1
  153. package/dist/llm/model/provider-options.d.ts +2 -1
  154. package/dist/llm/model/provider-options.d.ts.map +1 -1
  155. package/dist/llm/model/provider-types.generated.d.ts +126 -17
  156. package/dist/llm/model/resolve-model.d.ts +2 -2
  157. package/dist/llm/model/resolve-model.d.ts.map +1 -1
  158. package/dist/llm/model/shared.types.d.ts +18 -7
  159. package/dist/llm/model/shared.types.d.ts.map +1 -1
  160. package/dist/loop/index.cjs +2 -2
  161. package/dist/loop/index.js +1 -1
  162. package/dist/loop/network/index.d.ts +8 -8
  163. package/dist/loop/network/index.d.ts.map +1 -1
  164. package/dist/loop/test-utils/MastraLanguageModelV2Mock.d.ts +1 -1
  165. package/dist/loop/test-utils/MastraLanguageModelV2Mock.d.ts.map +1 -1
  166. package/dist/loop/test-utils/MastraLanguageModelV3Mock.d.ts +29 -0
  167. package/dist/loop/test-utils/MastraLanguageModelV3Mock.d.ts.map +1 -0
  168. package/dist/loop/test-utils/fullStream.d.ts +2 -1
  169. package/dist/loop/test-utils/fullStream.d.ts.map +1 -1
  170. package/dist/loop/test-utils/resultObject.d.ts +2 -1
  171. package/dist/loop/test-utils/resultObject.d.ts.map +1 -1
  172. package/dist/loop/test-utils/streamObject.d.ts.map +1 -1
  173. package/dist/loop/test-utils/utils-v3.d.ts +55 -0
  174. package/dist/loop/test-utils/utils-v3.d.ts.map +1 -0
  175. package/dist/loop/types.d.ts +10 -8
  176. package/dist/loop/types.d.ts.map +1 -1
  177. package/dist/loop/workflows/agentic-execution/index.d.ts +36 -36
  178. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts +25 -25
  179. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts.map +1 -1
  180. package/dist/loop/workflows/agentic-execution/llm-mapping-step.d.ts +12 -12
  181. package/dist/loop/workflows/agentic-execution/tool-call-step.d.ts.map +1 -1
  182. package/dist/loop/workflows/agentic-loop/index.d.ts +36 -36
  183. package/dist/loop/workflows/agentic-loop/index.d.ts.map +1 -1
  184. package/dist/loop/workflows/run-state.d.ts +2 -2
  185. package/dist/loop/workflows/run-state.d.ts.map +1 -1
  186. package/dist/loop/workflows/schema.d.ts +12 -12
  187. package/dist/mastra/hooks.d.ts.map +1 -1
  188. package/dist/mastra/index.cjs +2 -2
  189. package/dist/mastra/index.d.ts +7 -2
  190. package/dist/mastra/index.d.ts.map +1 -1
  191. package/dist/mastra/index.js +1 -1
  192. package/dist/mcp/index.cjs +4 -4
  193. package/dist/mcp/index.js +1 -1
  194. package/dist/memory/index.cjs +26 -6
  195. package/dist/memory/index.d.ts +1 -0
  196. package/dist/memory/index.d.ts.map +1 -1
  197. package/dist/memory/index.js +1 -1
  198. package/dist/memory/memory.d.ts +9 -8
  199. package/dist/memory/memory.d.ts.map +1 -1
  200. package/dist/memory/mock.d.ts +2 -1
  201. package/dist/memory/mock.d.ts.map +1 -1
  202. package/dist/memory/types.d.ts +3 -4
  203. package/dist/memory/types.d.ts.map +1 -1
  204. package/dist/memory/working-memory-utils.d.ts +20 -0
  205. package/dist/memory/working-memory-utils.d.ts.map +1 -0
  206. package/dist/models-dev-26XLUKVK.cjs +12 -0
  207. package/dist/{models-dev-D3EKFGAO.cjs.map → models-dev-26XLUKVK.cjs.map} +1 -1
  208. package/dist/models-dev-HUFLQFPB.js +3 -0
  209. package/dist/{models-dev-EO22XOXQ.js.map → models-dev-HUFLQFPB.js.map} +1 -1
  210. package/dist/netlify-CUYK2MZ2.cjs +12 -0
  211. package/dist/{netlify-WE42TZIT.cjs.map → netlify-CUYK2MZ2.cjs.map} +1 -1
  212. package/dist/netlify-J4QPOROO.js +3 -0
  213. package/dist/{netlify-AE4LNCAI.js.map → netlify-J4QPOROO.js.map} +1 -1
  214. package/dist/observability/index.cjs +14 -10
  215. package/dist/observability/index.js +1 -1
  216. package/dist/observability/types/tracing.d.ts +32 -19
  217. package/dist/observability/types/tracing.d.ts.map +1 -1
  218. package/dist/processors/index.cjs +37 -37
  219. package/dist/processors/index.d.ts +9 -7
  220. package/dist/processors/index.d.ts.map +1 -1
  221. package/dist/processors/index.js +1 -1
  222. package/dist/processors/memory/message-history.d.ts +7 -1
  223. package/dist/processors/memory/message-history.d.ts.map +1 -1
  224. package/dist/processors/processors/language-detector.d.ts.map +1 -1
  225. package/dist/processors/processors/moderation.d.ts.map +1 -1
  226. package/dist/processors/processors/pii-detector.d.ts.map +1 -1
  227. package/dist/processors/processors/prompt-injection-detector.d.ts.map +1 -1
  228. package/dist/processors/processors/token-limiter.d.ts +5 -2
  229. package/dist/processors/processors/token-limiter.d.ts.map +1 -1
  230. package/dist/processors/runner.d.ts +2 -0
  231. package/dist/processors/runner.d.ts.map +1 -1
  232. package/dist/processors/step-schema.d.ts +26 -26
  233. package/dist/processors/step-schema.d.ts.map +1 -1
  234. package/dist/provider-registry-6CIGRQVZ.js +3 -0
  235. package/dist/{provider-registry-6LF3NGC5.js.map → provider-registry-6CIGRQVZ.js.map} +1 -1
  236. package/dist/provider-registry-7O7FJ4BS.cjs +40 -0
  237. package/dist/{provider-registry-73FKMXJV.cjs.map → provider-registry-7O7FJ4BS.cjs.map} +1 -1
  238. package/dist/provider-registry.json +295 -45
  239. package/dist/relevance/index.cjs +3 -3
  240. package/dist/relevance/index.cjs.map +1 -1
  241. package/dist/relevance/index.js +2 -2
  242. package/dist/relevance/index.js.map +1 -1
  243. package/dist/server/index.cjs +5 -5
  244. package/dist/server/index.js +1 -1
  245. package/dist/storage/base.d.ts +40 -292
  246. package/dist/storage/base.d.ts.map +1 -1
  247. package/dist/storage/constants.cjs +60 -0
  248. package/dist/storage/constants.cjs.map +1 -0
  249. package/dist/storage/constants.d.ts +6 -1
  250. package/dist/storage/constants.d.ts.map +1 -1
  251. package/dist/storage/constants.js +3 -0
  252. package/dist/storage/constants.js.map +1 -0
  253. package/dist/storage/domains/agents/base.d.ts +2 -2
  254. package/dist/storage/domains/agents/base.d.ts.map +1 -1
  255. package/dist/storage/domains/agents/inmemory.d.ts +5 -4
  256. package/dist/storage/domains/agents/inmemory.d.ts.map +1 -1
  257. package/dist/storage/domains/base.d.ts +20 -0
  258. package/dist/storage/domains/base.d.ts.map +1 -0
  259. package/dist/storage/domains/index.d.ts +3 -0
  260. package/dist/storage/domains/index.d.ts.map +1 -1
  261. package/dist/storage/domains/inmemory-db.d.ts +57 -0
  262. package/dist/storage/domains/inmemory-db.d.ts.map +1 -0
  263. package/dist/storage/domains/memory/base.d.ts +2 -2
  264. package/dist/storage/domains/memory/base.d.ts.map +1 -1
  265. package/dist/storage/domains/memory/inmemory.d.ts +5 -13
  266. package/dist/storage/domains/memory/inmemory.d.ts.map +1 -1
  267. package/dist/storage/domains/observability/base.d.ts +24 -29
  268. package/dist/storage/domains/observability/base.d.ts.map +1 -1
  269. package/dist/storage/domains/observability/index.d.ts +1 -0
  270. package/dist/storage/domains/observability/index.d.ts.map +1 -1
  271. package/dist/storage/domains/observability/inmemory.d.ts +46 -35
  272. package/dist/storage/domains/observability/inmemory.d.ts.map +1 -1
  273. package/dist/storage/domains/observability/types.d.ts +2365 -0
  274. package/dist/storage/domains/observability/types.d.ts.map +1 -0
  275. package/dist/storage/domains/scores/base.d.ts +9 -20
  276. package/dist/storage/domains/scores/base.d.ts.map +1 -1
  277. package/dist/storage/domains/scores/inmemory.d.ts +11 -22
  278. package/dist/storage/domains/scores/inmemory.d.ts.map +1 -1
  279. package/dist/storage/domains/shared.d.ts +76 -0
  280. package/dist/storage/domains/shared.d.ts.map +1 -0
  281. package/dist/storage/domains/workflows/base.d.ts +4 -2
  282. package/dist/storage/domains/workflows/base.d.ts.map +1 -1
  283. package/dist/storage/domains/workflows/inmemory.d.ts +10 -9
  284. package/dist/storage/domains/workflows/inmemory.d.ts.map +1 -1
  285. package/dist/storage/index.cjs +272 -59
  286. package/dist/storage/index.js +2 -1
  287. package/dist/storage/mock.d.ts +28 -174
  288. package/dist/storage/mock.d.ts.map +1 -1
  289. package/dist/storage/types.d.ts +39 -44
  290. package/dist/storage/types.d.ts.map +1 -1
  291. package/dist/storage/utils.d.ts +5 -0
  292. package/dist/storage/utils.d.ts.map +1 -1
  293. package/dist/stream/MastraAgentNetworkStream.d.ts +1 -1
  294. package/dist/stream/MastraAgentNetworkStream.d.ts.map +1 -1
  295. package/dist/stream/MastraWorkflowStream.d.ts +1 -1
  296. package/dist/stream/MastraWorkflowStream.d.ts.map +1 -1
  297. package/dist/stream/RunOutput.d.ts.map +1 -1
  298. package/dist/stream/aisdk/v5/execute.d.ts +4 -4
  299. package/dist/stream/aisdk/v5/execute.d.ts.map +1 -1
  300. package/dist/stream/aisdk/v5/output.d.ts +2 -2
  301. package/dist/stream/aisdk/v5/output.d.ts.map +1 -1
  302. package/dist/stream/aisdk/v5/transform.d.ts.map +1 -1
  303. package/dist/stream/base/output.d.ts +7 -5
  304. package/dist/stream/base/output.d.ts.map +1 -1
  305. package/dist/stream/index.cjs +12 -12
  306. package/dist/stream/index.js +2 -2
  307. package/dist/stream/types.d.ts +32 -21
  308. package/dist/stream/types.d.ts.map +1 -1
  309. package/dist/test-utils/llm-mock.cjs +4 -4
  310. package/dist/test-utils/llm-mock.cjs.map +1 -1
  311. package/dist/test-utils/llm-mock.js +1 -1
  312. package/dist/test-utils/llm-mock.js.map +1 -1
  313. package/dist/token-6GSAFR2W-LTZ7QQUP.js +61 -0
  314. package/dist/token-6GSAFR2W-LTZ7QQUP.js.map +1 -0
  315. package/dist/token-6GSAFR2W-UEEINYAN.cjs +63 -0
  316. package/dist/token-6GSAFR2W-UEEINYAN.cjs.map +1 -0
  317. package/dist/token-util-NEHG7TUY-QTFZ26EN.js +8 -0
  318. package/dist/token-util-NEHG7TUY-QTFZ26EN.js.map +1 -0
  319. package/dist/token-util-NEHG7TUY-WZL2DNCG.cjs +10 -0
  320. package/dist/token-util-NEHG7TUY-WZL2DNCG.cjs.map +1 -0
  321. package/dist/tool-loop-agent/index.cjs +20 -0
  322. package/dist/tool-loop-agent/index.cjs.map +1 -0
  323. package/dist/tool-loop-agent/index.d.ts +36 -0
  324. package/dist/tool-loop-agent/index.d.ts.map +1 -0
  325. package/dist/tool-loop-agent/index.js +3 -0
  326. package/dist/tool-loop-agent/index.js.map +1 -0
  327. package/dist/tool-loop-agent/tool-loop-processor.d.ts +30 -0
  328. package/dist/tool-loop-agent/tool-loop-processor.d.ts.map +1 -0
  329. package/dist/tool-loop-agent/utils.d.ts +17 -0
  330. package/dist/tool-loop-agent/utils.d.ts.map +1 -0
  331. package/dist/tools/index.cjs +4 -4
  332. package/dist/tools/index.js +1 -1
  333. package/dist/tools/is-vercel-tool.cjs +2 -2
  334. package/dist/tools/is-vercel-tool.js +1 -1
  335. package/dist/tools/tool-builder/builder.d.ts.map +1 -1
  336. package/dist/tools/toolchecks.d.ts +1 -1
  337. package/dist/tools/toolchecks.d.ts.map +1 -1
  338. package/dist/tools/validation.d.ts +1 -1
  339. package/dist/tools/validation.d.ts.map +1 -1
  340. package/dist/utils/zod-utils.d.ts +34 -0
  341. package/dist/utils/zod-utils.d.ts.map +1 -0
  342. package/dist/utils.cjs +39 -22
  343. package/dist/utils.d.ts +3 -3
  344. package/dist/utils.d.ts.map +1 -1
  345. package/dist/utils.js +2 -1
  346. package/dist/vector/embed.d.ts +1 -0
  347. package/dist/vector/embed.d.ts.map +1 -1
  348. package/dist/vector/index.cjs +18 -5
  349. package/dist/vector/index.cjs.map +1 -1
  350. package/dist/vector/index.js +9 -2
  351. package/dist/vector/index.js.map +1 -1
  352. package/dist/vector/vector.d.ts +26 -3
  353. package/dist/vector/vector.d.ts.map +1 -1
  354. package/dist/voice/composite-voice.d.ts.map +1 -1
  355. package/dist/voice/index.cjs +6 -6
  356. package/dist/voice/index.js +1 -1
  357. package/dist/workflows/default.d.ts +2 -0
  358. package/dist/workflows/default.d.ts.map +1 -1
  359. package/dist/workflows/evented/execution-engine.d.ts +1 -0
  360. package/dist/workflows/evented/execution-engine.d.ts.map +1 -1
  361. package/dist/workflows/evented/index.cjs +10 -10
  362. package/dist/workflows/evented/index.js +1 -1
  363. package/dist/workflows/evented/step-executor.d.ts +5 -0
  364. package/dist/workflows/evented/step-executor.d.ts.map +1 -1
  365. package/dist/workflows/evented/workflow-event-processor/index.d.ts +20 -4
  366. package/dist/workflows/evented/workflow-event-processor/index.d.ts.map +1 -1
  367. package/dist/workflows/evented/workflow-event-processor/loop.d.ts +2 -2
  368. package/dist/workflows/evented/workflow-event-processor/loop.d.ts.map +1 -1
  369. package/dist/workflows/evented/workflow-event-processor/parallel.d.ts +2 -2
  370. package/dist/workflows/evented/workflow-event-processor/parallel.d.ts.map +1 -1
  371. package/dist/workflows/evented/workflow-event-processor/sleep.d.ts +2 -2
  372. package/dist/workflows/evented/workflow-event-processor/sleep.d.ts.map +1 -1
  373. package/dist/workflows/evented/workflow.d.ts +10 -2
  374. package/dist/workflows/evented/workflow.d.ts.map +1 -1
  375. package/dist/workflows/execution-engine.d.ts +1 -0
  376. package/dist/workflows/execution-engine.d.ts.map +1 -1
  377. package/dist/workflows/handlers/control-flow.d.ts +4 -0
  378. package/dist/workflows/handlers/control-flow.d.ts.map +1 -1
  379. package/dist/workflows/handlers/entry.d.ts +3 -2
  380. package/dist/workflows/handlers/entry.d.ts.map +1 -1
  381. package/dist/workflows/handlers/step.d.ts +1 -0
  382. package/dist/workflows/handlers/step.d.ts.map +1 -1
  383. package/dist/workflows/index.cjs +23 -23
  384. package/dist/workflows/index.js +1 -1
  385. package/dist/workflows/types.d.ts +23 -3
  386. package/dist/workflows/types.d.ts.map +1 -1
  387. package/dist/workflows/utils.d.ts +1 -0
  388. package/dist/workflows/utils.d.ts.map +1 -1
  389. package/dist/workflows/workflow.d.ts +26 -9
  390. package/dist/workflows/workflow.d.ts.map +1 -1
  391. package/package.json +20 -12
  392. package/src/llm/model/provider-types.generated.d.ts +126 -17
  393. package/storage/constants.d.ts +1 -0
  394. package/tool-loop-agent.d.ts +1 -0
  395. package/dist/chunk-2IU4RGU5.js.map +0 -1
  396. package/dist/chunk-373OC54J.js.map +0 -1
  397. package/dist/chunk-4BC5FUAO.js.map +0 -1
  398. package/dist/chunk-5VZGJTPR.js.map +0 -1
  399. package/dist/chunk-62Q7K656.js.map +0 -1
  400. package/dist/chunk-72YCRTEX.cjs.map +0 -1
  401. package/dist/chunk-ADADLFDR.js +0 -42
  402. package/dist/chunk-ADADLFDR.js.map +0 -1
  403. package/dist/chunk-AGHLXC4I.cjs.map +0 -1
  404. package/dist/chunk-ARAQIW6E.js.map +0 -1
  405. package/dist/chunk-BQDZIQ3G.js.map +0 -1
  406. package/dist/chunk-E5BQRAJK.js.map +0 -1
  407. package/dist/chunk-GIWC35YQ.js.map +0 -1
  408. package/dist/chunk-H4VUIOWU.cjs.map +0 -1
  409. package/dist/chunk-HWMMIRIF.cjs.map +0 -1
  410. package/dist/chunk-IXZ2T2QX.cjs +0 -448
  411. package/dist/chunk-IXZ2T2QX.cjs.map +0 -1
  412. package/dist/chunk-LGB4VNZI.cjs.map +0 -1
  413. package/dist/chunk-MLKE7HRS.cjs.map +0 -1
  414. package/dist/chunk-MRRFTNF4.js.map +0 -1
  415. package/dist/chunk-MXBVP7HX.cjs.map +0 -1
  416. package/dist/chunk-OWIEOL55.cjs.map +0 -1
  417. package/dist/chunk-PJAK4U6R.cjs.map +0 -1
  418. package/dist/chunk-R5AJGM55.cjs.map +0 -1
  419. package/dist/chunk-RCJLMMTO.js.map +0 -1
  420. package/dist/chunk-SZYSDJTN.cjs.map +0 -1
  421. package/dist/chunk-T2VLUFGG.cjs +0 -47
  422. package/dist/chunk-T2VLUFGG.cjs.map +0 -1
  423. package/dist/chunk-U4CSOY6T.cjs.map +0 -1
  424. package/dist/chunk-UBSPZTQX.js +0 -434
  425. package/dist/chunk-UBSPZTQX.js.map +0 -1
  426. package/dist/chunk-VEPP75C4.cjs.map +0 -1
  427. package/dist/chunk-VETAQUW3.js.map +0 -1
  428. package/dist/chunk-WYGUWVTF.js.map +0 -1
  429. package/dist/chunk-WYWRMIQC.js.map +0 -1
  430. package/dist/chunk-X6IBA7FP.cjs.map +0 -1
  431. package/dist/chunk-Y36Y5MTD.js.map +0 -1
  432. package/dist/chunk-Y7MZ5LJT.cjs.map +0 -1
  433. package/dist/chunk-YPLZDWG7.js.map +0 -1
  434. package/dist/chunk-Z55SJVEC.cjs.map +0 -1
  435. package/dist/llm/model/is-v2-model.d.ts +0 -3
  436. package/dist/llm/model/is-v2-model.d.ts.map +0 -1
  437. package/dist/models-dev-D3EKFGAO.cjs +0 -12
  438. package/dist/models-dev-EO22XOXQ.js +0 -3
  439. package/dist/netlify-AE4LNCAI.js +0 -3
  440. package/dist/netlify-WE42TZIT.cjs +0 -12
  441. package/dist/provider-registry-6LF3NGC5.js +0 -3
  442. package/dist/provider-registry-73FKMXJV.cjs +0 -40
@@ -1,186 +1,9 @@
1
- import { MessageList } from './chunk-WYWRMIQC.js';
2
- import { MastraError } from './chunk-YPLZDWG7.js';
1
+ import { MessageList } from './chunk-QXL3F3T2.js';
2
+ import { TABLE_SCHEMAS, TABLE_SCORERS, listTracesArgsSchema, TABLE_WORKFLOW_SNAPSHOT } from './chunk-YV43YEZ6.js';
3
+ import { MastraError } from './chunk-FJEVLHJT.js';
3
4
  import { MastraBase } from './chunk-LSHPJWM5.js';
4
5
 
5
- // src/storage/constants.ts
6
- var TABLE_WORKFLOW_SNAPSHOT = "mastra_workflow_snapshot";
7
- var TABLE_MESSAGES = "mastra_messages";
8
- var TABLE_THREADS = "mastra_threads";
9
- var TABLE_TRACES = "mastra_traces";
10
- var TABLE_RESOURCES = "mastra_resources";
11
- var TABLE_SCORERS = "mastra_scorers";
12
- var TABLE_SPANS = "mastra_ai_spans";
13
- var TABLE_AGENTS = "mastra_agents";
14
- var SCORERS_SCHEMA = {
15
- id: { type: "text", nullable: false, primaryKey: true },
16
- scorerId: { type: "text" },
17
- traceId: { type: "text", nullable: true },
18
- spanId: { type: "text", nullable: true },
19
- runId: { type: "text" },
20
- scorer: { type: "jsonb" },
21
- preprocessStepResult: { type: "jsonb", nullable: true },
22
- extractStepResult: { type: "jsonb", nullable: true },
23
- analyzeStepResult: { type: "jsonb", nullable: true },
24
- score: { type: "float" },
25
- reason: { type: "text", nullable: true },
26
- metadata: { type: "jsonb", nullable: true },
27
- preprocessPrompt: { type: "text", nullable: true },
28
- extractPrompt: { type: "text", nullable: true },
29
- generateScorePrompt: { type: "text", nullable: true },
30
- generateReasonPrompt: { type: "text", nullable: true },
31
- analyzePrompt: { type: "text", nullable: true },
32
- // Deprecated
33
- reasonPrompt: { type: "text", nullable: true },
34
- input: { type: "jsonb" },
35
- output: { type: "jsonb" },
36
- // MESSAGE OUTPUT
37
- additionalContext: { type: "jsonb", nullable: true },
38
- // DATA FROM THE CONTEXT PARAM ON AN AGENT
39
- requestContext: { type: "jsonb", nullable: true },
40
- // THE EVALUATE Request Context FOR THE RUN
41
- /**
42
- * Things you can evaluate
43
- */
44
- entityType: { type: "text", nullable: true },
45
- // WORKFLOW, AGENT, TOOL, STEP, NETWORK
46
- entity: { type: "jsonb", nullable: true },
47
- // MINIMAL JSON DATA ABOUT WORKFLOW, AGENT, TOOL, STEP, NETWORK
48
- entityId: { type: "text", nullable: true },
49
- source: { type: "text" },
50
- resourceId: { type: "text", nullable: true },
51
- threadId: { type: "text", nullable: true },
52
- createdAt: { type: "timestamp" },
53
- updatedAt: { type: "timestamp" }
54
- };
55
- var SPAN_SCHEMA = {
56
- // Composite primary key of traceId and spanId
57
- traceId: { type: "text", nullable: false },
58
- spanId: { type: "text", nullable: false },
59
- parentSpanId: { type: "text", nullable: true },
60
- name: { type: "text", nullable: false },
61
- scope: { type: "jsonb", nullable: true },
62
- // Mastra package info {"core-version": "0.1.0"}
63
- spanType: { type: "text", nullable: false },
64
- // WORKFLOW_RUN, WORKFLOW_STEP, AGENT_RUN, AGENT_STEP, TOOL_RUN, TOOL_STEP, etc.
65
- attributes: { type: "jsonb", nullable: true },
66
- metadata: { type: "jsonb", nullable: true },
67
- links: { type: "jsonb", nullable: true },
68
- input: { type: "jsonb", nullable: true },
69
- output: { type: "jsonb", nullable: true },
70
- error: { type: "jsonb", nullable: true },
71
- startedAt: { type: "timestamp", nullable: false },
72
- // When the span started
73
- endedAt: { type: "timestamp", nullable: true },
74
- // When the span ended
75
- createdAt: { type: "timestamp", nullable: false },
76
- // The time the database record was created
77
- updatedAt: { type: "timestamp", nullable: true },
78
- // The time the database record was last updated
79
- isEvent: { type: "boolean", nullable: false }
80
- };
81
- var AGENTS_SCHEMA = {
82
- id: { type: "text", nullable: false, primaryKey: true },
83
- name: { type: "text", nullable: false },
84
- description: { type: "text", nullable: true },
85
- instructions: { type: "text", nullable: false },
86
- // System instructions for the agent
87
- model: { type: "jsonb", nullable: false },
88
- // Model configuration (provider, name, etc.)
89
- tools: { type: "jsonb", nullable: true },
90
- // Serialized tool references/configurations
91
- defaultOptions: { type: "jsonb", nullable: true },
92
- // Default options for generate/stream calls
93
- workflows: { type: "jsonb", nullable: true },
94
- // Workflow references (IDs or configurations)
95
- agents: { type: "jsonb", nullable: true },
96
- // Sub-agent references (IDs or configurations)
97
- inputProcessors: { type: "jsonb", nullable: true },
98
- // Input processor configurations
99
- outputProcessors: { type: "jsonb", nullable: true },
100
- // Output processor configurations
101
- memory: { type: "jsonb", nullable: true },
102
- // Memory configuration
103
- scorers: { type: "jsonb", nullable: true },
104
- // Scorer configurations
105
- metadata: { type: "jsonb", nullable: true },
106
- // Additional metadata for the agent
107
- createdAt: { type: "timestamp", nullable: false },
108
- updatedAt: { type: "timestamp", nullable: false }
109
- };
110
- var TABLE_SCHEMAS = {
111
- [TABLE_WORKFLOW_SNAPSHOT]: {
112
- workflow_name: {
113
- type: "text"
114
- },
115
- run_id: {
116
- type: "text"
117
- },
118
- resourceId: { type: "text", nullable: true },
119
- snapshot: {
120
- type: "text"
121
- },
122
- createdAt: {
123
- type: "timestamp"
124
- },
125
- updatedAt: {
126
- type: "timestamp"
127
- }
128
- },
129
- [TABLE_SCORERS]: SCORERS_SCHEMA,
130
- [TABLE_THREADS]: {
131
- id: { type: "text", nullable: false, primaryKey: true },
132
- resourceId: { type: "text", nullable: false },
133
- title: { type: "text", nullable: false },
134
- metadata: { type: "text", nullable: true },
135
- createdAt: { type: "timestamp", nullable: false },
136
- updatedAt: { type: "timestamp", nullable: false }
137
- },
138
- [TABLE_MESSAGES]: {
139
- id: { type: "text", nullable: false, primaryKey: true },
140
- thread_id: { type: "text", nullable: false },
141
- content: { type: "text", nullable: false },
142
- role: { type: "text", nullable: false },
143
- type: { type: "text", nullable: false },
144
- createdAt: { type: "timestamp", nullable: false },
145
- resourceId: { type: "text", nullable: true }
146
- },
147
- [TABLE_SPANS]: SPAN_SCHEMA,
148
- [TABLE_TRACES]: {
149
- id: { type: "text", nullable: false, primaryKey: true },
150
- parentSpanId: { type: "text", nullable: true },
151
- name: { type: "text", nullable: false },
152
- traceId: { type: "text", nullable: false },
153
- scope: { type: "text", nullable: false },
154
- kind: { type: "integer", nullable: false },
155
- attributes: { type: "jsonb", nullable: true },
156
- status: { type: "jsonb", nullable: true },
157
- events: { type: "jsonb", nullable: true },
158
- links: { type: "jsonb", nullable: true },
159
- other: { type: "text", nullable: true },
160
- startTime: { type: "bigint", nullable: false },
161
- endTime: { type: "bigint", nullable: false },
162
- createdAt: { type: "timestamp", nullable: false }
163
- },
164
- [TABLE_RESOURCES]: {
165
- id: { type: "text", nullable: false, primaryKey: true },
166
- workingMemory: { type: "text", nullable: true },
167
- metadata: { type: "jsonb", nullable: true },
168
- createdAt: { type: "timestamp", nullable: false },
169
- updatedAt: { type: "timestamp", nullable: false }
170
- },
171
- [TABLE_AGENTS]: AGENTS_SCHEMA
172
- };
173
-
174
6
  // src/storage/base.ts
175
- function ensureDate(date) {
176
- if (!date) return void 0;
177
- return date instanceof Date ? date : new Date(date);
178
- }
179
- function serializeDate(date) {
180
- if (!date) return void 0;
181
- const dateObj = ensureDate(date);
182
- return dateObj?.toISOString();
183
- }
184
7
  function normalizePerPage(perPageInput, defaultValue) {
185
8
  if (perPageInput === false) {
186
9
  return Number.MAX_SAFE_INTEGER;
@@ -240,535 +63,136 @@ var MastraStorage = class extends MastraBase {
240
63
  hasColumn: false,
241
64
  createTable: false,
242
65
  deleteMessages: false,
243
- observabilityInstance: false,
66
+ observability: false,
244
67
  indexManagement: false,
245
68
  listScoresBySpan: false,
246
69
  agents: false
247
70
  };
248
71
  }
249
- ensureDate(date) {
250
- return ensureDate(date);
251
- }
252
- serializeDate(date) {
253
- return serializeDate(date);
254
- }
255
- async getResourceById(_) {
256
- throw new Error(
257
- `Resource working memory is not supported by this storage adapter (${this.constructor.name}). Supported storage adapters: LibSQL (@mastra/libsql), PostgreSQL (@mastra/pg), Upstash (@mastra/upstash). To use per-resource working memory, switch to one of these supported storage adapters.`
258
- );
259
- }
260
- async saveResource(_) {
261
- throw new Error(
262
- `Resource working memory is not supported by this storage adapter (${this.constructor.name}). Supported storage adapters: LibSQL (@mastra/libsql), PostgreSQL (@mastra/pg), Upstash (@mastra/upstash). To use per-resource working memory, switch to one of these supported storage adapters.`
263
- );
264
- }
265
- async updateResource(_) {
266
- throw new Error(
267
- `Resource working memory is not supported by this storage adapter (${this.constructor.name}). Supported storage adapters: LibSQL (@mastra/libsql), PostgreSQL (@mastra/pg), Upstash (@mastra/upstash). To use per-resource working memory, switch to one of these supported storage adapters.`
268
- );
269
- }
270
- async listMessages(args) {
271
- if (this.stores?.memory) {
272
- return this.stores.memory.listMessages(args);
273
- }
274
- throw new MastraError({
275
- id: "MASTRA_STORAGE_LIST_MESSAGES_NOT_SUPPORTED",
276
- domain: "STORAGE" /* STORAGE */,
277
- category: "SYSTEM" /* SYSTEM */,
278
- text: `Listing messages is not implemented by this storage adapter (${this.constructor.name})`
279
- });
280
- }
281
- async listWorkflowRuns(args) {
282
- if (this.stores?.workflows) {
283
- return this.stores.workflows.listWorkflowRuns(args);
284
- }
285
- throw new MastraError({
286
- id: "MASTRA_STORAGE_LIST_WORKFLOW_RUNS_NOT_SUPPORTED",
287
- domain: "STORAGE" /* STORAGE */,
288
- category: "SYSTEM" /* SYSTEM */,
289
- text: `Listing workflow runs is not implemented by this storage adapter (${this.constructor.name})`
290
- });
291
- }
292
- async listThreadsByResourceId(args) {
293
- if (this.stores?.memory) {
294
- return this.stores.memory.listThreadsByResourceId(args);
295
- }
296
- throw new MastraError({
297
- id: "MASTRA_STORAGE_LIST_THREADS_BY_RESOURCE_ID_PAGINATED_NOT_SUPPORTED",
298
- domain: "STORAGE" /* STORAGE */,
299
- category: "SYSTEM" /* SYSTEM */,
300
- text: `Listing threads by resource ID paginated is not implemented by this storage adapter (${this.constructor.name})`
301
- });
302
- }
303
- async listMessagesById({ messageIds }) {
304
- if (this.stores?.memory) {
305
- const result = await this.stores.memory.listMessagesById({ messageIds });
306
- return result;
307
- }
308
- throw new MastraError({
309
- id: "MASTRA_STORAGE_LIST_MESSAGES_BY_ID_NOT_SUPPORTED",
310
- domain: "STORAGE" /* STORAGE */,
311
- category: "SYSTEM" /* SYSTEM */,
312
- text: `Listing messages by ID is not implemented by this storage adapter (${this.constructor.name})`
313
- });
314
- }
315
- async deleteMessages(_messageIds) {
316
- throw new Error(
317
- `Message deletion is not supported by this storage adapter (${this.constructor.name}). The deleteMessages method needs to be implemented in the storage adapter.`
318
- );
72
+ /**
73
+ * Get a domain-specific storage interface.
74
+ *
75
+ * @param storeName - The name of the domain to access ('memory', 'workflows', 'scores', 'observability', 'agents')
76
+ * @returns The domain storage interface, or undefined if not available
77
+ *
78
+ * @example
79
+ * ```typescript
80
+ * const memory = await storage.getStore('memory');
81
+ * if (memory) {
82
+ * await memory.saveThread({ thread });
83
+ * }
84
+ * ```
85
+ */
86
+ async getStore(storeName) {
87
+ return this.stores?.[storeName];
319
88
  }
89
+ /**
90
+ * Initialize all domain stores.
91
+ * This creates necessary tables, indexes, and performs any required migrations.
92
+ */
320
93
  async init() {
321
94
  if (this.shouldCacheInit && await this.hasInitialized) {
322
95
  return;
323
96
  }
324
- const tableCreationTasks = [
325
- this.createTable({
326
- tableName: TABLE_WORKFLOW_SNAPSHOT,
327
- schema: TABLE_SCHEMAS[TABLE_WORKFLOW_SNAPSHOT]
328
- }),
329
- this.createTable({
330
- tableName: TABLE_THREADS,
331
- schema: TABLE_SCHEMAS[TABLE_THREADS]
332
- }),
333
- this.createTable({
334
- tableName: TABLE_MESSAGES,
335
- schema: TABLE_SCHEMAS[TABLE_MESSAGES]
336
- }),
337
- this.createTable({
338
- tableName: TABLE_TRACES,
339
- schema: TABLE_SCHEMAS[TABLE_TRACES]
340
- }),
341
- this.createTable({
342
- tableName: TABLE_SCORERS,
343
- schema: TABLE_SCHEMAS[TABLE_SCORERS]
344
- })
345
- ];
346
- if (this.supports.resourceWorkingMemory) {
347
- tableCreationTasks.push(
348
- this.createTable({
349
- tableName: TABLE_RESOURCES,
350
- schema: TABLE_SCHEMAS[TABLE_RESOURCES]
351
- })
352
- );
353
- }
354
- if (this.supports.observabilityInstance) {
355
- tableCreationTasks.push(
356
- this.createTable({
357
- tableName: TABLE_SPANS,
358
- schema: TABLE_SCHEMAS[TABLE_SPANS]
359
- })
360
- );
97
+ const initTasks = [];
98
+ if (this.stores?.memory) {
99
+ initTasks.push(this.stores.memory.init());
361
100
  }
362
- if (this.supports.agents) {
363
- tableCreationTasks.push(
364
- this.createTable({
365
- tableName: TABLE_AGENTS,
366
- schema: TABLE_SCHEMAS[TABLE_AGENTS]
367
- })
368
- );
101
+ if (this.stores?.workflows) {
102
+ initTasks.push(this.stores.workflows.init());
369
103
  }
370
- this.hasInitialized = Promise.all(tableCreationTasks).then(() => true);
371
- await this.hasInitialized;
372
- await this?.alterTable?.({
373
- tableName: TABLE_MESSAGES,
374
- schema: TABLE_SCHEMAS[TABLE_MESSAGES],
375
- ifNotExists: ["resourceId"]
376
- });
377
- await this?.alterTable?.({
378
- tableName: TABLE_WORKFLOW_SNAPSHOT,
379
- schema: TABLE_SCHEMAS[TABLE_WORKFLOW_SNAPSHOT],
380
- ifNotExists: ["resourceId"]
381
- });
382
- await this?.alterTable?.({
383
- tableName: TABLE_SCORERS,
384
- schema: TABLE_SCHEMAS[TABLE_SCORERS],
385
- ifNotExists: ["spanId", "requestContext"]
386
- });
387
- }
388
- async persistWorkflowSnapshot({
389
- workflowName,
390
- runId,
391
- resourceId,
392
- snapshot
393
- }) {
394
- await this.init();
395
- const data = {
396
- workflow_name: workflowName,
397
- run_id: runId,
398
- resourceId,
399
- snapshot,
400
- createdAt: /* @__PURE__ */ new Date(),
401
- updatedAt: /* @__PURE__ */ new Date()
402
- };
403
- this.logger.debug("Persisting workflow snapshot", { workflowName, runId, data });
404
- await this.insert({
405
- tableName: TABLE_WORKFLOW_SNAPSHOT,
406
- record: data
407
- });
408
- }
409
- async loadWorkflowSnapshot({
410
- workflowName,
411
- runId
412
- }) {
413
- if (!this.hasInitialized) {
414
- await this.init();
104
+ if (this.stores?.scores) {
105
+ initTasks.push(this.stores.scores.init());
415
106
  }
416
- this.logger.debug("Loading workflow snapshot", { workflowName, runId });
417
- const d = await this.load({
418
- tableName: TABLE_WORKFLOW_SNAPSHOT,
419
- keys: { workflow_name: workflowName, run_id: runId }
420
- });
421
- return d ? d.snapshot : null;
422
- }
423
- async listScoresBySpan({
424
- traceId,
425
- spanId,
426
- pagination: _pagination
427
- }) {
428
- throw new MastraError({
429
- id: "SCORES_STORAGE_GET_SCORES_BY_SPAN_NOT_IMPLEMENTED",
430
- domain: "STORAGE" /* STORAGE */,
431
- category: "SYSTEM" /* SYSTEM */,
432
- details: { traceId, spanId }
433
- });
434
- }
435
- /**
436
- * OBSERVABILITY
437
- */
438
- /**
439
- * Provides hints for tracing strategy selection by the DefaultExporter.
440
- * Storage adapters can override this to specify their preferred and supported strategies.
441
- */
442
- get tracingStrategy() {
443
107
  if (this.stores?.observability) {
444
- return this.stores.observability.tracingStrategy;
108
+ initTasks.push(this.stores.observability.init());
445
109
  }
446
- throw new MastraError({
447
- id: "MASTRA_STORAGE_TRACING_STRATEGY_NOT_SUPPORTED",
448
- domain: "STORAGE" /* STORAGE */,
449
- category: "SYSTEM" /* SYSTEM */,
450
- text: `tracing is not supported by this storage adapter (${this.constructor.name})`
451
- });
452
- }
453
- /**
454
- * Creates a single Span record in the storage provider.
455
- */
456
- async createSpan(span) {
457
- if (this.stores?.observability) {
458
- return this.stores.observability.createSpan(span);
110
+ if (this.stores?.agents) {
111
+ initTasks.push(this.stores.agents.init());
459
112
  }
460
- throw new MastraError({
461
- id: "MASTRA_STORAGE_CREATE_AI_SPAN_NOT_SUPPORTED",
462
- domain: "STORAGE" /* STORAGE */,
463
- category: "SYSTEM" /* SYSTEM */,
464
- text: `tracing is not supported by this storage adapter (${this.constructor.name})`
465
- });
113
+ this.hasInitialized = Promise.all(initTasks).then(() => true);
114
+ await this.hasInitialized;
466
115
  }
116
+ };
117
+
118
+ // src/storage/domains/base.ts
119
+ var StorageDomain = class extends MastraBase {
467
120
  /**
468
- * Updates a single Span with partial data. Primarily used for realtime trace creation.
121
+ * Initialize the storage domain.
122
+ * This should create any necessary tables/collections.
123
+ * Default implementation is a no-op - override in adapters that need initialization.
469
124
  */
470
- async updateSpan(params) {
471
- if (this.stores?.observability) {
472
- return this.stores.observability.updateSpan(params);
473
- }
474
- throw new MastraError({
475
- id: "MASTRA_STORAGE_UPDATE_AI_SPAN_NOT_SUPPORTED",
476
- domain: "STORAGE" /* STORAGE */,
477
- category: "SYSTEM" /* SYSTEM */,
478
- text: `tracing is not supported by this storage adapter (${this.constructor.name})`
479
- });
125
+ async init() {
480
126
  }
481
- /**
482
- * Retrieves a single trace with all its associated spans.
483
- */
484
- async getTrace(traceId) {
485
- if (this.stores?.observability) {
486
- return this.stores.observability.getTrace(traceId);
487
- }
488
- throw new MastraError({
489
- id: "MASTRA_STORAGE_GET_TRACE_NOT_SUPPORTED",
490
- domain: "STORAGE" /* STORAGE */,
491
- category: "SYSTEM" /* SYSTEM */,
492
- text: `tracing is not supported by this storage adapter (${this.constructor.name})`
127
+ };
128
+
129
+ // src/storage/domains/agents/base.ts
130
+ var AgentsStorage = class extends StorageDomain {
131
+ constructor() {
132
+ super({
133
+ component: "STORAGE",
134
+ name: "AGENTS"
493
135
  });
494
136
  }
495
137
  /**
496
- * Retrieves a paginated list of traces with optional filtering.
138
+ * Parses orderBy input for consistent sorting behavior.
497
139
  */
498
- async getTracesPaginated(args) {
499
- if (this.stores?.observability) {
500
- return this.stores.observability.getTracesPaginated(args);
501
- }
502
- throw new MastraError({
503
- id: "MASTRA_STORAGE_GET_TRACES_PAGINATED_NOT_SUPPORTED",
504
- domain: "STORAGE" /* STORAGE */,
505
- category: "SYSTEM" /* SYSTEM */,
506
- text: `tracing is not supported by this storage adapter (${this.constructor.name})`
507
- });
140
+ parseOrderBy(orderBy, defaultDirection = "DESC") {
141
+ return {
142
+ field: orderBy?.field && orderBy.field in AGENT_ORDER_BY_SET ? orderBy.field : "createdAt",
143
+ direction: orderBy?.direction && orderBy.direction in AGENT_SORT_DIRECTION_SET ? orderBy.direction : defaultDirection
144
+ };
508
145
  }
509
- /**
510
- * Creates multiple Spans in a single batch.
511
- */
512
- async batchCreateSpans(args) {
513
- if (this.stores?.observability) {
514
- return this.stores.observability.batchCreateSpans(args);
515
- }
516
- throw new MastraError({
517
- id: "MASTRA_STORAGE_BATCH_CREATE_AI_SPANS_NOT_SUPPORTED",
518
- domain: "STORAGE" /* STORAGE */,
519
- category: "SYSTEM" /* SYSTEM */,
520
- text: `tracing is not supported by this storage adapter (${this.constructor.name})`
521
- });
146
+ };
147
+ var AGENT_ORDER_BY_SET = {
148
+ createdAt: true,
149
+ updatedAt: true
150
+ };
151
+ var AGENT_SORT_DIRECTION_SET = {
152
+ ASC: true,
153
+ DESC: true
154
+ };
155
+
156
+ // src/storage/domains/agents/inmemory.ts
157
+ var InMemoryAgentsStorage = class extends AgentsStorage {
158
+ db;
159
+ constructor({ db }) {
160
+ super();
161
+ this.db = db;
522
162
  }
523
- /**
524
- * Updates multiple Spans in a single batch.
525
- */
526
- async batchUpdateSpans(args) {
527
- if (this.stores?.observability) {
528
- return this.stores.observability.batchUpdateSpans(args);
529
- }
530
- throw new MastraError({
531
- id: "MASTRA_STORAGE_BATCH_UPDATE_AI_SPANS_NOT_SUPPORTED",
532
- domain: "STORAGE" /* STORAGE */,
533
- category: "SYSTEM" /* SYSTEM */,
534
- text: `tracing is not supported by this storage adapter (${this.constructor.name})`
535
- });
163
+ async dangerouslyClearAll() {
164
+ this.db.agents.clear();
536
165
  }
537
- /**
538
- * Deletes multiple traces and all their associated spans in a single batch operation.
539
- */
540
- async batchDeleteTraces(args) {
541
- if (this.stores?.observability) {
542
- return this.stores.observability.batchDeleteTraces(args);
543
- }
544
- throw new MastraError({
545
- id: "MASTRA_STORAGE_BATCH_DELETE_TRACES_NOT_SUPPORTED",
546
- domain: "STORAGE" /* STORAGE */,
547
- category: "SYSTEM" /* SYSTEM */,
548
- text: `tracing is not supported by this storage adapter (${this.constructor.name})`
549
- });
166
+ async getAgentById({ id }) {
167
+ this.logger.debug(`InMemoryAgentsStorage: getAgentById called for ${id}`);
168
+ const agent = this.db.agents.get(id);
169
+ return agent ? {
170
+ ...agent,
171
+ metadata: agent.metadata ? { ...agent.metadata } : agent.metadata,
172
+ model: { ...agent.model },
173
+ tools: agent.tools ? [...agent.tools] : agent.tools,
174
+ workflows: agent.workflows ? [...agent.workflows] : agent.workflows,
175
+ agents: agent.agents ? [...agent.agents] : agent.agents,
176
+ scorers: agent.scorers ? { ...agent.scorers } : agent.scorers
177
+ } : null;
550
178
  }
551
- /**
552
- * DATABASE INDEX MANAGEMENT
553
- * These methods delegate to the operations store for index management.
554
- * Storage adapters that support indexes should implement these in their operations class.
555
- */
556
- /**
557
- * Creates a database index on specified columns
558
- * @throws {MastraError} if not supported by the storage adapter
559
- */
560
- async createIndex(options) {
561
- if (this.stores?.operations) {
562
- return this.stores.operations.createIndex(options);
179
+ async createAgent({ agent }) {
180
+ this.logger.debug(`InMemoryAgentsStorage: createAgent called for ${agent.id}`);
181
+ if (this.db.agents.has(agent.id)) {
182
+ throw new Error(`Agent with id ${agent.id} already exists`);
563
183
  }
564
- throw new MastraError({
565
- id: "MASTRA_STORAGE_CREATE_INDEX_NOT_SUPPORTED",
566
- domain: "STORAGE" /* STORAGE */,
567
- category: "SYSTEM" /* SYSTEM */,
568
- text: `Index management is not supported by this storage adapter (${this.constructor.name})`
569
- });
570
- }
571
- /**
572
- * Drops a database index by name
573
- * @throws {MastraError} if not supported by the storage adapter
574
- */
575
- async dropIndex(indexName) {
576
- if (this.stores?.operations) {
577
- return this.stores.operations.dropIndex(indexName);
578
- }
579
- throw new MastraError({
580
- id: "MASTRA_STORAGE_DROP_INDEX_NOT_SUPPORTED",
581
- domain: "STORAGE" /* STORAGE */,
582
- category: "SYSTEM" /* SYSTEM */,
583
- text: `Index management is not supported by this storage adapter (${this.constructor.name})`
584
- });
585
- }
586
- /**
587
- * Lists database indexes for a table or all tables
588
- * @throws {MastraError} if not supported by the storage adapter
589
- */
590
- async listIndexes(tableName) {
591
- if (this.stores?.operations) {
592
- return this.stores.operations.listIndexes(tableName);
593
- }
594
- throw new MastraError({
595
- id: "MASTRA_STORAGE_LIST_INDEXES_NOT_SUPPORTED",
596
- domain: "STORAGE" /* STORAGE */,
597
- category: "SYSTEM" /* SYSTEM */,
598
- text: `Index management is not supported by this storage adapter (${this.constructor.name})`
599
- });
600
- }
601
- /**
602
- * Gets detailed statistics for a specific index
603
- * @throws {MastraError} if not supported by the storage adapter
604
- */
605
- async describeIndex(indexName) {
606
- if (this.stores?.operations) {
607
- return this.stores.operations.describeIndex(indexName);
608
- }
609
- throw new MastraError({
610
- id: "MASTRA_STORAGE_DESCRIBE_INDEX_NOT_SUPPORTED",
611
- domain: "STORAGE" /* STORAGE */,
612
- category: "SYSTEM" /* SYSTEM */,
613
- text: `Index management is not supported by this storage adapter (${this.constructor.name})`
614
- });
615
- }
616
- /**
617
- * AGENTS STORAGE
618
- * These methods delegate to the agents store for agent CRUD operations.
619
- * This enables dynamic creation of agents via Mastra Studio.
620
- */
621
- /**
622
- * Retrieves an agent by its unique identifier.
623
- * @param id - The unique identifier of the agent
624
- * @returns The agent if found, null otherwise
625
- * @throws {MastraError} if not supported by the storage adapter
626
- */
627
- async getAgentById({ id }) {
628
- if (this.stores?.agents) {
629
- return this.stores.agents.getAgentById({ id });
630
- }
631
- throw new MastraError({
632
- id: "MASTRA_STORAGE_GET_AGENT_BY_ID_NOT_SUPPORTED",
633
- domain: "STORAGE" /* STORAGE */,
634
- category: "SYSTEM" /* SYSTEM */,
635
- text: `Agent storage is not supported by this storage adapter (${this.constructor.name})`
636
- });
637
- }
638
- /**
639
- * Creates a new agent in storage.
640
- * @param agent - The agent data to create
641
- * @returns The created agent with timestamps
642
- * @throws {MastraError} if not supported by the storage adapter
643
- */
644
- async createAgent({ agent }) {
645
- if (this.stores?.agents) {
646
- return this.stores.agents.createAgent({ agent });
647
- }
648
- throw new MastraError({
649
- id: "MASTRA_STORAGE_CREATE_AGENT_NOT_SUPPORTED",
650
- domain: "STORAGE" /* STORAGE */,
651
- category: "SYSTEM" /* SYSTEM */,
652
- text: `Agent storage is not supported by this storage adapter (${this.constructor.name})`
653
- });
654
- }
655
- /**
656
- * Updates an existing agent in storage.
657
- * @param id - The unique identifier of the agent to update
658
- * @param updates - The fields to update
659
- * @returns The updated agent
660
- * @throws {MastraError} if not supported by the storage adapter
661
- */
662
- async updateAgent(args) {
663
- if (this.stores?.agents) {
664
- return this.stores.agents.updateAgent(args);
665
- }
666
- throw new MastraError({
667
- id: "MASTRA_STORAGE_UPDATE_AGENT_NOT_SUPPORTED",
668
- domain: "STORAGE" /* STORAGE */,
669
- category: "SYSTEM" /* SYSTEM */,
670
- text: `Agent storage is not supported by this storage adapter (${this.constructor.name})`
671
- });
672
- }
673
- /**
674
- * Deletes an agent from storage.
675
- * @param id - The unique identifier of the agent to delete
676
- * @throws {MastraError} if not supported by the storage adapter
677
- */
678
- async deleteAgent({ id }) {
679
- if (this.stores?.agents) {
680
- return this.stores.agents.deleteAgent({ id });
681
- }
682
- throw new MastraError({
683
- id: "MASTRA_STORAGE_DELETE_AGENT_NOT_SUPPORTED",
684
- domain: "STORAGE" /* STORAGE */,
685
- category: "SYSTEM" /* SYSTEM */,
686
- text: `Agent storage is not supported by this storage adapter (${this.constructor.name})`
687
- });
688
- }
689
- /**
690
- * Lists all agents with optional pagination.
691
- * @param args - Pagination and ordering options
692
- * @returns Paginated list of agents
693
- * @throws {MastraError} if not supported by the storage adapter
694
- */
695
- async listAgents(args) {
696
- if (this.stores?.agents) {
697
- return this.stores.agents.listAgents(args);
698
- }
699
- throw new MastraError({
700
- id: "MASTRA_STORAGE_LIST_AGENTS_NOT_SUPPORTED",
701
- domain: "STORAGE" /* STORAGE */,
702
- category: "SYSTEM" /* SYSTEM */,
703
- text: `Agent storage is not supported by this storage adapter (${this.constructor.name})`
704
- });
705
- }
706
- };
707
-
708
- // src/storage/domains/agents/base.ts
709
- var AgentsStorage = class extends MastraBase {
710
- constructor() {
711
- super({
712
- component: "STORAGE",
713
- name: "AGENTS"
714
- });
715
- }
716
- /**
717
- * Parses orderBy input for consistent sorting behavior.
718
- */
719
- parseOrderBy(orderBy, defaultDirection = "DESC") {
720
- return {
721
- field: orderBy?.field && orderBy.field in AGENT_ORDER_BY_SET ? orderBy.field : "createdAt",
722
- direction: orderBy?.direction && orderBy.direction in AGENT_SORT_DIRECTION_SET ? orderBy.direction : defaultDirection
723
- };
724
- }
725
- };
726
- var AGENT_ORDER_BY_SET = {
727
- createdAt: true,
728
- updatedAt: true
729
- };
730
- var AGENT_SORT_DIRECTION_SET = {
731
- ASC: true,
732
- DESC: true
733
- };
734
-
735
- // src/storage/domains/agents/inmemory.ts
736
- var InMemoryAgentsStorage = class extends AgentsStorage {
737
- collection;
738
- constructor({ collection }) {
739
- super();
740
- this.collection = collection;
741
- }
742
- async getAgentById({ id }) {
743
- this.logger.debug(`InMemoryAgentsStorage: getAgentById called for ${id}`);
744
- const agent = this.collection.get(id);
745
- return agent ? {
746
- ...agent,
747
- metadata: agent.metadata ? { ...agent.metadata } : agent.metadata,
748
- model: { ...agent.model },
749
- tools: agent.tools ? [...agent.tools] : agent.tools,
750
- workflows: agent.workflows ? [...agent.workflows] : agent.workflows,
751
- agents: agent.agents ? [...agent.agents] : agent.agents,
752
- scorers: agent.scorers ? { ...agent.scorers } : agent.scorers
753
- } : null;
754
- }
755
- async createAgent({ agent }) {
756
- this.logger.debug(`InMemoryAgentsStorage: createAgent called for ${agent.id}`);
757
- if (this.collection.has(agent.id)) {
758
- throw new Error(`Agent with id ${agent.id} already exists`);
759
- }
760
- const now = /* @__PURE__ */ new Date();
761
- const newAgent = {
762
- ...agent,
763
- createdAt: now,
764
- updatedAt: now
765
- };
766
- this.collection.set(agent.id, newAgent);
767
- return { ...newAgent };
184
+ const now = /* @__PURE__ */ new Date();
185
+ const newAgent = {
186
+ ...agent,
187
+ createdAt: now,
188
+ updatedAt: now
189
+ };
190
+ this.db.agents.set(agent.id, newAgent);
191
+ return { ...newAgent };
768
192
  }
769
193
  async updateAgent({ id, ...updates }) {
770
194
  this.logger.debug(`InMemoryAgentsStorage: updateAgent called for ${id}`);
771
- const existingAgent = this.collection.get(id);
195
+ const existingAgent = this.db.agents.get(id);
772
196
  if (!existingAgent) {
773
197
  throw new Error(`Agent with id ${id} not found`);
774
198
  }
@@ -793,12 +217,12 @@ var InMemoryAgentsStorage = class extends AgentsStorage {
793
217
  },
794
218
  updatedAt: /* @__PURE__ */ new Date()
795
219
  };
796
- this.collection.set(id, updatedAgent);
220
+ this.db.agents.set(id, updatedAgent);
797
221
  return { ...updatedAgent };
798
222
  }
799
223
  async deleteAgent({ id }) {
800
224
  this.logger.debug(`InMemoryAgentsStorage: deleteAgent called for ${id}`);
801
- this.collection.delete(id);
225
+ this.db.agents.delete(id);
802
226
  }
803
227
  async listAgents(args) {
804
228
  const { page = 0, perPage: perPageInput, orderBy } = args || {};
@@ -812,7 +236,7 @@ var InMemoryAgentsStorage = class extends AgentsStorage {
812
236
  if (page * perPage > maxOffset) {
813
237
  throw new Error("page value too large");
814
238
  }
815
- const agents = Array.from(this.collection.values());
239
+ const agents = Array.from(this.db.agents.values());
816
240
  const sortedAgents = this.sortAgents(agents, field, direction);
817
241
  const clonedAgents = sortedAgents.map((agent) => ({
818
242
  ...agent,
@@ -841,6 +265,30 @@ var InMemoryAgentsStorage = class extends AgentsStorage {
841
265
  }
842
266
  };
843
267
 
268
+ // src/storage/domains/inmemory-db.ts
269
+ var InMemoryDB = class {
270
+ threads = /* @__PURE__ */ new Map();
271
+ messages = /* @__PURE__ */ new Map();
272
+ resources = /* @__PURE__ */ new Map();
273
+ workflows = /* @__PURE__ */ new Map();
274
+ scores = /* @__PURE__ */ new Map();
275
+ traces = /* @__PURE__ */ new Map();
276
+ agents = /* @__PURE__ */ new Map();
277
+ /**
278
+ * Clears all data from all collections.
279
+ * Useful for testing.
280
+ */
281
+ clear() {
282
+ this.threads.clear();
283
+ this.messages.clear();
284
+ this.resources.clear();
285
+ this.workflows.clear();
286
+ this.scores.clear();
287
+ this.traces.clear();
288
+ this.agents.clear();
289
+ }
290
+ };
291
+
844
292
  // src/storage/utils.ts
845
293
  function safelyParseJSON(input) {
846
294
  if (input && typeof input === "object") return input;
@@ -905,9 +353,57 @@ function createStorageErrorId(store, operation, status) {
905
353
  function createVectorErrorId(store, operation, status) {
906
354
  return createStoreErrorId("vector", store, operation, status);
907
355
  }
356
+ function getSqlType(type) {
357
+ switch (type) {
358
+ case "text":
359
+ return "TEXT";
360
+ case "timestamp":
361
+ return "TIMESTAMP";
362
+ case "float":
363
+ return "FLOAT";
364
+ case "integer":
365
+ return "INTEGER";
366
+ case "bigint":
367
+ return "BIGINT";
368
+ case "jsonb":
369
+ return "JSONB";
370
+ case "boolean":
371
+ return "BOOLEAN";
372
+ default:
373
+ return "TEXT";
374
+ }
375
+ }
376
+ function getDefaultValue(type) {
377
+ switch (type) {
378
+ case "text":
379
+ case "uuid":
380
+ return "DEFAULT ''";
381
+ case "timestamp":
382
+ return "DEFAULT '1970-01-01 00:00:00'";
383
+ case "integer":
384
+ case "bigint":
385
+ case "float":
386
+ return "DEFAULT 0";
387
+ case "jsonb":
388
+ return "DEFAULT '{}'";
389
+ case "boolean":
390
+ return "DEFAULT FALSE";
391
+ default:
392
+ return "DEFAULT ''";
393
+ }
394
+ }
395
+ function ensureDate(date) {
396
+ if (!date) return void 0;
397
+ return date instanceof Date ? date : new Date(date);
398
+ }
399
+ function serializeDate(date) {
400
+ if (!date) return void 0;
401
+ const dateObj = ensureDate(date);
402
+ return dateObj?.toISOString();
403
+ }
908
404
 
909
405
  // src/storage/domains/memory/base.ts
910
- var MemoryStorage = class extends MastraBase {
406
+ var MemoryStorage = class extends StorageDomain {
911
407
  constructor() {
912
408
  super({
913
409
  component: "STORAGE",
@@ -952,25 +448,25 @@ var THREAD_THREAD_SORT_DIRECTION_SET = {
952
448
 
953
449
  // src/storage/domains/memory/inmemory.ts
954
450
  var InMemoryMemory = class extends MemoryStorage {
955
- collection;
956
- operations;
957
- constructor({
958
- collection,
959
- operations
960
- }) {
451
+ db;
452
+ constructor({ db }) {
961
453
  super();
962
- this.collection = collection;
963
- this.operations = operations;
454
+ this.db = db;
455
+ }
456
+ async dangerouslyClearAll() {
457
+ this.db.threads.clear();
458
+ this.db.messages.clear();
459
+ this.db.resources.clear();
964
460
  }
965
461
  async getThreadById({ threadId }) {
966
- this.logger.debug(`MockStore: getThreadById called for ${threadId}`);
967
- const thread = this.collection.threads.get(threadId);
462
+ this.logger.debug(`InMemoryMemory: getThreadById called for ${threadId}`);
463
+ const thread = this.db.threads.get(threadId);
968
464
  return thread ? { ...thread, metadata: thread.metadata ? { ...thread.metadata } : thread.metadata } : null;
969
465
  }
970
466
  async saveThread({ thread }) {
971
- this.logger.debug(`MockStore: saveThread called for ${thread.id}`);
467
+ this.logger.debug(`InMemoryMemory: saveThread called for ${thread.id}`);
972
468
  const key = thread.id;
973
- this.collection.threads.set(key, thread);
469
+ this.db.threads.set(key, thread);
974
470
  return thread;
975
471
  }
976
472
  async updateThread({
@@ -978,8 +474,8 @@ var InMemoryMemory = class extends MemoryStorage {
978
474
  title,
979
475
  metadata
980
476
  }) {
981
- this.logger.debug(`MockStore: updateThread called for ${id}`);
982
- const thread = this.collection.threads.get(id);
477
+ this.logger.debug(`InMemoryMemory: updateThread called for ${id}`);
478
+ const thread = this.db.threads.get(id);
983
479
  if (!thread) {
984
480
  throw new Error(`Thread with id ${id} not found`);
985
481
  }
@@ -991,11 +487,11 @@ var InMemoryMemory = class extends MemoryStorage {
991
487
  return thread;
992
488
  }
993
489
  async deleteThread({ threadId }) {
994
- this.logger.debug(`MockStore: deleteThread called for ${threadId}`);
995
- this.collection.threads.delete(threadId);
996
- this.collection.messages.forEach((msg, key) => {
490
+ this.logger.debug(`InMemoryMemory: deleteThread called for ${threadId}`);
491
+ this.db.threads.delete(threadId);
492
+ this.db.messages.forEach((msg, key) => {
997
493
  if (msg.thread_id === threadId) {
998
- this.collection.messages.delete(key);
494
+ this.db.messages.delete(key);
999
495
  }
1000
496
  });
1001
497
  }
@@ -1009,7 +505,7 @@ var InMemoryMemory = class extends MemoryStorage {
1009
505
  orderBy
1010
506
  }) {
1011
507
  const threadIds = Array.isArray(threadId) ? threadId : [threadId];
1012
- this.logger.debug(`MockStore: listMessages called for threads ${threadIds.join(", ")}`);
508
+ this.logger.debug(`InMemoryMemory: listMessages called for threads ${threadIds.join(", ")}`);
1013
509
  if (threadIds.length === 0 || threadIds.some((id) => !id.trim())) {
1014
510
  throw new Error("threadId must be a non-empty string or array of non-empty strings");
1015
511
  }
@@ -1024,7 +520,7 @@ var InMemoryMemory = class extends MemoryStorage {
1024
520
  throw new Error("page value too large");
1025
521
  }
1026
522
  const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1027
- let threadMessages = Array.from(this.collection.messages.values()).filter((msg) => {
523
+ let threadMessages = Array.from(this.db.messages.values()).filter((msg) => {
1028
524
  if (!threadIdSet.has(msg.thread_id)) return false;
1029
525
  if (resourceId && msg.resourceId !== resourceId) return false;
1030
526
  return true;
@@ -1062,7 +558,7 @@ var InMemoryMemory = class extends MemoryStorage {
1062
558
  }
1063
559
  if (include && include.length > 0) {
1064
560
  for (const includeItem of include) {
1065
- const targetMessage = this.collection.messages.get(includeItem.id);
561
+ const targetMessage = this.db.messages.get(includeItem.id);
1066
562
  if (targetMessage) {
1067
563
  const convertedMessage = {
1068
564
  id: targetMessage.id,
@@ -1078,7 +574,7 @@ var InMemoryMemory = class extends MemoryStorage {
1078
574
  messageIds.add(convertedMessage.id);
1079
575
  }
1080
576
  if (includeItem.withPreviousMessages) {
1081
- const allThreadMessages = Array.from(this.collection.messages.values()).filter((msg) => msg.thread_id === (includeItem.threadId || threadId)).sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
577
+ const allThreadMessages = Array.from(this.db.messages.values()).filter((msg) => msg.thread_id === (includeItem.threadId || threadId)).sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
1082
578
  const targetIndex = allThreadMessages.findIndex((msg) => msg.id === includeItem.id);
1083
579
  if (targetIndex !== -1) {
1084
580
  const startIndex = Math.max(0, targetIndex - (includeItem.withPreviousMessages || 0));
@@ -1101,7 +597,7 @@ var InMemoryMemory = class extends MemoryStorage {
1101
597
  }
1102
598
  }
1103
599
  if (includeItem.withNextMessages) {
1104
- const allThreadMessages = Array.from(this.collection.messages.values()).filter((msg) => msg.thread_id === (includeItem.threadId || threadId)).sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
600
+ const allThreadMessages = Array.from(this.db.messages.values()).filter((msg) => msg.thread_id === (includeItem.threadId || threadId)).sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
1105
601
  const targetIndex = allThreadMessages.findIndex((msg) => msg.id === includeItem.id);
1106
602
  if (targetIndex !== -1) {
1107
603
  const endIndex = Math.min(
@@ -1172,20 +668,23 @@ var InMemoryMemory = class extends MemoryStorage {
1172
668
  };
1173
669
  }
1174
670
  async listMessagesById({ messageIds }) {
1175
- this.logger.debug(`MockStore: listMessagesById called`);
1176
- const rawMessages = messageIds.map((id) => this.collection.messages.get(id)).filter((message) => !!message);
1177
- const list = new MessageList().add(rawMessages.map(this.parseStoredMessage), "memory");
671
+ this.logger.debug(`InMemoryMemory: listMessagesById called`);
672
+ const rawMessages = messageIds.map((id) => this.db.messages.get(id)).filter((message) => !!message);
673
+ const list = new MessageList().add(
674
+ rawMessages.map((m) => this.parseStoredMessage(m)),
675
+ "memory"
676
+ );
1178
677
  return { messages: list.get.all.db() };
1179
678
  }
1180
679
  async saveMessages(args) {
1181
680
  const { messages } = args;
1182
- this.logger.debug(`MockStore: saveMessages called with ${messages.length} messages`);
681
+ this.logger.debug(`InMemoryMemory: saveMessages called with ${messages.length} messages`);
1183
682
  if (messages.some((msg) => msg.id === "error-message" || msg.resourceId === null)) {
1184
683
  throw new Error("Simulated error for testing");
1185
684
  }
1186
685
  const threadIds = new Set(messages.map((msg) => msg.threadId).filter((id) => Boolean(id)));
1187
686
  for (const threadId of threadIds) {
1188
- const thread = this.collection.threads.get(threadId);
687
+ const thread = this.db.threads.get(threadId);
1189
688
  if (thread) {
1190
689
  thread.updatedAt = /* @__PURE__ */ new Date();
1191
690
  }
@@ -1201,7 +700,7 @@ var InMemoryMemory = class extends MemoryStorage {
1201
700
  createdAt: message.createdAt,
1202
701
  resourceId: message.resourceId || null
1203
702
  };
1204
- this.collection.messages.set(key, storageMessage);
703
+ this.db.messages.set(key, storageMessage);
1205
704
  }
1206
705
  const list = new MessageList().add(messages, "memory");
1207
706
  return { messages: list.get.all.db() };
@@ -1209,7 +708,7 @@ var InMemoryMemory = class extends MemoryStorage {
1209
708
  async updateMessages(args) {
1210
709
  const updatedMessages = [];
1211
710
  for (const update of args.messages) {
1212
- const storageMsg = this.collection.messages.get(update.id);
711
+ const storageMsg = this.db.messages.get(update.id);
1213
712
  if (!storageMsg) continue;
1214
713
  const oldThreadId = storageMsg.thread_id;
1215
714
  const newThreadId = update.threadId || oldThreadId;
@@ -1236,13 +735,13 @@ var InMemoryMemory = class extends MemoryStorage {
1236
735
  storageMsg.thread_id = newThreadId;
1237
736
  const base = Date.now();
1238
737
  let oldThreadNewTime;
1239
- const oldThread = this.collection.threads.get(oldThreadId);
738
+ const oldThread = this.db.threads.get(oldThreadId);
1240
739
  if (oldThread) {
1241
740
  const prev = new Date(oldThread.updatedAt).getTime();
1242
741
  oldThreadNewTime = Math.max(base, prev + 1);
1243
742
  oldThread.updatedAt = new Date(oldThreadNewTime);
1244
743
  }
1245
- const newThread = this.collection.threads.get(newThreadId);
744
+ const newThread = this.db.threads.get(newThreadId);
1246
745
  if (newThread) {
1247
746
  const prev = new Date(newThread.updatedAt).getTime();
1248
747
  let newThreadNewTime = Math.max(base + 1, prev + 1);
@@ -1252,7 +751,7 @@ var InMemoryMemory = class extends MemoryStorage {
1252
751
  newThread.updatedAt = new Date(newThreadNewTime);
1253
752
  }
1254
753
  } else {
1255
- const thread = this.collection.threads.get(oldThreadId);
754
+ const thread = this.db.threads.get(oldThreadId);
1256
755
  if (thread) {
1257
756
  const prev = new Date(thread.updatedAt).getTime();
1258
757
  let newTime = Date.now();
@@ -1260,7 +759,7 @@ var InMemoryMemory = class extends MemoryStorage {
1260
759
  thread.updatedAt = new Date(newTime);
1261
760
  }
1262
761
  }
1263
- this.collection.messages.set(update.id, storageMsg);
762
+ this.db.messages.set(update.id, storageMsg);
1264
763
  updatedMessages.push({
1265
764
  id: storageMsg.id,
1266
765
  threadId: storageMsg.thread_id,
@@ -1277,18 +776,18 @@ var InMemoryMemory = class extends MemoryStorage {
1277
776
  if (!messageIds || messageIds.length === 0) {
1278
777
  return;
1279
778
  }
1280
- this.logger.debug(`MockStore: deleteMessages called for ${messageIds.length} messages`);
779
+ this.logger.debug(`InMemoryMemory: deleteMessages called for ${messageIds.length} messages`);
1281
780
  const threadIds = /* @__PURE__ */ new Set();
1282
781
  for (const messageId of messageIds) {
1283
- const message = this.collection.messages.get(messageId);
782
+ const message = this.db.messages.get(messageId);
1284
783
  if (message && message.thread_id) {
1285
784
  threadIds.add(message.thread_id);
1286
785
  }
1287
- this.collection.messages.delete(messageId);
786
+ this.db.messages.delete(messageId);
1288
787
  }
1289
788
  const now = /* @__PURE__ */ new Date();
1290
789
  for (const threadId of threadIds) {
1291
- const thread = this.collection.threads.get(threadId);
790
+ const thread = this.db.threads.get(threadId);
1292
791
  if (thread) {
1293
792
  thread.updatedAt = now;
1294
793
  }
@@ -1305,8 +804,8 @@ var InMemoryMemory = class extends MemoryStorage {
1305
804
  if (page * perPage > maxOffset) {
1306
805
  throw new Error("page value too large");
1307
806
  }
1308
- this.logger.debug(`MockStore: listThreadsByResourceId called for ${resourceId}`);
1309
- const threads = Array.from(this.collection.threads.values()).filter((t) => t.resourceId === resourceId);
807
+ this.logger.debug(`InMemoryMemory: listThreadsByResourceId called for ${resourceId}`);
808
+ const threads = Array.from(this.db.threads.values()).filter((t) => t.resourceId === resourceId);
1310
809
  const sortedThreads = this.sortThreads(threads, field, direction);
1311
810
  const clonedThreads = sortedThreads.map((thread) => ({
1312
811
  ...thread,
@@ -1322,13 +821,13 @@ var InMemoryMemory = class extends MemoryStorage {
1322
821
  };
1323
822
  }
1324
823
  async getResourceById({ resourceId }) {
1325
- this.logger.debug(`MockStore: getResourceById called for ${resourceId}`);
1326
- const resource = this.collection.resources.get(resourceId);
824
+ this.logger.debug(`InMemoryMemory: getResourceById called for ${resourceId}`);
825
+ const resource = this.db.resources.get(resourceId);
1327
826
  return resource ? { ...resource, metadata: resource.metadata ? { ...resource.metadata } : resource.metadata } : null;
1328
827
  }
1329
828
  async saveResource({ resource }) {
1330
- this.logger.debug(`MockStore: saveResource called for ${resource.id}`);
1331
- this.collection.resources.set(resource.id, resource);
829
+ this.logger.debug(`InMemoryMemory: saveResource called for ${resource.id}`);
830
+ this.db.resources.set(resource.id, resource);
1332
831
  return resource;
1333
832
  }
1334
833
  async updateResource({
@@ -1336,8 +835,8 @@ var InMemoryMemory = class extends MemoryStorage {
1336
835
  workingMemory,
1337
836
  metadata
1338
837
  }) {
1339
- this.logger.debug(`MockStore: updateResource called for ${resourceId}`);
1340
- let resource = this.collection.resources.get(resourceId);
838
+ this.logger.debug(`InMemoryMemory: updateResource called for ${resourceId}`);
839
+ let resource = this.db.resources.get(resourceId);
1341
840
  if (!resource) {
1342
841
  resource = {
1343
842
  id: resourceId,
@@ -1357,7 +856,7 @@ var InMemoryMemory = class extends MemoryStorage {
1357
856
  updatedAt: /* @__PURE__ */ new Date()
1358
857
  };
1359
858
  }
1360
- this.collection.resources.set(resourceId, resource);
859
+ this.db.resources.set(resourceId, resource);
1361
860
  return resource;
1362
861
  }
1363
862
  sortThreads(threads, field, direction) {
@@ -1378,13 +877,15 @@ var InMemoryMemory = class extends MemoryStorage {
1378
877
  };
1379
878
 
1380
879
  // src/storage/domains/observability/base.ts
1381
- var ObservabilityStorage = class extends MastraBase {
880
+ var ObservabilityStorage = class extends StorageDomain {
1382
881
  constructor() {
1383
882
  super({
1384
883
  component: "STORAGE",
1385
884
  name: "OBSERVABILITY"
1386
885
  });
1387
886
  }
887
+ async dangerouslyClearAll() {
888
+ }
1388
889
  /**
1389
890
  * Provides hints for tracing strategy selection by the DefaultExporter.
1390
891
  * Storage adapters can override this to specify their preferred and supported strategies.
@@ -1399,7 +900,7 @@ var ObservabilityStorage = class extends MastraBase {
1399
900
  /**
1400
901
  * Creates a single Span record in the storage provider.
1401
902
  */
1402
- createSpan(_span) {
903
+ async createSpan(_args) {
1403
904
  throw new MastraError({
1404
905
  id: "OBSERVABILITY_CREATE_SPAN_NOT_IMPLEMENTED",
1405
906
  domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */,
@@ -1410,7 +911,7 @@ var ObservabilityStorage = class extends MastraBase {
1410
911
  /**
1411
912
  * Updates a single Span with partial data. Primarily used for realtime trace creation.
1412
913
  */
1413
- updateSpan(_params) {
914
+ async updateSpan(_args) {
1414
915
  throw new MastraError({
1415
916
  id: "OBSERVABILITY_STORAGE_UPDATE_SPAN_NOT_IMPLEMENTED",
1416
917
  domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */,
@@ -1418,10 +919,32 @@ var ObservabilityStorage = class extends MastraBase {
1418
919
  text: "This storage provider does not support updating spans"
1419
920
  });
1420
921
  }
922
+ /**
923
+ * Retrieves a single span.
924
+ */
925
+ async getSpan(_args) {
926
+ throw new MastraError({
927
+ id: "OBSERVABILITY_STORAGE_GET_SPAN_NOT_IMPLEMENTED",
928
+ domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */,
929
+ category: "SYSTEM" /* SYSTEM */,
930
+ text: "This storage provider does not support getting spans"
931
+ });
932
+ }
933
+ /**
934
+ * Retrieves a single root span.
935
+ */
936
+ async getRootSpan(_args) {
937
+ throw new MastraError({
938
+ id: "OBSERVABILITY_STORAGE_GET_ROOT_SPAN_NOT_IMPLEMENTED",
939
+ domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */,
940
+ category: "SYSTEM" /* SYSTEM */,
941
+ text: "This storage provider does not support getting root spans"
942
+ });
943
+ }
1421
944
  /**
1422
945
  * Retrieves a single trace with all its associated spans.
1423
946
  */
1424
- getTrace(_traceId) {
947
+ async getTrace(_args) {
1425
948
  throw new MastraError({
1426
949
  id: "OBSERVABILITY_STORAGE_GET_TRACE_NOT_IMPLEMENTED",
1427
950
  domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */,
@@ -1430,20 +953,20 @@ var ObservabilityStorage = class extends MastraBase {
1430
953
  });
1431
954
  }
1432
955
  /**
1433
- * Retrieves a paginated list of traces with optional filtering.
956
+ * Retrieves a list of traces with optional filtering.
1434
957
  */
1435
- getTracesPaginated(_args) {
958
+ async listTraces(_args) {
1436
959
  throw new MastraError({
1437
- id: "OBSERVABILITY_STORAGE_GET_TRACES_PAGINATED_NOT_IMPLEMENTED",
960
+ id: "OBSERVABILITY_STORAGE_LIST_TRACES_NOT_IMPLEMENTED",
1438
961
  domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */,
1439
962
  category: "SYSTEM" /* SYSTEM */,
1440
- text: "This storage provider does not support getting traces paginated"
963
+ text: "This storage provider does not support listing traces"
1441
964
  });
1442
965
  }
1443
966
  /**
1444
967
  * Creates multiple Spans in a single batch.
1445
968
  */
1446
- batchCreateSpans(_args) {
969
+ async batchCreateSpans(_args) {
1447
970
  throw new MastraError({
1448
971
  id: "OBSERVABILITY_STORAGE_BATCH_CREATE_SPAN_NOT_IMPLEMENTED",
1449
972
  domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */,
@@ -1454,7 +977,7 @@ var ObservabilityStorage = class extends MastraBase {
1454
977
  /**
1455
978
  * Updates multiple Spans in a single batch.
1456
979
  */
1457
- batchUpdateSpans(_args) {
980
+ async batchUpdateSpans(_args) {
1458
981
  throw new MastraError({
1459
982
  id: "OBSERVABILITY_STORAGE_BATCH_UPDATE_SPANS_NOT_IMPLEMENTED",
1460
983
  domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */,
@@ -1465,7 +988,7 @@ var ObservabilityStorage = class extends MastraBase {
1465
988
  /**
1466
989
  * Deletes multiple traces and all their associated spans in a single batch operation.
1467
990
  */
1468
- batchDeleteTraces(_args) {
991
+ async batchDeleteTraces(_args) {
1469
992
  throw new MastraError({
1470
993
  id: "OBSERVABILITY_STORAGE_BATCH_DELETE_TRACES_NOT_IMPLEMENTED",
1471
994
  domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */,
@@ -1477,12 +1000,13 @@ var ObservabilityStorage = class extends MastraBase {
1477
1000
 
1478
1001
  // src/storage/domains/observability/inmemory.ts
1479
1002
  var ObservabilityInMemory = class extends ObservabilityStorage {
1480
- operations;
1481
- collection;
1482
- constructor({ collection, operations }) {
1003
+ db;
1004
+ constructor({ db }) {
1483
1005
  super();
1484
- this.collection = collection;
1485
- this.operations = operations;
1006
+ this.db = db;
1007
+ }
1008
+ async dangerouslyClearAll() {
1009
+ this.db.traces.clear();
1486
1010
  }
1487
1011
  get tracingStrategy() {
1488
1012
  return {
@@ -1490,17 +1014,27 @@ var ObservabilityInMemory = class extends ObservabilityStorage {
1490
1014
  supported: ["realtime", "batch-with-updates", "insert-only"]
1491
1015
  };
1492
1016
  }
1493
- async createSpan(span) {
1017
+ async createSpan(args) {
1018
+ const { span } = args;
1494
1019
  this.validateCreateSpan(span);
1495
- const id = this.generateId(span);
1496
- const record = span;
1497
- record.createdAt = /* @__PURE__ */ new Date();
1498
- record.updatedAt = record.createdAt;
1499
- this.collection.set(id, record);
1020
+ const now = /* @__PURE__ */ new Date();
1021
+ const record = {
1022
+ ...span,
1023
+ createdAt: now,
1024
+ updatedAt: now
1025
+ };
1026
+ this.upsertSpanToTrace(record);
1500
1027
  }
1501
1028
  async batchCreateSpans(args) {
1502
- for (const record of args.records) {
1503
- await this.createSpan(record);
1029
+ const now = /* @__PURE__ */ new Date();
1030
+ for (const span of args.records) {
1031
+ this.validateCreateSpan(span);
1032
+ const record = {
1033
+ ...span,
1034
+ createdAt: now,
1035
+ updatedAt: now
1036
+ };
1037
+ this.upsertSpanToTrace(record);
1504
1038
  }
1505
1039
  }
1506
1040
  validateCreateSpan(record) {
@@ -1521,11 +1055,74 @@ var ObservabilityInMemory = class extends ObservabilityStorage {
1521
1055
  });
1522
1056
  }
1523
1057
  }
1524
- generateId({ traceId, spanId }) {
1525
- return `${traceId}-${spanId}`;
1058
+ /**
1059
+ * Inserts or updates a span in the trace and recomputes trace-level properties
1060
+ */
1061
+ upsertSpanToTrace(span) {
1062
+ const { traceId, spanId } = span;
1063
+ let traceEntry = this.db.traces.get(traceId);
1064
+ if (!traceEntry) {
1065
+ traceEntry = {
1066
+ spans: {},
1067
+ rootSpan: null,
1068
+ status: "running" /* RUNNING */,
1069
+ hasChildError: false
1070
+ };
1071
+ this.db.traces.set(traceId, traceEntry);
1072
+ }
1073
+ traceEntry.spans[spanId] = span;
1074
+ if (span.parentSpanId === null) {
1075
+ traceEntry.rootSpan = span;
1076
+ }
1077
+ this.recomputeTraceProperties(traceEntry);
1078
+ }
1079
+ /**
1080
+ * Recomputes derived trace properties from all spans
1081
+ */
1082
+ recomputeTraceProperties(traceEntry) {
1083
+ const spans = Object.values(traceEntry.spans);
1084
+ if (spans.length === 0) return;
1085
+ traceEntry.hasChildError = spans.some((s) => s.error != null);
1086
+ const rootSpan = traceEntry.rootSpan;
1087
+ if (rootSpan) {
1088
+ if (rootSpan.error != null) {
1089
+ traceEntry.status = "error" /* ERROR */;
1090
+ } else if (rootSpan.endedAt === null) {
1091
+ traceEntry.status = "running" /* RUNNING */;
1092
+ } else {
1093
+ traceEntry.status = "success" /* SUCCESS */;
1094
+ }
1095
+ } else {
1096
+ traceEntry.status = "running" /* RUNNING */;
1097
+ }
1098
+ }
1099
+ async getSpan(args) {
1100
+ const { traceId, spanId } = args;
1101
+ const traceEntry = this.db.traces.get(traceId);
1102
+ if (!traceEntry) {
1103
+ return null;
1104
+ }
1105
+ const span = traceEntry.spans[spanId];
1106
+ if (!span) {
1107
+ return null;
1108
+ }
1109
+ return { span };
1110
+ }
1111
+ async getRootSpan(args) {
1112
+ const { traceId } = args;
1113
+ const traceEntry = this.db.traces.get(traceId);
1114
+ if (!traceEntry || !traceEntry.rootSpan) {
1115
+ return null;
1116
+ }
1117
+ return { span: traceEntry.rootSpan };
1526
1118
  }
1527
- async getTrace(traceId) {
1528
- const spans = Array.from(this.collection.values()).filter((span) => span.traceId === traceId);
1119
+ async getTrace(args) {
1120
+ const { traceId } = args;
1121
+ const traceEntry = this.db.traces.get(traceId);
1122
+ if (!traceEntry) {
1123
+ return null;
1124
+ }
1125
+ const spans = Object.values(traceEntry.spans);
1529
1126
  if (spans.length === 0) {
1530
1127
  return null;
1531
1128
  }
@@ -1535,272 +1132,233 @@ var ObservabilityInMemory = class extends ObservabilityStorage {
1535
1132
  spans
1536
1133
  };
1537
1134
  }
1538
- async getTracesPaginated({
1539
- filters,
1540
- pagination
1541
- }) {
1542
- const allRootSpans = this.filterForRootSpans(Array.from(this.collection.values()));
1543
- const filteredRootSpans = this.filterSpansByFilter(allRootSpans, filters);
1544
- const startDate = pagination?.dateRange?.start;
1545
- const endDate = pagination?.dateRange?.end;
1546
- const filteredRootSpansByDate = this.filterSpansByDate(filteredRootSpans, startDate, endDate);
1547
- const total = filteredRootSpansByDate.length;
1548
- const page = pagination?.page ?? 0;
1549
- const perPage = pagination?.perPage ?? 10;
1135
+ async listTraces(args) {
1136
+ const { filters, pagination, orderBy } = listTracesArgsSchema.parse(args);
1137
+ const matchingRootSpans = [];
1138
+ for (const [, traceEntry] of this.db.traces) {
1139
+ if (!traceEntry.rootSpan) continue;
1140
+ if (this.traceMatchesFilters(traceEntry, filters)) {
1141
+ matchingRootSpans.push(traceEntry.rootSpan);
1142
+ }
1143
+ }
1144
+ const { field: sortField, direction: sortDirection } = orderBy;
1145
+ matchingRootSpans.sort((a, b) => {
1146
+ if (sortField === "endedAt") {
1147
+ const aVal = a.endedAt;
1148
+ const bVal = b.endedAt;
1149
+ if (aVal == null && bVal == null) return 0;
1150
+ if (aVal == null) return sortDirection === "DESC" ? -1 : 1;
1151
+ if (bVal == null) return sortDirection === "DESC" ? 1 : -1;
1152
+ const diff = aVal.getTime() - bVal.getTime();
1153
+ return sortDirection === "DESC" ? -diff : diff;
1154
+ } else {
1155
+ const diff = a.startedAt.getTime() - b.startedAt.getTime();
1156
+ return sortDirection === "DESC" ? -diff : diff;
1157
+ }
1158
+ });
1159
+ const total = matchingRootSpans.length;
1160
+ const { page, perPage } = pagination;
1550
1161
  const start = page * perPage;
1551
1162
  const end = start + perPage;
1552
- const paged = this.filterSpansByPagination(filteredRootSpansByDate, pagination);
1163
+ const paged = matchingRootSpans.slice(start, end);
1553
1164
  return {
1554
1165
  spans: paged,
1555
1166
  pagination: { total, page, perPage, hasMore: end < total }
1556
1167
  };
1557
1168
  }
1558
- filterForRootSpans(spans) {
1559
- return spans.filter((span) => span.parentSpanId === null);
1560
- }
1561
- filterSpansByDate(spans, startDate, endDate) {
1562
- return spans.filter((span) => {
1563
- if (startDate && span.startedAt < startDate) return false;
1564
- if (endDate && span.startedAt > endDate) return false;
1565
- return true;
1566
- });
1567
- }
1568
- filterSpansByFilter(spans, filter) {
1569
- return spans.filter((span) => {
1570
- if (filter?.name && span.name !== filter.name) return false;
1571
- if (filter?.spanType && span.spanType !== filter.spanType) return false;
1572
- if (filter?.entityType === "agent" && filter.entityId !== span.attributes?.agentId) return false;
1573
- if (filter?.entityType === "workflow" && filter.entityId !== span.attributes?.workflowId) return false;
1574
- return true;
1575
- });
1576
- }
1577
- filterSpansByPagination(spans, pagination) {
1578
- const page = pagination?.page ?? 0;
1579
- const perPage = pagination?.perPage ?? 10;
1580
- const start = page * perPage;
1581
- const end = start + perPage;
1582
- return spans.slice(start, end);
1583
- }
1584
- async updateSpan(params) {
1585
- const id = this.generateId(params);
1586
- const span = this.collection.get(id);
1587
- if (!span) {
1588
- throw new MastraError({
1589
- id: "OBSERVABILITY_UPDATE_SPAN_NOT_FOUND",
1590
- domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */,
1591
- category: "SYSTEM" /* SYSTEM */,
1592
- text: "Span not found for update"
1593
- });
1594
- }
1595
- this.collection.set(id, { ...span, ...params.updates, updatedAt: /* @__PURE__ */ new Date() });
1596
- }
1597
- async batchUpdateSpans(args) {
1598
- for (const record of args.records) {
1599
- await this.updateSpan(record);
1169
+ /**
1170
+ * Check if a trace matches all provided filters
1171
+ */
1172
+ traceMatchesFilters(traceEntry, filters) {
1173
+ if (!filters) return true;
1174
+ const rootSpan = traceEntry.rootSpan;
1175
+ if (!rootSpan) return false;
1176
+ if (filters.startedAt) {
1177
+ if (filters.startedAt.start && rootSpan.startedAt < filters.startedAt.start) {
1178
+ return false;
1179
+ }
1180
+ if (filters.startedAt.end && rootSpan.startedAt > filters.startedAt.end) {
1181
+ return false;
1182
+ }
1600
1183
  }
1601
- }
1602
- async batchDeleteTraces(args) {
1603
- for (const traceId of args.traceIds) {
1604
- const spans = Array.from(this.collection.values()).filter((span) => span.traceId === traceId);
1605
- for (const span of spans) {
1606
- this.collection.delete(this.generateId(span));
1184
+ if (filters.endedAt) {
1185
+ if (rootSpan.endedAt == null) {
1186
+ return false;
1187
+ }
1188
+ if (filters.endedAt.start && rootSpan.endedAt < filters.endedAt.start) {
1189
+ return false;
1190
+ }
1191
+ if (filters.endedAt.end && rootSpan.endedAt > filters.endedAt.end) {
1192
+ return false;
1607
1193
  }
1608
1194
  }
1609
- }
1610
- };
1611
-
1612
- // src/storage/domains/operations/base.ts
1613
- var StoreOperations = class extends MastraBase {
1614
- constructor() {
1615
- super({
1616
- component: "STORAGE",
1617
- name: "OPERATIONS"
1618
- });
1619
- }
1620
- getSqlType(type) {
1621
- switch (type) {
1622
- case "text":
1623
- return "TEXT";
1624
- case "timestamp":
1625
- return "TIMESTAMP";
1626
- case "float":
1627
- return "FLOAT";
1628
- case "integer":
1629
- return "INTEGER";
1630
- case "bigint":
1631
- return "BIGINT";
1632
- case "jsonb":
1633
- return "JSONB";
1634
- default:
1635
- return "TEXT";
1195
+ if (filters.spanType !== void 0 && rootSpan.spanType !== filters.spanType) {
1196
+ return false;
1636
1197
  }
1637
- }
1638
- getDefaultValue(type) {
1639
- switch (type) {
1640
- case "text":
1641
- case "uuid":
1642
- return "DEFAULT ''";
1643
- case "timestamp":
1644
- return "DEFAULT '1970-01-01 00:00:00'";
1645
- case "integer":
1646
- case "bigint":
1647
- case "float":
1648
- return "DEFAULT 0";
1649
- case "jsonb":
1650
- return "DEFAULT '{}'";
1651
- default:
1652
- return "DEFAULT ''";
1198
+ if (filters.entityType !== void 0 && rootSpan.entityType !== filters.entityType) {
1199
+ return false;
1653
1200
  }
1201
+ if (filters.entityId !== void 0 && rootSpan.entityId !== filters.entityId) {
1202
+ return false;
1203
+ }
1204
+ if (filters.entityName !== void 0 && rootSpan.entityName !== filters.entityName) {
1205
+ return false;
1206
+ }
1207
+ if (filters.userId !== void 0 && rootSpan.userId !== filters.userId) {
1208
+ return false;
1209
+ }
1210
+ if (filters.organizationId !== void 0 && rootSpan.organizationId !== filters.organizationId) {
1211
+ return false;
1212
+ }
1213
+ if (filters.resourceId !== void 0 && rootSpan.resourceId !== filters.resourceId) {
1214
+ return false;
1215
+ }
1216
+ if (filters.runId !== void 0 && rootSpan.runId !== filters.runId) {
1217
+ return false;
1218
+ }
1219
+ if (filters.sessionId !== void 0 && rootSpan.sessionId !== filters.sessionId) {
1220
+ return false;
1221
+ }
1222
+ if (filters.threadId !== void 0 && rootSpan.threadId !== filters.threadId) {
1223
+ return false;
1224
+ }
1225
+ if (filters.requestId !== void 0 && rootSpan.requestId !== filters.requestId) {
1226
+ return false;
1227
+ }
1228
+ if (filters.environment !== void 0 && rootSpan.environment !== filters.environment) {
1229
+ return false;
1230
+ }
1231
+ if (filters.source !== void 0 && rootSpan.source !== filters.source) {
1232
+ return false;
1233
+ }
1234
+ if (filters.serviceName !== void 0 && rootSpan.serviceName !== filters.serviceName) {
1235
+ return false;
1236
+ }
1237
+ if (filters.scope != null && rootSpan.scope != null) {
1238
+ for (const [key, value] of Object.entries(filters.scope)) {
1239
+ if (!this.jsonValueEquals(rootSpan.scope[key], value)) {
1240
+ return false;
1241
+ }
1242
+ }
1243
+ } else if (filters.scope != null && rootSpan.scope == null) {
1244
+ return false;
1245
+ }
1246
+ if (filters.metadata != null && rootSpan.metadata != null) {
1247
+ for (const [key, value] of Object.entries(filters.metadata)) {
1248
+ if (!this.jsonValueEquals(rootSpan.metadata[key], value)) {
1249
+ return false;
1250
+ }
1251
+ }
1252
+ } else if (filters.metadata != null && rootSpan.metadata == null) {
1253
+ return false;
1254
+ }
1255
+ if (filters.tags != null && filters.tags.length > 0) {
1256
+ if (rootSpan.tags == null) {
1257
+ return false;
1258
+ }
1259
+ for (const tag of filters.tags) {
1260
+ if (!rootSpan.tags.includes(tag)) {
1261
+ return false;
1262
+ }
1263
+ }
1264
+ }
1265
+ if (filters.status !== void 0 && traceEntry.status !== filters.status) {
1266
+ return false;
1267
+ }
1268
+ if (filters.hasChildError !== void 0 && traceEntry.hasChildError !== filters.hasChildError) {
1269
+ return false;
1270
+ }
1271
+ return true;
1654
1272
  }
1655
1273
  /**
1656
- * DATABASE INDEX MANAGEMENT
1657
- * Optional methods for database index management.
1658
- * Storage adapters can override these to provide index management capabilities.
1659
- */
1660
- /**
1661
- * Creates a database index on specified columns
1662
- * @throws {MastraError} if not supported by the storage adapter
1663
- */
1664
- async createIndex(_options) {
1665
- throw new MastraError({
1666
- id: "MASTRA_STORAGE_CREATE_INDEX_NOT_SUPPORTED",
1667
- domain: "STORAGE" /* STORAGE */,
1668
- category: "SYSTEM" /* SYSTEM */,
1669
- text: `Index management is not supported by this storage adapter`
1670
- });
1671
- }
1672
- /**
1673
- * Drops a database index by name
1674
- * @throws {MastraError} if not supported by the storage adapter
1675
- */
1676
- async dropIndex(_indexName) {
1677
- throw new MastraError({
1678
- id: "MASTRA_STORAGE_DROP_INDEX_NOT_SUPPORTED",
1679
- domain: "STORAGE" /* STORAGE */,
1680
- category: "SYSTEM" /* SYSTEM */,
1681
- text: `Index management is not supported by this storage adapter`
1682
- });
1683
- }
1684
- /**
1685
- * Lists database indexes for a table or all tables
1686
- * @throws {MastraError} if not supported by the storage adapter
1687
- */
1688
- async listIndexes(_tableName) {
1689
- throw new MastraError({
1690
- id: "MASTRA_STORAGE_LIST_INDEXES_NOT_SUPPORTED",
1691
- domain: "STORAGE" /* STORAGE */,
1692
- category: "SYSTEM" /* SYSTEM */,
1693
- text: `Index management is not supported by this storage adapter`
1694
- });
1695
- }
1696
- /**
1697
- * Gets detailed statistics for a specific index
1698
- * @throws {MastraError} if not supported by the storage adapter
1699
- */
1700
- async describeIndex(_indexName) {
1701
- throw new MastraError({
1702
- id: "MASTRA_STORAGE_DESCRIBE_INDEX_NOT_SUPPORTED",
1703
- domain: "STORAGE" /* STORAGE */,
1704
- category: "SYSTEM" /* SYSTEM */,
1705
- text: `Index management is not supported by this storage adapter`
1706
- });
1707
- }
1708
- /**
1709
- * Returns definitions for automatic performance indexes
1710
- * Storage adapters can override this to define indexes that should be created during initialization
1711
- * @returns Array of index definitions to create automatically
1274
+ * Deep equality check for JSON values
1712
1275
  */
1713
- getAutomaticIndexDefinitions() {
1714
- return [];
1715
- }
1716
- };
1717
-
1718
- // src/storage/domains/operations/inmemory.ts
1719
- var StoreOperationsInMemory = class extends StoreOperations {
1720
- data;
1721
- constructor() {
1722
- super();
1723
- this.data = {
1724
- mastra_workflow_snapshot: /* @__PURE__ */ new Map(),
1725
- mastra_messages: /* @__PURE__ */ new Map(),
1726
- mastra_threads: /* @__PURE__ */ new Map(),
1727
- mastra_traces: /* @__PURE__ */ new Map(),
1728
- mastra_resources: /* @__PURE__ */ new Map(),
1729
- mastra_scorers: /* @__PURE__ */ new Map(),
1730
- mastra_ai_spans: /* @__PURE__ */ new Map(),
1731
- mastra_agents: /* @__PURE__ */ new Map()
1732
- };
1733
- }
1734
- getDatabase() {
1735
- return this.data;
1736
- }
1737
- async insert({ tableName, record }) {
1738
- const table = this.data[tableName];
1739
- let key = record.id;
1740
- if ([TABLE_WORKFLOW_SNAPSHOT].includes(tableName) && !record.id && record.run_id) {
1741
- key = record.workflow_name ? `${record.workflow_name}-${record.run_id}` : record.run_id;
1742
- record.id = key;
1743
- } else if (!record.id) {
1744
- key = `auto-${Date.now()}-${Math.random()}`;
1745
- record.id = key;
1276
+ jsonValueEquals(a, b) {
1277
+ if (a === void 0 || b === void 0) {
1278
+ return a === b;
1746
1279
  }
1747
- table.set(key, record);
1748
- }
1749
- async batchInsert({ tableName, records }) {
1750
- const table = this.data[tableName];
1751
- for (const record of records) {
1752
- let key = record.id;
1753
- if ([TABLE_WORKFLOW_SNAPSHOT].includes(tableName) && !record.id && record.run_id) {
1754
- key = record.run_id;
1755
- record.id = key;
1756
- } else if (!record.id) {
1757
- key = `auto-${Date.now()}-${Math.random()}`;
1758
- record.id = key;
1280
+ if (a === null || b === null) {
1281
+ return a === b;
1282
+ }
1283
+ if (typeof a !== typeof b) {
1284
+ return false;
1285
+ }
1286
+ if (a instanceof Date && b instanceof Date) {
1287
+ return a.getTime() === b.getTime();
1288
+ }
1289
+ if (a instanceof Date || b instanceof Date) {
1290
+ return false;
1291
+ }
1292
+ if (typeof a === "object") {
1293
+ if (Array.isArray(a) && Array.isArray(b)) {
1294
+ if (a.length !== b.length) return false;
1295
+ return a.every((val, i) => this.jsonValueEquals(val, b[i]));
1759
1296
  }
1760
- table.set(key, record);
1297
+ if (Array.isArray(a) || Array.isArray(b)) {
1298
+ return false;
1299
+ }
1300
+ const aKeys = Object.keys(a);
1301
+ const bKeys = Object.keys(b);
1302
+ if (aKeys.length !== bKeys.length) return false;
1303
+ return aKeys.every(
1304
+ (key) => this.jsonValueEquals(a[key], b[key])
1305
+ );
1761
1306
  }
1307
+ return a === b;
1762
1308
  }
1763
- async load({ tableName, keys }) {
1764
- this.logger.debug(`MockStore: load called for ${tableName} with keys`, keys);
1765
- const table = this.data[tableName];
1766
- const records = Array.from(table.values());
1767
- return records.filter((record) => Object.keys(keys).every((key) => record[key] === keys[key]))?.[0];
1768
- }
1769
- async createTable({
1770
- tableName,
1771
- schema
1772
- }) {
1773
- this.logger.debug(`MockStore: createTable called for ${tableName} with schema`, schema);
1774
- this.data[tableName] = /* @__PURE__ */ new Map();
1775
- }
1776
- async clearTable({ tableName }) {
1777
- this.logger.debug(`MockStore: clearTable called for ${tableName}`);
1778
- this.data[tableName].clear();
1779
- }
1780
- async dropTable({ tableName }) {
1781
- this.logger.debug(`MockStore: dropTable called for ${tableName}`);
1782
- this.data[tableName].clear();
1309
+ async updateSpan(args) {
1310
+ const { traceId, spanId, updates } = args;
1311
+ const traceEntry = this.db.traces.get(traceId);
1312
+ if (!traceEntry) {
1313
+ throw new MastraError({
1314
+ id: "OBSERVABILITY_UPDATE_SPAN_NOT_FOUND",
1315
+ domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */,
1316
+ category: "SYSTEM" /* SYSTEM */,
1317
+ text: "Trace not found for span update"
1318
+ });
1319
+ }
1320
+ const span = traceEntry.spans[spanId];
1321
+ if (!span) {
1322
+ throw new MastraError({
1323
+ id: "OBSERVABILITY_UPDATE_SPAN_NOT_FOUND",
1324
+ domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */,
1325
+ category: "SYSTEM" /* SYSTEM */,
1326
+ text: "Span not found for update"
1327
+ });
1328
+ }
1329
+ const updatedSpan = {
1330
+ ...span,
1331
+ ...updates,
1332
+ updatedAt: /* @__PURE__ */ new Date()
1333
+ };
1334
+ traceEntry.spans[spanId] = updatedSpan;
1335
+ if (updatedSpan.parentSpanId === null) {
1336
+ traceEntry.rootSpan = updatedSpan;
1337
+ }
1338
+ this.recomputeTraceProperties(traceEntry);
1783
1339
  }
1784
- async alterTable({
1785
- tableName,
1786
- schema
1787
- }) {
1788
- this.logger.debug(`MockStore: alterTable called for ${tableName} with schema`, schema);
1340
+ async batchUpdateSpans(args) {
1341
+ for (const record of args.records) {
1342
+ await this.updateSpan(record);
1343
+ }
1789
1344
  }
1790
- async hasColumn(table, column) {
1791
- this.logger.debug(`MockStore: hasColumn called for ${table} with column ${column}`);
1792
- return true;
1345
+ async batchDeleteTraces(args) {
1346
+ for (const traceId of args.traceIds) {
1347
+ this.db.traces.delete(traceId);
1348
+ }
1793
1349
  }
1794
1350
  };
1795
1351
 
1796
1352
  // src/storage/domains/scores/base.ts
1797
- var ScoresStorage = class extends MastraBase {
1353
+ var ScoresStorage = class extends StorageDomain {
1798
1354
  constructor() {
1799
1355
  super({
1800
1356
  component: "STORAGE",
1801
1357
  name: "SCORES"
1802
1358
  });
1803
1359
  }
1360
+ async dangerouslyClearAll() {
1361
+ }
1804
1362
  async listScoresBySpan({
1805
1363
  traceId,
1806
1364
  spanId,
@@ -1817,17 +1375,20 @@ var ScoresStorage = class extends MastraBase {
1817
1375
 
1818
1376
  // src/storage/domains/scores/inmemory.ts
1819
1377
  var ScoresInMemory = class extends ScoresStorage {
1820
- scores;
1821
- constructor({ collection }) {
1378
+ db;
1379
+ constructor({ db }) {
1822
1380
  super();
1823
- this.scores = collection;
1381
+ this.db = db;
1382
+ }
1383
+ async dangerouslyClearAll() {
1384
+ this.db.scores.clear();
1824
1385
  }
1825
1386
  async getScoreById({ id }) {
1826
- return this.scores.get(id) ?? null;
1387
+ return this.db.scores.get(id) ?? null;
1827
1388
  }
1828
1389
  async saveScore(score) {
1829
1390
  const newScore = { id: crypto.randomUUID(), createdAt: /* @__PURE__ */ new Date(), updatedAt: /* @__PURE__ */ new Date(), ...score };
1830
- this.scores.set(newScore.id, newScore);
1391
+ this.db.scores.set(newScore.id, newScore);
1831
1392
  return { score: newScore };
1832
1393
  }
1833
1394
  async listScoresByScorerId({
@@ -1837,7 +1398,7 @@ var ScoresInMemory = class extends ScoresStorage {
1837
1398
  entityType,
1838
1399
  source
1839
1400
  }) {
1840
- const scores = Array.from(this.scores.values()).filter((score) => {
1401
+ const scores = Array.from(this.db.scores.values()).filter((score) => {
1841
1402
  let baseFilter = score.scorerId === scorerId;
1842
1403
  if (entityId) {
1843
1404
  baseFilter = baseFilter && score.entityId === entityId;
@@ -1868,7 +1429,7 @@ var ScoresInMemory = class extends ScoresStorage {
1868
1429
  runId,
1869
1430
  pagination
1870
1431
  }) {
1871
- const scores = Array.from(this.scores.values()).filter((score) => score.runId === runId);
1432
+ const scores = Array.from(this.db.scores.values()).filter((score) => score.runId === runId);
1872
1433
  const { page, perPage: perPageInput } = pagination;
1873
1434
  const perPage = normalizePerPage(perPageInput, Number.MAX_SAFE_INTEGER);
1874
1435
  const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
@@ -1888,7 +1449,7 @@ var ScoresInMemory = class extends ScoresStorage {
1888
1449
  entityType,
1889
1450
  pagination
1890
1451
  }) {
1891
- const scores = Array.from(this.scores.values()).filter((score) => {
1452
+ const scores = Array.from(this.db.scores.values()).filter((score) => {
1892
1453
  const baseFilter = score.entityId === entityId && score.entityType === entityType;
1893
1454
  return baseFilter;
1894
1455
  });
@@ -1911,7 +1472,7 @@ var ScoresInMemory = class extends ScoresStorage {
1911
1472
  spanId,
1912
1473
  pagination
1913
1474
  }) {
1914
- const scores = Array.from(this.scores.values()).filter(
1475
+ const scores = Array.from(this.db.scores.values()).filter(
1915
1476
  (score) => score.traceId === traceId && score.spanId === spanId
1916
1477
  );
1917
1478
  scores.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
@@ -1932,7 +1493,7 @@ var ScoresInMemory = class extends ScoresStorage {
1932
1493
  };
1933
1494
 
1934
1495
  // src/storage/domains/workflows/base.ts
1935
- var WorkflowsStorage = class extends MastraBase {
1496
+ var WorkflowsStorage = class extends StorageDomain {
1936
1497
  constructor() {
1937
1498
  super({
1938
1499
  component: "STORAGE",
@@ -1943,12 +1504,16 @@ var WorkflowsStorage = class extends MastraBase {
1943
1504
 
1944
1505
  // src/storage/domains/workflows/inmemory.ts
1945
1506
  var WorkflowsInMemory = class extends WorkflowsStorage {
1946
- operations;
1947
- collection;
1948
- constructor({ collection, operations }) {
1507
+ db;
1508
+ constructor({ db }) {
1949
1509
  super();
1950
- this.collection = collection;
1951
- this.operations = operations;
1510
+ this.db = db;
1511
+ }
1512
+ async dangerouslyClearAll() {
1513
+ this.db.workflows.clear();
1514
+ }
1515
+ getWorkflowKey(workflowName, runId) {
1516
+ return `${workflowName}-${runId}`;
1952
1517
  }
1953
1518
  async updateWorkflowResults({
1954
1519
  workflowName,
@@ -1957,8 +1522,9 @@ var WorkflowsInMemory = class extends WorkflowsStorage {
1957
1522
  result,
1958
1523
  requestContext
1959
1524
  }) {
1960
- this.logger.debug(`MockStore: updateWorkflowResults called for ${workflowName} ${runId} ${stepId}`, result);
1961
- const run = this.collection.get(`${workflowName}-${runId}`);
1525
+ this.logger.debug(`WorkflowsInMemory: updateWorkflowResults called for ${workflowName} ${runId} ${stepId}`, result);
1526
+ const key = this.getWorkflowKey(workflowName, runId);
1527
+ const run = this.db.workflows.get(key);
1962
1528
  if (!run) {
1963
1529
  return {};
1964
1530
  }
@@ -1977,18 +1543,19 @@ var WorkflowsInMemory = class extends WorkflowsStorage {
1977
1543
  status: "pending",
1978
1544
  runId: run.run_id
1979
1545
  };
1980
- this.collection.set(`${workflowName}-${runId}`, {
1546
+ this.db.workflows.set(key, {
1981
1547
  ...run,
1982
1548
  snapshot
1983
1549
  });
1550
+ } else {
1551
+ snapshot = typeof run.snapshot === "string" ? JSON.parse(run.snapshot) : run.snapshot;
1984
1552
  }
1985
- snapshot = typeof run.snapshot === "string" ? JSON.parse(run.snapshot) : run.snapshot;
1986
1553
  if (!snapshot || !snapshot?.context) {
1987
1554
  throw new Error(`Snapshot not found for runId ${runId}`);
1988
1555
  }
1989
1556
  snapshot.context[stepId] = result;
1990
1557
  snapshot.requestContext = { ...snapshot.requestContext, ...requestContext };
1991
- this.collection.set(`${workflowName}-${runId}`, {
1558
+ this.db.workflows.set(key, {
1992
1559
  ...run,
1993
1560
  snapshot
1994
1561
  });
@@ -1999,7 +1566,8 @@ var WorkflowsInMemory = class extends WorkflowsStorage {
1999
1566
  runId,
2000
1567
  opts
2001
1568
  }) {
2002
- const run = this.collection.get(`${workflowName}-${runId}`);
1569
+ const key = this.getWorkflowKey(workflowName, runId);
1570
+ const run = this.db.workflows.get(key);
2003
1571
  if (!run) {
2004
1572
  return;
2005
1573
  }
@@ -2018,7 +1586,7 @@ var WorkflowsInMemory = class extends WorkflowsStorage {
2018
1586
  status: "pending",
2019
1587
  runId: run.run_id
2020
1588
  };
2021
- this.collection.set(`${workflowName}-${runId}`, {
1589
+ this.db.workflows.set(key, {
2022
1590
  ...run,
2023
1591
  snapshot
2024
1592
  });
@@ -2029,7 +1597,7 @@ var WorkflowsInMemory = class extends WorkflowsStorage {
2029
1597
  throw new Error(`Snapshot not found for runId ${runId}`);
2030
1598
  }
2031
1599
  snapshot = { ...snapshot, ...opts };
2032
- this.collection.set(`${workflowName}-${runId}`, {
1600
+ this.db.workflows.set(key, {
2033
1601
  ...run,
2034
1602
  snapshot
2035
1603
  });
@@ -2039,31 +1607,34 @@ var WorkflowsInMemory = class extends WorkflowsStorage {
2039
1607
  workflowName,
2040
1608
  runId,
2041
1609
  resourceId,
2042
- snapshot
1610
+ snapshot,
1611
+ createdAt,
1612
+ updatedAt
2043
1613
  }) {
1614
+ const key = this.getWorkflowKey(workflowName, runId);
1615
+ const now = /* @__PURE__ */ new Date();
2044
1616
  const data = {
2045
1617
  workflow_name: workflowName,
2046
1618
  run_id: runId,
2047
1619
  resourceId,
2048
1620
  snapshot,
2049
- createdAt: /* @__PURE__ */ new Date(),
2050
- updatedAt: /* @__PURE__ */ new Date()
1621
+ createdAt: createdAt ?? now,
1622
+ updatedAt: updatedAt ?? now
2051
1623
  };
2052
- await this.operations.insert({
2053
- tableName: TABLE_WORKFLOW_SNAPSHOT,
2054
- record: data
2055
- });
1624
+ this.db.workflows.set(key, data);
2056
1625
  }
2057
1626
  async loadWorkflowSnapshot({
2058
1627
  workflowName,
2059
1628
  runId
2060
1629
  }) {
2061
1630
  this.logger.debug("Loading workflow snapshot", { workflowName, runId });
2062
- const d = await this.operations.load({
2063
- tableName: TABLE_WORKFLOW_SNAPSHOT,
2064
- keys: { workflow_name: workflowName, run_id: runId }
2065
- });
2066
- return d ? JSON.parse(JSON.stringify(d.snapshot)) : null;
1631
+ const key = this.getWorkflowKey(workflowName, runId);
1632
+ const run = this.db.workflows.get(key);
1633
+ if (!run) {
1634
+ return null;
1635
+ }
1636
+ const snapshot = typeof run.snapshot === "string" ? JSON.parse(run.snapshot) : run.snapshot;
1637
+ return snapshot ? JSON.parse(JSON.stringify(snapshot)) : null;
2067
1638
  }
2068
1639
  async listWorkflowRuns({
2069
1640
  workflowName,
@@ -2077,7 +1648,7 @@ var WorkflowsInMemory = class extends WorkflowsStorage {
2077
1648
  if (page !== void 0 && page < 0) {
2078
1649
  throw new Error("page must be >= 0");
2079
1650
  }
2080
- let runs = Array.from(this.collection.values());
1651
+ let runs = Array.from(this.db.workflows.values());
2081
1652
  if (workflowName) runs = runs.filter((run) => run.workflow_name === workflowName);
2082
1653
  if (status) {
2083
1654
  runs = runs.filter((run) => {
@@ -2131,7 +1702,7 @@ var WorkflowsInMemory = class extends WorkflowsStorage {
2131
1702
  runId,
2132
1703
  workflowName
2133
1704
  }) {
2134
- const runs = Array.from(this.collection.values()).filter((r) => r.run_id === runId);
1705
+ const runs = Array.from(this.db.workflows.values()).filter((r) => r.run_id === runId);
2135
1706
  let run = runs.find((r) => r.workflow_name === workflowName);
2136
1707
  if (!run) return null;
2137
1708
  const parsedRun = {
@@ -2146,227 +1717,240 @@ var WorkflowsInMemory = class extends WorkflowsStorage {
2146
1717
  return parsedRun;
2147
1718
  }
2148
1719
  async deleteWorkflowRunById({ runId, workflowName }) {
2149
- this.collection.delete(`${workflowName}-${runId}`);
1720
+ const key = this.getWorkflowKey(workflowName, runId);
1721
+ this.db.workflows.delete(key);
2150
1722
  }
2151
1723
  };
2152
1724
 
2153
1725
  // src/storage/mock.ts
2154
1726
  var InMemoryStore = class extends MastraStorage {
2155
1727
  stores;
1728
+ /**
1729
+ * Internal database layer shared across all domains.
1730
+ * This is an implementation detail - domains interact with this
1731
+ * rather than managing their own data structures.
1732
+ */
1733
+ #db;
2156
1734
  constructor({ id = "in-memory" } = {}) {
2157
1735
  super({ id, name: "InMemoryStorage" });
2158
1736
  this.hasInitialized = Promise.resolve(true);
2159
- const operationsStorage = new StoreOperationsInMemory();
2160
- const database = operationsStorage.getDatabase();
2161
- const scoresStorage = new ScoresInMemory({
2162
- collection: database.mastra_scorers
2163
- });
2164
- const workflowsStorage = new WorkflowsInMemory({
2165
- collection: database.mastra_workflow_snapshot,
2166
- operations: operationsStorage
2167
- });
2168
- const memoryStorage = new InMemoryMemory({
2169
- collection: {
2170
- threads: database.mastra_threads,
2171
- resources: database.mastra_resources,
2172
- messages: database.mastra_messages
2173
- },
2174
- operations: operationsStorage
2175
- });
2176
- const observabilityStorage = new ObservabilityInMemory({
2177
- collection: database.mastra_ai_spans,
2178
- operations: operationsStorage
2179
- });
2180
- const agentsCollection = /* @__PURE__ */ new Map();
2181
- const agentsStorage = new InMemoryAgentsStorage({
2182
- collection: agentsCollection
2183
- });
1737
+ this.#db = new InMemoryDB();
2184
1738
  this.stores = {
2185
- operations: operationsStorage,
2186
- workflows: workflowsStorage,
2187
- scores: scoresStorage,
2188
- memory: memoryStorage,
2189
- observability: observabilityStorage,
2190
- agents: agentsStorage
1739
+ memory: new InMemoryMemory({ db: this.#db }),
1740
+ workflows: new WorkflowsInMemory({ db: this.#db }),
1741
+ scores: new ScoresInMemory({ db: this.#db }),
1742
+ observability: new ObservabilityInMemory({ db: this.#db }),
1743
+ agents: new InMemoryAgentsStorage({ db: this.#db })
2191
1744
  };
2192
1745
  }
2193
1746
  get supports() {
2194
1747
  return {
2195
1748
  selectByIncludeResourceScope: false,
2196
- resourceWorkingMemory: false,
1749
+ resourceWorkingMemory: true,
2197
1750
  hasColumn: false,
2198
1751
  createTable: false,
2199
1752
  deleteMessages: true,
2200
- observabilityInstance: true,
1753
+ observability: true,
2201
1754
  indexManagement: false,
2202
1755
  listScoresBySpan: true,
2203
1756
  agents: true
2204
1757
  };
2205
1758
  }
2206
- async persistWorkflowSnapshot({
2207
- workflowName,
2208
- runId,
2209
- resourceId,
2210
- snapshot
2211
- }) {
2212
- await this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot });
2213
- }
2214
- async loadWorkflowSnapshot({
2215
- workflowName,
2216
- runId
2217
- }) {
2218
- return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
2219
- }
2220
- async createTable({
2221
- tableName,
2222
- schema
2223
- }) {
2224
- await this.stores.operations.createTable({ tableName, schema });
2225
- }
2226
- async alterTable({
2227
- tableName,
2228
- schema,
2229
- ifNotExists
2230
- }) {
2231
- await this.stores.operations.alterTable({ tableName, schema, ifNotExists });
2232
- }
2233
- async clearTable({ tableName }) {
2234
- await this.stores.operations.clearTable({ tableName });
2235
- }
2236
- async dropTable({ tableName }) {
2237
- await this.stores.operations.dropTable({ tableName });
2238
- }
2239
- async insert({ tableName, record }) {
2240
- await this.stores.operations.insert({ tableName, record });
2241
- }
2242
- async updateWorkflowResults({
2243
- workflowName,
2244
- runId,
2245
- stepId,
2246
- result,
2247
- requestContext
2248
- }) {
2249
- return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
2250
- }
2251
- async updateWorkflowState({
2252
- workflowName,
2253
- runId,
2254
- opts
2255
- }) {
2256
- return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
2257
- }
2258
- async batchInsert({ tableName, records }) {
2259
- await this.stores.operations.batchInsert({ tableName, records });
2260
- }
2261
- async load({ tableName, keys }) {
2262
- return this.stores.operations.load({ tableName, keys });
2263
- }
2264
- async getThreadById({ threadId }) {
2265
- return this.stores.memory.getThreadById({ threadId });
1759
+ /**
1760
+ * Clears all data from the in-memory database.
1761
+ * Useful for testing.
1762
+ * @deprecated Use dangerouslyClearAll() on individual domains instead.
1763
+ */
1764
+ clear() {
1765
+ this.#db.clear();
2266
1766
  }
2267
- async saveThread({ thread }) {
2268
- return this.stores.memory.saveThread({ thread });
1767
+ };
1768
+ var MockStore = InMemoryStore;
1769
+
1770
+ // src/storage/domains/operations/base.ts
1771
+ var StoreOperations = class extends MastraBase {
1772
+ constructor() {
1773
+ super({
1774
+ component: "STORAGE",
1775
+ name: "OPERATIONS"
1776
+ });
2269
1777
  }
2270
- async updateThread({
2271
- id,
2272
- title,
2273
- metadata
2274
- }) {
2275
- return this.stores.memory.updateThread({ id, title, metadata });
1778
+ getSqlType(type) {
1779
+ switch (type) {
1780
+ case "text":
1781
+ return "TEXT";
1782
+ case "timestamp":
1783
+ return "TIMESTAMP";
1784
+ case "float":
1785
+ return "FLOAT";
1786
+ case "integer":
1787
+ return "INTEGER";
1788
+ case "bigint":
1789
+ return "BIGINT";
1790
+ case "jsonb":
1791
+ return "JSONB";
1792
+ default:
1793
+ return "TEXT";
1794
+ }
2276
1795
  }
2277
- async deleteThread({ threadId }) {
2278
- return this.stores.memory.deleteThread({ threadId });
1796
+ getDefaultValue(type) {
1797
+ switch (type) {
1798
+ case "text":
1799
+ case "uuid":
1800
+ return "DEFAULT ''";
1801
+ case "timestamp":
1802
+ return "DEFAULT '1970-01-01 00:00:00'";
1803
+ case "integer":
1804
+ case "bigint":
1805
+ case "float":
1806
+ return "DEFAULT 0";
1807
+ case "jsonb":
1808
+ return "DEFAULT '{}'";
1809
+ default:
1810
+ return "DEFAULT ''";
1811
+ }
2279
1812
  }
2280
- async getResourceById({ resourceId }) {
2281
- return this.stores.memory.getResourceById({ resourceId });
1813
+ /**
1814
+ * DATABASE INDEX MANAGEMENT
1815
+ * Optional methods for database index management.
1816
+ * Storage adapters can override these to provide index management capabilities.
1817
+ */
1818
+ /**
1819
+ * Creates a database index on specified columns
1820
+ * @throws {MastraError} if not supported by the storage adapter
1821
+ */
1822
+ async createIndex(_options) {
1823
+ throw new MastraError({
1824
+ id: "MASTRA_STORAGE_CREATE_INDEX_NOT_SUPPORTED",
1825
+ domain: "STORAGE" /* STORAGE */,
1826
+ category: "SYSTEM" /* SYSTEM */,
1827
+ text: `Index management is not supported by this storage adapter`
1828
+ });
2282
1829
  }
2283
- async saveResource({ resource }) {
2284
- return this.stores.memory.saveResource({ resource });
1830
+ /**
1831
+ * Drops a database index by name
1832
+ * @throws {MastraError} if not supported by the storage adapter
1833
+ */
1834
+ async dropIndex(_indexName) {
1835
+ throw new MastraError({
1836
+ id: "MASTRA_STORAGE_DROP_INDEX_NOT_SUPPORTED",
1837
+ domain: "STORAGE" /* STORAGE */,
1838
+ category: "SYSTEM" /* SYSTEM */,
1839
+ text: `Index management is not supported by this storage adapter`
1840
+ });
2285
1841
  }
2286
- async updateResource({
2287
- resourceId,
2288
- workingMemory,
2289
- metadata
2290
- }) {
2291
- return this.stores.memory.updateResource({ resourceId, workingMemory, metadata });
1842
+ /**
1843
+ * Lists database indexes for a table or all tables
1844
+ * @throws {MastraError} if not supported by the storage adapter
1845
+ */
1846
+ async listIndexes(_tableName) {
1847
+ throw new MastraError({
1848
+ id: "MASTRA_STORAGE_LIST_INDEXES_NOT_SUPPORTED",
1849
+ domain: "STORAGE" /* STORAGE */,
1850
+ category: "SYSTEM" /* SYSTEM */,
1851
+ text: `Index management is not supported by this storage adapter`
1852
+ });
2292
1853
  }
2293
- async listMessagesById({ messageIds }) {
2294
- return this.stores.memory.listMessagesById({ messageIds });
1854
+ /**
1855
+ * Gets detailed statistics for a specific index
1856
+ * @throws {MastraError} if not supported by the storage adapter
1857
+ */
1858
+ async describeIndex(_indexName) {
1859
+ throw new MastraError({
1860
+ id: "MASTRA_STORAGE_DESCRIBE_INDEX_NOT_SUPPORTED",
1861
+ domain: "STORAGE" /* STORAGE */,
1862
+ category: "SYSTEM" /* SYSTEM */,
1863
+ text: `Index management is not supported by this storage adapter`
1864
+ });
2295
1865
  }
2296
- async saveMessages(args) {
2297
- return this.stores.memory.saveMessages(args);
1866
+ /**
1867
+ * Returns definitions for automatic performance indexes
1868
+ * Storage adapters can override this to define indexes that should be created during initialization
1869
+ * @returns Array of index definitions to create automatically
1870
+ */
1871
+ getAutomaticIndexDefinitions() {
1872
+ return [];
2298
1873
  }
2299
- async updateMessages(args) {
2300
- return this.stores.memory.updateMessages(args);
1874
+ };
1875
+
1876
+ // src/storage/domains/operations/inmemory.ts
1877
+ var StoreOperationsInMemory = class extends StoreOperations {
1878
+ data;
1879
+ constructor() {
1880
+ super();
1881
+ this.data = {
1882
+ mastra_workflow_snapshot: /* @__PURE__ */ new Map(),
1883
+ mastra_messages: /* @__PURE__ */ new Map(),
1884
+ mastra_threads: /* @__PURE__ */ new Map(),
1885
+ mastra_traces: /* @__PURE__ */ new Map(),
1886
+ mastra_resources: /* @__PURE__ */ new Map(),
1887
+ mastra_scorers: /* @__PURE__ */ new Map(),
1888
+ mastra_ai_spans: /* @__PURE__ */ new Map(),
1889
+ mastra_agents: /* @__PURE__ */ new Map()
1890
+ };
2301
1891
  }
2302
- async deleteMessages(messageIds) {
2303
- return this.stores.memory.deleteMessages(messageIds);
1892
+ getDatabase() {
1893
+ return this.data;
2304
1894
  }
2305
- async getScoreById({ id }) {
2306
- return this.stores.scores.getScoreById({ id });
1895
+ async insert({ tableName, record }) {
1896
+ const table = this.data[tableName];
1897
+ let key = record.id;
1898
+ if ([TABLE_WORKFLOW_SNAPSHOT].includes(tableName) && !record.id && record.run_id) {
1899
+ key = record.workflow_name ? `${record.workflow_name}-${record.run_id}` : record.run_id;
1900
+ record.id = key;
1901
+ } else if (!record.id) {
1902
+ key = `auto-${Date.now()}-${Math.random()}`;
1903
+ record.id = key;
1904
+ }
1905
+ table.set(key, record);
2307
1906
  }
2308
- async saveScore(score) {
2309
- return this.stores.scores.saveScore(score);
1907
+ async batchInsert({ tableName, records }) {
1908
+ const table = this.data[tableName];
1909
+ for (const record of records) {
1910
+ let key = record.id;
1911
+ if ([TABLE_WORKFLOW_SNAPSHOT].includes(tableName) && !record.id && record.run_id) {
1912
+ key = record.run_id;
1913
+ record.id = key;
1914
+ } else if (!record.id) {
1915
+ key = `auto-${Date.now()}-${Math.random()}`;
1916
+ record.id = key;
1917
+ }
1918
+ table.set(key, record);
1919
+ }
2310
1920
  }
2311
- async listScoresByScorerId({
2312
- scorerId,
2313
- entityId,
2314
- entityType,
2315
- source,
2316
- pagination
2317
- }) {
2318
- return this.stores.scores.listScoresByScorerId({ scorerId, entityId, entityType, source, pagination });
1921
+ async load({ tableName, keys }) {
1922
+ this.logger.debug(`MockStore: load called for ${tableName} with keys`, keys);
1923
+ const table = this.data[tableName];
1924
+ const records = Array.from(table.values());
1925
+ return records.filter((record) => Object.keys(keys).every((key) => record[key] === keys[key]))?.[0];
2319
1926
  }
2320
- async listScoresByRunId({
2321
- runId,
2322
- pagination
1927
+ async createTable({
1928
+ tableName,
1929
+ schema
2323
1930
  }) {
2324
- return this.stores.scores.listScoresByRunId({ runId, pagination });
1931
+ this.logger.debug(`MockStore: createTable called for ${tableName} with schema`, schema);
1932
+ this.data[tableName] = /* @__PURE__ */ new Map();
2325
1933
  }
2326
- async listScoresByEntityId({
2327
- entityId,
2328
- entityType,
2329
- pagination
2330
- }) {
2331
- return this.stores.scores.listScoresByEntityId({ entityId, entityType, pagination });
1934
+ async clearTable({ tableName }) {
1935
+ this.logger.debug(`MockStore: clearTable called for ${tableName}`);
1936
+ this.data[tableName].clear();
2332
1937
  }
2333
- async listScoresBySpan({
2334
- traceId,
2335
- spanId,
2336
- pagination
2337
- }) {
2338
- return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination });
1938
+ async dropTable({ tableName }) {
1939
+ this.logger.debug(`MockStore: dropTable called for ${tableName}`);
1940
+ this.data[tableName].clear();
2339
1941
  }
2340
- async getWorkflowRunById({
2341
- runId,
2342
- workflowName
1942
+ async alterTable({
1943
+ tableName,
1944
+ schema
2343
1945
  }) {
2344
- return this.stores.workflows.getWorkflowRunById({ runId, workflowName });
2345
- }
2346
- async deleteWorkflowRunById({ runId, workflowName }) {
2347
- return this.stores.workflows.deleteWorkflowRunById({ runId, workflowName });
2348
- }
2349
- async createSpan(span) {
2350
- return this.stores.observability.createSpan(span);
2351
- }
2352
- async updateSpan(params) {
2353
- return this.stores.observability.updateSpan(params);
2354
- }
2355
- async getTrace(traceId) {
2356
- return this.stores.observability.getTrace(traceId);
2357
- }
2358
- async batchCreateSpans(args) {
2359
- return this.stores.observability.batchCreateSpans(args);
2360
- }
2361
- async batchUpdateSpans(args) {
2362
- return this.stores.observability.batchUpdateSpans(args);
1946
+ this.logger.debug(`MockStore: alterTable called for ${tableName} with schema`, schema);
2363
1947
  }
2364
- async batchDeleteTraces(args) {
2365
- return this.stores.observability.batchDeleteTraces(args);
1948
+ async hasColumn(table, column) {
1949
+ this.logger.debug(`MockStore: hasColumn called for ${table} with column ${column}`);
1950
+ return true;
2366
1951
  }
2367
1952
  };
2368
- var MockStore = InMemoryStore;
2369
1953
 
2370
- export { AGENTS_SCHEMA, AgentsStorage, InMemoryAgentsStorage, InMemoryMemory, InMemoryStore, MastraStorage, MemoryStorage, MockStore, ObservabilityInMemory, ObservabilityStorage, SCORERS_SCHEMA, SPAN_SCHEMA, ScoresInMemory, ScoresStorage, StoreOperations, StoreOperationsInMemory, TABLE_AGENTS, TABLE_MESSAGES, TABLE_RESOURCES, TABLE_SCHEMAS, TABLE_SCORERS, TABLE_SPANS, TABLE_THREADS, TABLE_TRACES, TABLE_WORKFLOW_SNAPSHOT, WorkflowsInMemory, WorkflowsStorage, calculatePagination, createStorageErrorId, createStoreErrorId, createVectorErrorId, ensureDate, normalizePerPage, safelyParseJSON, serializeDate, transformRow, transformScoreRow };
2371
- //# sourceMappingURL=chunk-VETAQUW3.js.map
2372
- //# sourceMappingURL=chunk-VETAQUW3.js.map
1954
+ export { AgentsStorage, InMemoryAgentsStorage, InMemoryDB, InMemoryMemory, InMemoryStore, MastraStorage, MemoryStorage, MockStore, ObservabilityInMemory, ObservabilityStorage, ScoresInMemory, ScoresStorage, StorageDomain, StoreOperations, StoreOperationsInMemory, WorkflowsInMemory, WorkflowsStorage, calculatePagination, createStorageErrorId, createStoreErrorId, createVectorErrorId, ensureDate, getDefaultValue, getSqlType, normalizePerPage, safelyParseJSON, serializeDate, transformRow, transformScoreRow };
1955
+ //# sourceMappingURL=chunk-3HDRO3GG.js.map
1956
+ //# sourceMappingURL=chunk-3HDRO3GG.js.map