@mastra/core 1.2.1-alpha.0 → 1.3.0-alpha.2

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 (403) hide show
  1. package/CHANGELOG.md +341 -0
  2. package/dist/_types/@internal_ai-sdk-v5/dist/index.d.ts +2093 -262
  3. package/dist/agent/agent-legacy.d.ts.map +1 -1
  4. package/dist/agent/agent.d.ts +12 -3
  5. package/dist/agent/agent.d.ts.map +1 -1
  6. package/dist/agent/index.cjs +13 -13
  7. package/dist/agent/index.js +2 -2
  8. package/dist/agent/message-list/index.cjs +18 -18
  9. package/dist/agent/message-list/index.js +1 -1
  10. package/dist/agent/message-list/message-list.d.ts.map +1 -1
  11. package/dist/agent/types.d.ts +6 -1
  12. package/dist/agent/types.d.ts.map +1 -1
  13. package/dist/agent/workflows/prepare-stream/index.d.ts +3 -1
  14. package/dist/agent/workflows/prepare-stream/index.d.ts.map +1 -1
  15. package/dist/agent/workflows/prepare-stream/map-results-step.d.ts.map +1 -1
  16. package/dist/agent/workflows/prepare-stream/stream-step.d.ts +3 -1
  17. package/dist/agent/workflows/prepare-stream/stream-step.d.ts.map +1 -1
  18. package/dist/base.cjs +2 -2
  19. package/dist/base.d.ts +13 -1
  20. package/dist/base.d.ts.map +1 -1
  21. package/dist/base.js +1 -1
  22. package/dist/bundler/index.cjs +2 -2
  23. package/dist/bundler/index.js +1 -1
  24. package/dist/cache/index.cjs +3 -3
  25. package/dist/cache/index.js +1 -1
  26. package/dist/{chunk-ENCTSDWC.js → chunk-2GWTJFVM.js} +2410 -1402
  27. package/dist/chunk-2GWTJFVM.js.map +1 -0
  28. package/dist/{chunk-OB4V67IX.cjs → chunk-2K5PNW2U.cjs} +4 -4
  29. package/dist/{chunk-OB4V67IX.cjs.map → chunk-2K5PNW2U.cjs.map} +1 -1
  30. package/dist/{chunk-VZXYBFCX.cjs → chunk-2P6DD7M5.cjs} +10 -10
  31. package/dist/{chunk-VZXYBFCX.cjs.map → chunk-2P6DD7M5.cjs.map} +1 -1
  32. package/dist/{chunk-Q2D7LERO.cjs → chunk-2VD5OGOT.cjs} +4 -4
  33. package/dist/{chunk-Q2D7LERO.cjs.map → chunk-2VD5OGOT.cjs.map} +1 -1
  34. package/dist/{chunk-2DMSFLJY.cjs → chunk-6TZKQI4R.cjs} +8 -8
  35. package/dist/chunk-6TZKQI4R.cjs.map +1 -0
  36. package/dist/{chunk-4NG7CKEG.js → chunk-6VGCVSP4.js} +3 -3
  37. package/dist/{chunk-4NG7CKEG.js.map → chunk-6VGCVSP4.js.map} +1 -1
  38. package/dist/{chunk-IIZF4W7B.cjs → chunk-7UWHFWST.cjs} +52 -5
  39. package/dist/chunk-7UWHFWST.cjs.map +1 -0
  40. package/dist/{chunk-VW7YQWDW.cjs → chunk-BFIOQFGF.cjs} +28 -2
  41. package/dist/chunk-BFIOQFGF.cjs.map +1 -0
  42. package/dist/{chunk-E3VFKTIA.js → chunk-BXLLXTT4.js} +2245 -179
  43. package/dist/chunk-BXLLXTT4.js.map +1 -0
  44. package/dist/{chunk-HMCXNOF6.cjs → chunk-CGPH7CMG.cjs} +2431 -1417
  45. package/dist/chunk-CGPH7CMG.cjs.map +1 -0
  46. package/dist/{chunk-GVLPTDJA.cjs → chunk-D5JZT6EK.cjs} +236 -63
  47. package/dist/chunk-D5JZT6EK.cjs.map +1 -0
  48. package/dist/{chunk-5SOS47PH.cjs → chunk-FLHFB23E.cjs} +454 -222
  49. package/dist/chunk-FLHFB23E.cjs.map +1 -0
  50. package/dist/{chunk-XCPEEIHI.cjs → chunk-GCTAD6B7.cjs} +3012 -927
  51. package/dist/chunk-GCTAD6B7.cjs.map +1 -0
  52. package/dist/{chunk-W3AQUG66.js → chunk-GIY5BINT.js} +4 -4
  53. package/dist/{chunk-W3AQUG66.js.map → chunk-GIY5BINT.js.map} +1 -1
  54. package/dist/{chunk-M6VFJX5A.js → chunk-GMSAGYTB.js} +3 -3
  55. package/dist/{chunk-M6VFJX5A.js.map → chunk-GMSAGYTB.js.map} +1 -1
  56. package/dist/{chunk-JRJJ5VQE.cjs → chunk-GZD6443M.cjs} +99 -55
  57. package/dist/chunk-GZD6443M.cjs.map +1 -0
  58. package/dist/{chunk-Z6NRYYOH.js → chunk-ILQXPZCD.js} +9 -4
  59. package/dist/chunk-ILQXPZCD.js.map +1 -0
  60. package/dist/{chunk-5YVR7B4R.js → chunk-JQNREL64.js} +29 -9
  61. package/dist/chunk-JQNREL64.js.map +1 -0
  62. package/dist/{chunk-QOFI2WBM.cjs → chunk-JU6K7UDX.cjs} +991 -229
  63. package/dist/chunk-JU6K7UDX.cjs.map +1 -0
  64. package/dist/{chunk-HN2MSTR6.cjs → chunk-KAJNBNWP.cjs} +283 -38
  65. package/dist/chunk-KAJNBNWP.cjs.map +1 -0
  66. package/dist/{chunk-MSWXEOZC.js → chunk-KL2JPSRX.js} +5 -5
  67. package/dist/chunk-KL2JPSRX.js.map +1 -0
  68. package/dist/{chunk-MQB7XFXP.js → chunk-LHRHOPUC.js} +3 -3
  69. package/dist/{chunk-MQB7XFXP.js.map → chunk-LHRHOPUC.js.map} +1 -1
  70. package/dist/{chunk-VX7UA3SO.js → chunk-MOOJ3H3C.js} +974 -217
  71. package/dist/chunk-MOOJ3H3C.js.map +1 -0
  72. package/dist/{chunk-HU2ONA2W.cjs → chunk-ON2KVIUJ.cjs} +17 -17
  73. package/dist/{chunk-HU2ONA2W.cjs.map → chunk-ON2KVIUJ.cjs.map} +1 -1
  74. package/dist/{chunk-I66TMZJ3.cjs → chunk-OOCEAC6U.cjs} +21 -18
  75. package/dist/chunk-OOCEAC6U.cjs.map +1 -0
  76. package/dist/{chunk-MNWW2R3U.js → chunk-OV7OOUUR.js} +90 -54
  77. package/dist/chunk-OV7OOUUR.js.map +1 -0
  78. package/dist/{chunk-C4WWWQHT.cjs → chunk-RO47SMI7.cjs} +23 -3
  79. package/dist/chunk-RO47SMI7.cjs.map +1 -0
  80. package/dist/{chunk-6FG6FU5Y.cjs → chunk-RQ56ZSIR.cjs} +4 -4
  81. package/dist/{chunk-6FG6FU5Y.cjs.map → chunk-RQ56ZSIR.cjs.map} +1 -1
  82. package/dist/{chunk-IW3BNL7A.js → chunk-RS6CZXGA.js} +50 -3
  83. package/dist/chunk-RS6CZXGA.js.map +1 -0
  84. package/dist/{chunk-AIJLACR2.js → chunk-S53FKKVL.js} +27 -3
  85. package/dist/chunk-S53FKKVL.js.map +1 -0
  86. package/dist/{chunk-G6E3QNJC.js → chunk-SBPPGJL6.js} +4078 -4333
  87. package/dist/chunk-SBPPGJL6.js.map +1 -0
  88. package/dist/{chunk-UZL4H5P2.cjs → chunk-SH4PCZ3X.cjs} +5375 -5648
  89. package/dist/chunk-SH4PCZ3X.cjs.map +1 -0
  90. package/dist/{chunk-ZWM2CAIM.js → chunk-STKNQDVA.js} +4 -4
  91. package/dist/{chunk-ZWM2CAIM.js.map → chunk-STKNQDVA.js.map} +1 -1
  92. package/dist/{chunk-A5QFWX67.cjs → chunk-U2CABSMC.cjs} +79 -59
  93. package/dist/chunk-U2CABSMC.cjs.map +1 -0
  94. package/dist/{chunk-7MDVYPWX.cjs → chunk-UE2G2LRP.cjs} +9 -4
  95. package/dist/chunk-UE2G2LRP.cjs.map +1 -0
  96. package/dist/{chunk-AUF6U2BL.js → chunk-VM25PDSW.js} +5 -5
  97. package/dist/{chunk-AUF6U2BL.js.map → chunk-VM25PDSW.js.map} +1 -1
  98. package/dist/{chunk-RXD5EGQF.js → chunk-VVD56FI4.js} +228 -55
  99. package/dist/chunk-VVD56FI4.js.map +1 -0
  100. package/dist/{chunk-JIT2OY3X.js → chunk-WCAFTXGK.js} +23 -3
  101. package/dist/chunk-WCAFTXGK.js.map +1 -0
  102. package/dist/{chunk-P62OJXQ4.js → chunk-WL3AW3YA.js} +282 -37
  103. package/dist/chunk-WL3AW3YA.js.map +1 -0
  104. package/dist/{chunk-YLODOPYM.cjs → chunk-XDD5V446.cjs} +4163 -5352
  105. package/dist/chunk-XDD5V446.cjs.map +1 -0
  106. package/dist/{chunk-B4M33FCS.cjs → chunk-XQVYEOI7.cjs} +7 -7
  107. package/dist/{chunk-B4M33FCS.cjs.map → chunk-XQVYEOI7.cjs.map} +1 -1
  108. package/dist/{chunk-BP2TSCBW.js → chunk-ZATLLPIH.js} +4391 -5561
  109. package/dist/chunk-ZATLLPIH.js.map +1 -0
  110. package/dist/{chunk-T6PRRKMW.js → chunk-ZHFM7HCQ.js} +9 -6
  111. package/dist/chunk-ZHFM7HCQ.js.map +1 -0
  112. package/dist/{chunk-WFUNLRQX.js → chunk-ZRUTE56J.js} +366 -134
  113. package/dist/chunk-ZRUTE56J.js.map +1 -0
  114. package/dist/deployer/index.cjs +2 -2
  115. package/dist/deployer/index.js +1 -1
  116. package/dist/docs/SKILL.md +2 -9
  117. package/dist/docs/assets/SOURCE_MAP.json +399 -342
  118. package/dist/docs/references/docs-agents-agent-memory.md +45 -1
  119. package/dist/docs/references/docs-agents-network-approval.md +1 -1
  120. package/dist/docs/references/docs-agents-networks.md +3 -3
  121. package/dist/docs/references/docs-agents-overview.md +8 -0
  122. package/dist/docs/references/docs-agents-using-tools.md +82 -72
  123. package/dist/docs/references/docs-memory-observational-memory.md +11 -8
  124. package/dist/docs/references/docs-observability-overview.md +1 -1
  125. package/dist/docs/references/docs-observability-tracing-exporters-langsmith.md +70 -0
  126. package/dist/docs/references/docs-observability-tracing-overview.md +1 -1
  127. package/dist/docs/references/docs-server-middleware.md +0 -2
  128. package/dist/docs/references/docs-server-request-context.md +17 -0
  129. package/dist/docs/references/docs-workflows-agents-and-tools.md +2 -2
  130. package/dist/docs/references/docs-workflows-overview.md +1 -1
  131. package/dist/docs/references/docs-workspace-filesystem.md +2 -0
  132. package/dist/docs/references/docs-workspace-overview.md +3 -1
  133. package/dist/docs/references/docs-workspace-sandbox.md +2 -0
  134. package/dist/docs/references/docs-workspace-search.md +2 -0
  135. package/dist/docs/references/docs-workspace-skills.md +3 -1
  136. package/dist/docs/references/reference-agents-getTools.md +1 -6
  137. package/dist/docs/references/reference-agents-listAgents.md +1 -1
  138. package/dist/docs/references/reference-agents-network.md +0 -2
  139. package/dist/docs/references/reference-cli-mastra.md +29 -4
  140. package/dist/docs/references/reference-client-js-agents.md +1 -1
  141. package/dist/docs/references/reference-configuration.md +1 -1
  142. package/dist/docs/references/reference-core-getStoredAgentById.md +2 -2
  143. package/dist/docs/references/reference-core-listStoredAgents.md +1 -1
  144. package/dist/docs/references/reference-memory-observational-memory.md +2 -0
  145. package/dist/docs/references/reference-tools-mcp-client.md +0 -2
  146. package/dist/docs/references/reference-workflows-step.md +2 -0
  147. package/dist/docs/references/reference-workflows-workflow-methods-map.md +2 -2
  148. package/dist/docs/references/reference-workspace-filesystem.md +2 -0
  149. package/dist/docs/references/reference-workspace-local-filesystem.md +2 -0
  150. package/dist/docs/references/reference-workspace-local-sandbox.md +2 -0
  151. package/dist/docs/references/reference-workspace-sandbox.md +2 -0
  152. package/dist/docs/references/reference-workspace-workspace-class.md +2 -0
  153. package/dist/docs/references/reference.md +7 -2
  154. package/dist/editor/index.d.ts +1 -1
  155. package/dist/editor/index.d.ts.map +1 -1
  156. package/dist/editor/types.d.ts +53 -48
  157. package/dist/editor/types.d.ts.map +1 -1
  158. package/dist/evals/base.d.ts +15 -0
  159. package/dist/evals/base.d.ts.map +1 -1
  160. package/dist/evals/index.cjs +20 -20
  161. package/dist/evals/index.js +3 -3
  162. package/dist/evals/run/index.d.ts +3 -3
  163. package/dist/evals/run/index.d.ts.map +1 -1
  164. package/dist/evals/scoreTraces/index.cjs +5 -5
  165. package/dist/evals/scoreTraces/index.js +2 -2
  166. package/dist/features/index.cjs +1 -1
  167. package/dist/features/index.cjs.map +1 -1
  168. package/dist/features/index.d.ts.map +1 -1
  169. package/dist/features/index.js +1 -1
  170. package/dist/features/index.js.map +1 -1
  171. package/dist/index.cjs +4 -4
  172. package/dist/index.d.ts +3 -3
  173. package/dist/index.d.ts.map +1 -1
  174. package/dist/index.js +2 -2
  175. package/dist/integration/index.cjs +2 -2
  176. package/dist/integration/index.js +1 -1
  177. package/dist/llm/index.cjs +16 -16
  178. package/dist/llm/index.js +5 -5
  179. package/dist/llm/model/gateways/constants.d.ts.map +1 -1
  180. package/dist/llm/model/gateways/models-dev.d.ts.map +1 -1
  181. package/dist/llm/model/model.loop.d.ts +1 -1
  182. package/dist/llm/model/model.loop.d.ts.map +1 -1
  183. package/dist/llm/model/provider-types.generated.d.ts +128 -10
  184. package/dist/llm/model/resolve-model.d.ts.map +1 -1
  185. package/dist/loop/index.cjs +12 -12
  186. package/dist/loop/index.js +1 -1
  187. package/dist/loop/network/index.d.ts +3 -3
  188. package/dist/loop/network/index.d.ts.map +1 -1
  189. package/dist/loop/network/run-command-tool.d.ts +1 -1
  190. package/dist/loop/types.d.ts +13 -0
  191. package/dist/loop/types.d.ts.map +1 -1
  192. package/dist/loop/workflows/agentic-execution/index.d.ts +9 -9
  193. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts +7 -7
  194. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts.map +1 -1
  195. package/dist/loop/workflows/agentic-execution/llm-mapping-step.d.ts +3 -3
  196. package/dist/loop/workflows/agentic-execution/tool-call-step.d.ts.map +1 -1
  197. package/dist/loop/workflows/agentic-loop/index.d.ts +9 -9
  198. package/dist/loop/workflows/schema.d.ts +12 -12
  199. package/dist/mastra/index.cjs +2 -2
  200. package/dist/mastra/index.d.ts +91 -5
  201. package/dist/mastra/index.d.ts.map +1 -1
  202. package/dist/mastra/index.js +1 -1
  203. package/dist/mcp/index.cjs +2 -2
  204. package/dist/mcp/index.js +1 -1
  205. package/dist/memory/index.cjs +14 -14
  206. package/dist/memory/index.js +1 -1
  207. package/dist/memory/mock.d.ts.map +1 -1
  208. package/dist/memory/types.d.ts +128 -0
  209. package/dist/memory/types.d.ts.map +1 -1
  210. package/dist/models-dev-FQVUTQ7L.js +3 -0
  211. package/dist/{models-dev-Z45JSLWD.js.map → models-dev-FQVUTQ7L.js.map} +1 -1
  212. package/dist/models-dev-PPIXUUCU.cjs +12 -0
  213. package/dist/{models-dev-OQKVMEIT.cjs.map → models-dev-PPIXUUCU.cjs.map} +1 -1
  214. package/dist/netlify-4RIKF7Y3.js +3 -0
  215. package/dist/{netlify-SSWMYSAX.js.map → netlify-4RIKF7Y3.js.map} +1 -1
  216. package/dist/netlify-V5F7JEJH.cjs +12 -0
  217. package/dist/{netlify-TXZZCT6N.cjs.map → netlify-V5F7JEJH.cjs.map} +1 -1
  218. package/dist/processors/index.cjs +41 -41
  219. package/dist/processors/index.js +1 -1
  220. package/dist/processors/step-schema.d.ts +44 -44
  221. package/dist/provider-registry-C6XCYX44.cjs +40 -0
  222. package/dist/{provider-registry-NR7FXV2Q.cjs.map → provider-registry-C6XCYX44.cjs.map} +1 -1
  223. package/dist/provider-registry-NWU4YFQW.js +3 -0
  224. package/dist/{provider-registry-RPOTQNHI.js.map → provider-registry-NWU4YFQW.js.map} +1 -1
  225. package/dist/provider-registry.json +278 -33
  226. package/dist/relevance/index.cjs +3 -3
  227. package/dist/relevance/index.js +1 -1
  228. package/dist/server/index.cjs +3 -3
  229. package/dist/server/index.js +1 -1
  230. package/dist/storage/base.d.ts +3 -1
  231. package/dist/storage/base.d.ts.map +1 -1
  232. package/dist/storage/constants.cjs +51 -19
  233. package/dist/storage/constants.d.ts +10 -2
  234. package/dist/storage/constants.d.ts.map +1 -1
  235. package/dist/storage/constants.js +1 -1
  236. package/dist/storage/domains/agents/base.d.ts +13 -164
  237. package/dist/storage/domains/agents/base.d.ts.map +1 -1
  238. package/dist/storage/domains/agents/index.d.ts +0 -1
  239. package/dist/storage/domains/agents/index.d.ts.map +1 -1
  240. package/dist/storage/domains/agents/inmemory.d.ts +6 -10
  241. package/dist/storage/domains/agents/inmemory.d.ts.map +1 -1
  242. package/dist/storage/domains/index.d.ts +3 -0
  243. package/dist/storage/domains/index.d.ts.map +1 -1
  244. package/dist/storage/domains/inmemory-db.d.ts +7 -1
  245. package/dist/storage/domains/inmemory-db.d.ts.map +1 -1
  246. package/dist/storage/domains/memory/base.d.ts +45 -5
  247. package/dist/storage/domains/memory/base.d.ts.map +1 -1
  248. package/dist/storage/domains/memory/inmemory.d.ts +7 -7
  249. package/dist/storage/domains/memory/inmemory.d.ts.map +1 -1
  250. package/dist/storage/domains/observability/types.d.ts +62 -62
  251. package/dist/storage/domains/operations/inmemory.d.ts.map +1 -1
  252. package/dist/storage/domains/prompt-blocks/base.d.ts +47 -0
  253. package/dist/storage/domains/prompt-blocks/base.d.ts.map +1 -0
  254. package/dist/storage/domains/prompt-blocks/index.d.ts +3 -0
  255. package/dist/storage/domains/prompt-blocks/index.d.ts.map +1 -0
  256. package/dist/storage/domains/prompt-blocks/inmemory.d.ts +31 -0
  257. package/dist/storage/domains/prompt-blocks/inmemory.d.ts.map +1 -0
  258. package/dist/storage/domains/scorer-definitions/base.d.ts +47 -0
  259. package/dist/storage/domains/scorer-definitions/base.d.ts.map +1 -0
  260. package/dist/storage/domains/scorer-definitions/index.d.ts +3 -0
  261. package/dist/storage/domains/scorer-definitions/index.d.ts.map +1 -0
  262. package/dist/storage/domains/scorer-definitions/inmemory.d.ts +31 -0
  263. package/dist/storage/domains/scorer-definitions/inmemory.d.ts.map +1 -0
  264. package/dist/storage/domains/versioned.d.ts +136 -0
  265. package/dist/storage/domains/versioned.d.ts.map +1 -0
  266. package/dist/storage/index.cjs +156 -104
  267. package/dist/storage/index.js +2 -2
  268. package/dist/storage/mock.d.ts.map +1 -1
  269. package/dist/storage/types.d.ts +481 -27
  270. package/dist/storage/types.d.ts.map +1 -1
  271. package/dist/stream/MastraAgentNetworkStream.d.ts +1 -1
  272. package/dist/stream/MastraWorkflowStream.d.ts +1 -1
  273. package/dist/stream/RunOutput.d.ts +1 -1
  274. package/dist/stream/RunOutput.d.ts.map +1 -1
  275. package/dist/stream/base/output.d.ts +4 -0
  276. package/dist/stream/base/output.d.ts.map +1 -1
  277. package/dist/stream/index.cjs +11 -11
  278. package/dist/stream/index.js +2 -2
  279. package/dist/test-utils/llm-mock.cjs +4 -4
  280. package/dist/test-utils/llm-mock.js +1 -1
  281. package/dist/tool-loop-agent/index.cjs +4 -4
  282. package/dist/tool-loop-agent/index.js +1 -1
  283. package/dist/tools/index.cjs +4 -4
  284. package/dist/tools/index.js +1 -1
  285. package/dist/tools/is-vercel-tool.cjs +2 -2
  286. package/dist/tools/is-vercel-tool.js +1 -1
  287. package/dist/tools/tool-builder/builder.d.ts.map +1 -1
  288. package/dist/tools/types.d.ts +15 -0
  289. package/dist/tools/types.d.ts.map +1 -1
  290. package/dist/tools/validation.d.ts.map +1 -1
  291. package/dist/tts/index.cjs +2 -2
  292. package/dist/tts/index.js +1 -1
  293. package/dist/types/zod-compat.d.ts +2 -2
  294. package/dist/types/zod-compat.d.ts.map +1 -1
  295. package/dist/utils/zod-utils.d.ts +19 -0
  296. package/dist/utils/zod-utils.d.ts.map +1 -1
  297. package/dist/utils.cjs +28 -28
  298. package/dist/utils.d.ts +7 -1
  299. package/dist/utils.d.ts.map +1 -1
  300. package/dist/utils.js +2 -2
  301. package/dist/vector/index.cjs +9 -9
  302. package/dist/vector/index.js +2 -2
  303. package/dist/voice/index.cjs +6 -6
  304. package/dist/voice/index.js +1 -1
  305. package/dist/workflows/evented/index.cjs +10 -10
  306. package/dist/workflows/evented/index.js +1 -1
  307. package/dist/workflows/evented/step-executor.d.ts.map +1 -1
  308. package/dist/workflows/evented/workflow.d.ts +3 -1
  309. package/dist/workflows/evented/workflow.d.ts.map +1 -1
  310. package/dist/workflows/execution-engine.d.ts.map +1 -1
  311. package/dist/workflows/index.cjs +25 -25
  312. package/dist/workflows/index.js +1 -1
  313. package/dist/workflows/step.d.ts +4 -3
  314. package/dist/workflows/step.d.ts.map +1 -1
  315. package/dist/workflows/types.d.ts +2 -1
  316. package/dist/workflows/types.d.ts.map +1 -1
  317. package/dist/workflows/workflow.d.ts +12 -4
  318. package/dist/workflows/workflow.d.ts.map +1 -1
  319. package/dist/workspace/errors.d.ts +6 -0
  320. package/dist/workspace/errors.d.ts.map +1 -1
  321. package/dist/workspace/filesystem/composite-filesystem.d.ts +93 -0
  322. package/dist/workspace/filesystem/composite-filesystem.d.ts.map +1 -0
  323. package/dist/workspace/filesystem/filesystem.d.ts +35 -0
  324. package/dist/workspace/filesystem/filesystem.d.ts.map +1 -1
  325. package/dist/workspace/filesystem/index.d.ts +2 -0
  326. package/dist/workspace/filesystem/index.d.ts.map +1 -1
  327. package/dist/workspace/filesystem/local-filesystem.d.ts +9 -1
  328. package/dist/workspace/filesystem/local-filesystem.d.ts.map +1 -1
  329. package/dist/workspace/filesystem/mastra-filesystem.d.ts +92 -3
  330. package/dist/workspace/filesystem/mastra-filesystem.d.ts.map +1 -1
  331. package/dist/workspace/filesystem/mount.d.ts +34 -0
  332. package/dist/workspace/filesystem/mount.d.ts.map +1 -0
  333. package/dist/workspace/index.cjs +62 -34
  334. package/dist/workspace/index.d.ts +6 -2
  335. package/dist/workspace/index.d.ts.map +1 -1
  336. package/dist/workspace/index.js +1 -1
  337. package/dist/workspace/lifecycle.d.ts +29 -0
  338. package/dist/workspace/lifecycle.d.ts.map +1 -1
  339. package/dist/workspace/sandbox/errors.d.ts +50 -0
  340. package/dist/workspace/sandbox/errors.d.ts.map +1 -0
  341. package/dist/workspace/sandbox/index.d.ts +3 -0
  342. package/dist/workspace/sandbox/index.d.ts.map +1 -1
  343. package/dist/workspace/sandbox/local-sandbox.d.ts +17 -2
  344. package/dist/workspace/sandbox/local-sandbox.d.ts.map +1 -1
  345. package/dist/workspace/sandbox/mastra-sandbox.d.ts +153 -6
  346. package/dist/workspace/sandbox/mastra-sandbox.d.ts.map +1 -1
  347. package/dist/workspace/sandbox/mount-manager.d.ts +195 -0
  348. package/dist/workspace/sandbox/mount-manager.d.ts.map +1 -0
  349. package/dist/workspace/sandbox/sandbox.d.ts +37 -84
  350. package/dist/workspace/sandbox/sandbox.d.ts.map +1 -1
  351. package/dist/workspace/sandbox/types.d.ts +92 -0
  352. package/dist/workspace/sandbox/types.d.ts.map +1 -0
  353. package/dist/workspace/tools/tools.d.ts.map +1 -1
  354. package/dist/workspace/tools/tree-formatter.d.ts.map +1 -1
  355. package/dist/workspace/workspace.d.ts +73 -3
  356. package/dist/workspace/workspace.d.ts.map +1 -1
  357. package/package.json +16 -16
  358. package/src/llm/model/provider-types.generated.d.ts +128 -10
  359. package/dist/chunk-2DMSFLJY.cjs.map +0 -1
  360. package/dist/chunk-5SOS47PH.cjs.map +0 -1
  361. package/dist/chunk-5YVR7B4R.js.map +0 -1
  362. package/dist/chunk-7MDVYPWX.cjs.map +0 -1
  363. package/dist/chunk-A5QFWX67.cjs.map +0 -1
  364. package/dist/chunk-AIJLACR2.js.map +0 -1
  365. package/dist/chunk-BP2TSCBW.js.map +0 -1
  366. package/dist/chunk-C4WWWQHT.cjs.map +0 -1
  367. package/dist/chunk-E3VFKTIA.js.map +0 -1
  368. package/dist/chunk-ENCTSDWC.js.map +0 -1
  369. package/dist/chunk-G6E3QNJC.js.map +0 -1
  370. package/dist/chunk-GVLPTDJA.cjs.map +0 -1
  371. package/dist/chunk-HMCXNOF6.cjs.map +0 -1
  372. package/dist/chunk-HN2MSTR6.cjs.map +0 -1
  373. package/dist/chunk-I66TMZJ3.cjs.map +0 -1
  374. package/dist/chunk-IIZF4W7B.cjs.map +0 -1
  375. package/dist/chunk-IW3BNL7A.js.map +0 -1
  376. package/dist/chunk-JIT2OY3X.js.map +0 -1
  377. package/dist/chunk-JRJJ5VQE.cjs.map +0 -1
  378. package/dist/chunk-MNWW2R3U.js.map +0 -1
  379. package/dist/chunk-MSWXEOZC.js.map +0 -1
  380. package/dist/chunk-P62OJXQ4.js.map +0 -1
  381. package/dist/chunk-QOFI2WBM.cjs.map +0 -1
  382. package/dist/chunk-RXD5EGQF.js.map +0 -1
  383. package/dist/chunk-T6PRRKMW.js.map +0 -1
  384. package/dist/chunk-UZL4H5P2.cjs.map +0 -1
  385. package/dist/chunk-VW7YQWDW.cjs.map +0 -1
  386. package/dist/chunk-VX7UA3SO.js.map +0 -1
  387. package/dist/chunk-WFUNLRQX.js.map +0 -1
  388. package/dist/chunk-XCPEEIHI.cjs.map +0 -1
  389. package/dist/chunk-YLODOPYM.cjs.map +0 -1
  390. package/dist/chunk-Z6NRYYOH.js.map +0 -1
  391. package/dist/docs/references/docs-tools-mcp-advanced-usage.md +0 -143
  392. package/dist/docs/references/docs-tools-mcp-mcp-overview.md +0 -383
  393. package/dist/docs/references/docs-tools-mcp-overview.md +0 -78
  394. package/dist/docs/references/docs-workflows-input-data-mapping.md +0 -102
  395. package/dist/docs/references/reference-deployer-netlify.md +0 -14
  396. package/dist/docs/references/reference-deployer-vercel.md +0 -39
  397. package/dist/docs/references/reference-tools-client.md +0 -228
  398. package/dist/models-dev-OQKVMEIT.cjs +0 -12
  399. package/dist/models-dev-Z45JSLWD.js +0 -3
  400. package/dist/netlify-SSWMYSAX.js +0 -3
  401. package/dist/netlify-TXZZCT6N.cjs +0 -12
  402. package/dist/provider-registry-NR7FXV2Q.cjs +0 -40
  403. package/dist/provider-registry-RPOTQNHI.js +0 -3
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/storage/domains/shared.ts","../src/evals/types.ts","../src/storage/domains/observability/types.ts","../src/storage/types.ts","../src/storage/constants.ts"],"names":["z","EntityType","SpanType","TraceStatus","getZodTypeName"],"mappings":";;;;;;AAMO,IAAM,cAAA,GAAiBA,KAAA,CAAE,IAAA,EAAK,CAAE,SAAS,+BAA+B;AAExE,IAAM,cAAA,GAAiBA,KAAA,CAAE,IAAA,EAAK,CAAE,SAAS,kCAAkC;AAE3E,IAAM,YAAA,GAAe;AAAA,EAC1B,SAAA,EAAW,cAAA;AAAA,EACX,SAAA,EAAW,eAAe,QAAA;AAC5B;AAMO,IAAM,oBAAA,GAAuBA,MACjC,MAAA,CAAO;AAAA,EACN,MAAMA,KAAA,CAAE,MAAA,CAAO,MAAA,EAAO,CAAE,KAAI,CAAE,GAAA,CAAI,CAAC,CAA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AA,EAAK;AAAA,IAC1C,SAAA,EAAW,EAAE,IAAA,EAAM,WAAA,EAAa,UAAU,KAAA,EAAM;AAAA,IAChD,SAAA,EAAW,EAAE,IAAA,EAAM,WAAA,EAAa,UAAU,KAAA;AAAM,GAClD;AAAA,EACA,CAAC,YAAY,GAAG,aAAA;AAAA,EAChB,CAAC,oBAAoB,GAAG;AAC1B;AAMO,IAAM,iCAAA,GAAoC;AAAA,EAC/C,CAAC,0BAA0B,GAAG;AAChC","file":"chunk-JRJJ5VQE.cjs","sourcesContent":["import { z } from 'zod';\nimport { EntityType } from '../../observability';\n\n/**\n * Common DB fields\n */\nexport const createdAtField = z.date().describe('Database record creation time');\n\nexport const updatedAtField = z.date().describe('Database record last update time');\n\nexport const dbTimestamps = {\n createdAt: createdAtField,\n updatedAt: updatedAtField.nullable(),\n} as const satisfies z.ZodRawShape;\n\n/**\n * Pagination arguments for list queries (page and perPage only)\n * Uses z.coerce to handle string → number conversion from query params\n */\nexport const paginationArgsSchema = z\n .object({\n page: z.coerce.number().int().min(0).optional().default(0).describe('Zero-indexed page number'),\n perPage: z.coerce.number().int().min(1).max(100).optional().default(10).describe('Number of items per page'),\n })\n .describe('Pagination options for list queries');\n\nexport type PaginationArgs = z.input<typeof paginationArgsSchema>;\n\n/**\n * Pagination response info\n * Used across all paginated endpoints\n */\nexport const paginationInfoSchema = z.object({\n total: z.number().describe('Total number of items available'),\n page: z.number().describe('Current page'),\n perPage: z\n .union([z.number(), z.literal(false)])\n .describe('Number of items per page, or false if pagination is disabled'),\n hasMore: z.boolean().describe('True if more pages are available'),\n});\n\n/**\n * Date range for filtering by time\n * Uses z.coerce to handle ISO string → Date conversion from query params\n */\nexport const dateRangeSchema = z\n .object({\n start: z.coerce.date().optional().describe('Start of date range (inclusive by default)'),\n end: z.coerce.date().optional().describe('End of date range (inclusive by default)'),\n startExclusive: z\n .boolean()\n .optional()\n .describe('When true, excludes the start date from results (uses > instead of >=)'),\n endExclusive: z\n .boolean()\n .optional()\n .describe('When true, excludes the end date from results (uses < instead of <=)'),\n })\n .describe('Date range filter for timestamps');\n\nexport type DateRange = z.infer<typeof dateRangeSchema>;\n\nexport const sortDirectionSchema = z.enum(['ASC', 'DESC']).describe(\"Sort direction: 'ASC' | 'DESC'\");\n\nexport const entityTypeField = z\n .nativeEnum(EntityType)\n .describe(`Entity type (e.g., 'agent' | 'processor' | 'tool' | 'workflow')`);\n\nexport const entityIdField = z.string().describe('ID of the entity (e.g., \"weatherAgent\", \"orderWorkflow\")');\n\nexport const entityNameField = z.string().describe('Name of the entity');\n\nexport const userIdField = z.string().describe('Human end-user who triggered execution');\n\nexport const organizationIdField = z.string().describe('Multi-tenant organization/account');\n\nexport const resourceIdField = z.string().describe('Broader resource context (Mastra memory compatibility)');\n\nexport const runIdField = z.string().describe('Unique execution run identifier');\n\nexport const sessionIdField = z.string().describe('Session identifier for grouping traces');\n\nexport const threadIdField = z.string().describe('Conversation thread identifier');\n\nexport const requestIdField = z.string().describe('HTTP request ID for log correlation');\n\nexport const environmentField = z.string().describe(`Environment (e.g., \"production\" | \"staging\" | \"development\")`);\n\nexport const sourceField = z.string().describe(`Source of execution (e.g., \"local\" | \"cloud\" | \"ci\")`);\n\nexport const serviceNameField = z.string().describe('Name of the service');\n","import type { CoreMessage, CoreSystemMessage } from '@internal/ai-sdk-v4';\nimport { z } from 'zod';\nimport type { MastraDBMessage } from '../agent';\nimport { SpanType } from '../observability';\nimport type { TracingContext } from '../observability';\nimport { dbTimestamps, paginationInfoSchema } from '../storage/domains/shared';\n\n// ============================================================================\n// Sampling Config\n// ============================================================================\n\nexport type ScoringSamplingConfig = { type: 'none' } | { type: 'ratio'; rate: number };\n\n// ============================================================================\n// Scoring Source & Entity Type\n// ============================================================================\n\nexport const scoringSourceSchema = z.enum(['LIVE', 'TEST']);\n\nexport type ScoringSource = z.infer<typeof scoringSourceSchema>;\n\nexport const scoringEntityTypeSchema = z.enum(['AGENT', 'WORKFLOW', ...Object.values(SpanType)] as [\n string,\n string,\n ...string[],\n]);\n\nexport type ScoringEntityType = z.infer<typeof scoringEntityTypeSchema>;\n\n// ============================================================================\n// Scoring Prompts\n// ============================================================================\n\nexport const scoringPromptsSchema = z.object({\n description: z.string(),\n prompt: z.string(),\n});\n\nexport type ScoringPrompts = z.infer<typeof scoringPromptsSchema>;\n\n// ============================================================================\n// Shared Record Schemas\n// ============================================================================\n\n/** Reusable schema for required record fields (e.g., scorer, entity) */\nconst recordSchema = z.record(z.string(), z.unknown());\n\n/** Reusable schema for optional record fields (e.g., metadata, additionalContext) */\nconst optionalRecordSchema = recordSchema.optional();\n\n// ============================================================================\n// Base Scoring Input (used for scorer functions)\n// ============================================================================\n\nexport const scoringInputSchema = z.object({\n runId: z.string().optional(),\n input: z.unknown().optional(),\n output: z.unknown(),\n additionalContext: optionalRecordSchema,\n requestContext: optionalRecordSchema,\n // Note: tracingContext is not serializable, so we don't include it in the schema\n // It's added at runtime when needed\n});\n\nexport type ScoringInput = z.infer<typeof scoringInputSchema> & {\n tracingContext?: TracingContext;\n};\n\n// ============================================================================\n// Scoring Hook Input\n// ============================================================================\n\nexport const scoringHookInputSchema = z.object({\n runId: z.string().optional(),\n scorer: recordSchema,\n input: z.unknown(),\n output: z.unknown(),\n metadata: optionalRecordSchema,\n additionalContext: optionalRecordSchema,\n source: scoringSourceSchema,\n entity: recordSchema,\n entityType: scoringEntityTypeSchema,\n requestContext: optionalRecordSchema,\n structuredOutput: z.boolean().optional(),\n traceId: z.string().optional(),\n spanId: z.string().optional(),\n resourceId: z.string().optional(),\n threadId: z.string().optional(),\n // Note: tracingContext is not serializable, so we don't include it in the schema\n});\n\nexport type ScoringHookInput = z.infer<typeof scoringHookInputSchema> & {\n tracingContext?: TracingContext;\n};\n\n// ============================================================================\n// Extract Step Result\n// ============================================================================\n\nexport const scoringExtractStepResultSchema = optionalRecordSchema;\n\nexport type ScoringExtractStepResult = z.infer<typeof scoringExtractStepResultSchema>;\n\n// ============================================================================\n// Analyze Step Result (Score Result)\n// ============================================================================\n\nexport const scoringValueSchema = z.number();\n\nexport const scoreResultSchema = z.object({\n result: optionalRecordSchema,\n score: scoringValueSchema,\n prompt: z.string().optional(),\n});\n\nexport type ScoringAnalyzeStepResult = z.infer<typeof scoreResultSchema>;\n\n// ============================================================================\n// Composite Input Types (for scorer step functions)\n// ============================================================================\n\nexport const scoringInputWithExtractStepResultSchema = scoringInputSchema.extend({\n runId: z.string(), // Required in this context\n extractStepResult: optionalRecordSchema,\n extractPrompt: z.string().optional(),\n});\n\nexport type ScoringInputWithExtractStepResult<TExtract = any> = Omit<\n z.infer<typeof scoringInputWithExtractStepResultSchema>,\n 'extractStepResult'\n> & {\n extractStepResult?: TExtract;\n tracingContext?: TracingContext;\n};\n\nexport const scoringInputWithExtractStepResultAndAnalyzeStepResultSchema =\n scoringInputWithExtractStepResultSchema.extend({\n score: z.number(),\n analyzeStepResult: optionalRecordSchema,\n analyzePrompt: z.string().optional(),\n });\n\nexport type ScoringInputWithExtractStepResultAndAnalyzeStepResult<TExtract = any, TScore = any> = Omit<\n z.infer<typeof scoringInputWithExtractStepResultAndAnalyzeStepResultSchema>,\n 'extractStepResult' | 'analyzeStepResult'\n> & {\n extractStepResult?: TExtract;\n analyzeStepResult?: TScore;\n tracingContext?: TracingContext;\n};\n\nexport const scoringInputWithExtractStepResultAndScoreAndReasonSchema =\n scoringInputWithExtractStepResultAndAnalyzeStepResultSchema.extend({\n reason: z.string().optional(),\n reasonPrompt: z.string().optional(),\n });\n\nexport type ScoringInputWithExtractStepResultAndScoreAndReason = z.infer<\n typeof scoringInputWithExtractStepResultAndScoreAndReasonSchema\n> & {\n tracingContext?: TracingContext;\n};\n\n// ============================================================================\n// Score Row Data (stored in DB)\n// ============================================================================\n\nexport const scoreRowDataSchema = z.object({\n id: z.string(),\n scorerId: z.string(),\n entityId: z.string(),\n\n // From ScoringInputWithExtractStepResultAndScoreAndReason\n runId: z.string(),\n input: z.unknown().optional(),\n output: z.unknown(),\n additionalContext: optionalRecordSchema,\n requestContext: optionalRecordSchema,\n extractStepResult: optionalRecordSchema,\n extractPrompt: z.string().optional(),\n score: z.number(),\n analyzeStepResult: optionalRecordSchema,\n analyzePrompt: z.string().optional(),\n reason: z.string().optional(),\n reasonPrompt: z.string().optional(),\n\n // From ScoringHookInput\n scorer: recordSchema,\n metadata: optionalRecordSchema,\n source: scoringSourceSchema,\n entity: recordSchema,\n entityType: scoringEntityTypeSchema.optional(),\n structuredOutput: z.boolean().optional(),\n traceId: z.string().optional(),\n spanId: z.string().optional(),\n resourceId: z.string().optional(),\n threadId: z.string().optional(),\n\n // Additional ScoreRowData fields\n preprocessStepResult: optionalRecordSchema,\n preprocessPrompt: z.string().optional(),\n generateScorePrompt: z.string().optional(),\n generateReasonPrompt: z.string().optional(),\n\n // Timestamps\n ...dbTimestamps,\n});\n\nexport type ScoreRowData = z.infer<typeof scoreRowDataSchema>;\n\n// ============================================================================\n// Save Score Payload (for creating new scores)\n// ============================================================================\n\nexport const saveScorePayloadSchema = scoreRowDataSchema.omit({\n id: true,\n createdAt: true,\n updatedAt: true,\n});\n\nexport type SaveScorePayload = z.infer<typeof saveScorePayloadSchema>;\n\n// ============================================================================\n// List Scores Response\n// ============================================================================\n\nexport const listScoresResponseSchema = z.object({\n pagination: paginationInfoSchema,\n scores: z.array(scoreRowDataSchema),\n});\n\nexport type ListScoresResponse = z.infer<typeof listScoresResponseSchema>;\n\nexport type ExtractionStepFn = (input: ScoringInput) => Promise<Record<string, any>>;\n\nexport type AnalyzeStepFn = (input: ScoringInputWithExtractStepResult) => Promise<ScoringAnalyzeStepResult>;\n\nexport type ReasonStepFn = (\n input: ScoringInputWithExtractStepResultAndAnalyzeStepResult,\n) => Promise<{ reason: string; reasonPrompt?: string } | null>;\n\nexport type ScorerOptions = {\n name: string;\n description: string;\n extract?: ExtractionStepFn;\n analyze: AnalyzeStepFn;\n reason?: ReasonStepFn;\n metadata?: Record<string, any>;\n isLLMScorer?: boolean;\n};\n\nexport type ScorerRunInputForAgent = {\n inputMessages: MastraDBMessage[];\n rememberedMessages: MastraDBMessage[];\n systemMessages: CoreMessage[];\n taggedSystemMessages: Record<string, CoreSystemMessage[]>;\n};\n\nexport type ScorerRunOutputForAgent = MastraDBMessage[];\n","import { z } from 'zod';\nimport { scoreRowDataSchema } from '../../../evals/types';\nimport { SpanType } from '../../../observability/types';\nimport {\n dateRangeSchema,\n dbTimestamps,\n entityIdField,\n entityNameField,\n entityTypeField,\n environmentField,\n organizationIdField,\n paginationArgsSchema,\n paginationInfoSchema,\n requestIdField,\n resourceIdField,\n runIdField,\n serviceNameField,\n sessionIdField,\n sortDirectionSchema,\n sourceField,\n threadIdField,\n userIdField,\n} from '../shared';\n\n/** Strategy for how tracing data is persisted to storage */\nexport type TracingStorageStrategy = 'realtime' | 'batch-with-updates' | 'insert-only';\n\n// ============================================================================\n// Helper utilities for creating omit key objects from schema shapes\n// ============================================================================\n\n/**\n * Creates an omit key object from a Zod schema shape.\n * This allows dynamically deriving omit keys from existing schema definitions.\n */\nconst createOmitKeys = <T extends z.ZodRawShape>(shape: T): { [K in keyof T]: true } =>\n Object.fromEntries(Object.keys(shape).map(k => [k, true])) as { [K in keyof T]: true };\n\n// ============================================================================\n// Primitive Field Definitions\n// ============================================================================\n\n/** Zod schema for trace ID field */\nexport const traceIdField = z.string().describe('Unique trace identifier');\n\n/** Zod schema for span ID field */\nexport const spanIdField = z.string().describe('Unique span identifier within a trace');\n\nconst spanNameField = z.string().describe('Human-readable span name');\nconst parentSpanIdField = z.string().describe('Parent span reference (null = root span)');\nconst spanTypeField = z.nativeEnum(SpanType).describe('Span type (e.g., WORKFLOW_RUN, AGENT_RUN, TOOL_CALL, etc.)');\nconst attributesField = z.record(z.unknown()).describe('Span-type specific attributes (e.g., model, tokens, tools)');\nconst metadataField = z.record(z.unknown()).describe('User-defined metadata for custom filtering');\nconst tagsField = z.array(z.string()).describe('Labels for filtering traces (only on the root span)');\nconst scopeField = z\n .record(z.unknown())\n .describe('Arbitrary package/app version info (e.g., {\"core\": \"1.0.0\", \"memory\": \"1.0.0\", \"gitSha\": \"abcd1234\"})');\nconst linksField = z.array(z.unknown()).describe('References to related spans in other traces');\nconst inputField = z.unknown().describe('Input data passed to the span');\nconst outputField = z.unknown().describe('Output data returned from the span');\nconst errorField = z.unknown().describe('Error info - presence indicates failure (status derived from this)');\nconst isEventField = z.boolean().describe('Whether this is an event (point-in-time) vs a span (duration)');\nconst startedAtField = z.date().describe('When the span started');\nconst endedAtField = z.date().describe('When the span ended (null = running, status derived from this)');\n\n/** Status of a trace derived from the root span's state */\nexport enum TraceStatus {\n SUCCESS = 'success',\n ERROR = 'error',\n RUNNING = 'running',\n}\n\nconst traceStatusField = z.nativeEnum(TraceStatus).describe('Current status of the trace');\n\nconst hasChildErrorField = z\n .preprocess(v => {\n // Handle string \"true\"/\"false\" from query params correctly\n // z.coerce.boolean() would convert \"false\" to true (Boolean(\"false\") === true)\n if (v === 'true') return true;\n if (v === 'false') return false;\n return v;\n }, z.boolean())\n .describe('True if any span in the trace encountered an error');\n\n// ============================================================================\n// Shared Fields (used by both spanRecordSchema and tracesFilterSchema)\n// ============================================================================\n\n/**\n * All optional fields shared between span records and trace filters.\n * Note: When filtering traces, these fields are matched against the root span.\n */\nconst sharedFields = {\n // Entity identification - first-class fields for filtering (e.g., agent, workflow, tool)\n entityType: entityTypeField.nullish(),\n entityId: entityIdField.nullish(),\n entityName: entityNameField.nullish(),\n\n // Identity & tenancy - for multi-tenant applications\n userId: userIdField.nullish(),\n organizationId: organizationIdField.nullish(),\n resourceId: resourceIdField.nullish(),\n\n // Correlation IDs - for linking related operations\n runId: runIdField.nullish(),\n sessionId: sessionIdField.nullish(),\n threadId: threadIdField.nullish(),\n requestId: requestIdField.nullish(),\n\n // Deployment context - these fields only exist on the root span\n environment: environmentField.nullish(),\n source: sourceField.nullish(),\n serviceName: serviceNameField.nullish(),\n scope: scopeField.nullish(),\n\n // Filterable data - user-defined metadata and tags (tags only on root span)\n metadata: metadataField.nullish(),\n tags: tagsField.nullish(),\n} as const;\n\n// ============================================================================\n// Span Record Schema (for storage)\n// ============================================================================\n\n/** Shape containing trace and span identifier fields */\nexport const spanIds = {\n traceId: traceIdField,\n spanId: spanIdField,\n} as const satisfies z.ZodRawShape;\n\n/** Schema for span identifiers (traceId and spanId) */\nexport const spanIdsSchema = z.object({\n ...spanIds,\n});\n\n/** Span identifier pair (traceId and spanId) */\nexport type SpanIds = z.infer<typeof spanIdsSchema>;\n\n// Omit key objects derived from schema shapes for use with .omit()\nconst omitDbTimestamps = createOmitKeys(dbTimestamps);\nconst omitSpanIds = createOmitKeys(spanIds);\n\n/** Schema for a complete span record as stored in the database */\nexport const spanRecordSchema = z\n .object({\n // Required identifiers\n ...spanIds,\n name: spanNameField,\n spanType: spanTypeField,\n isEvent: isEventField,\n startedAt: startedAtField,\n\n // Shared fields\n parentSpanId: parentSpanIdField.nullish(),\n ...sharedFields,\n\n // Additional span-specific nullish fields\n attributes: attributesField.nullish(),\n links: linksField.nullish(),\n input: inputField.nullish(),\n output: outputField.nullish(),\n error: errorField.nullish(),\n endedAt: endedAtField.nullish(),\n\n // Database timestamps\n ...dbTimestamps,\n })\n .describe('Span record data');\n\n/** Complete span record as stored in the database */\nexport type SpanRecord = z.infer<typeof spanRecordSchema>;\n\n// ============================================================================\n// Trace Span Schema (SpanRecord + computed status for list responses)\n// ============================================================================\n\n/**\n * Computes the trace status from a root span's error and endedAt fields.\n * - ERROR: if error is present (regardless of endedAt)\n * - RUNNING: if endedAt is null/undefined and no error\n * - SUCCESS: if endedAt is present and no error\n */\nexport function computeTraceStatus(span: SpanRecord): TraceStatus {\n if (span.error != null) return TraceStatus.ERROR;\n if (span.endedAt == null) return TraceStatus.RUNNING;\n return TraceStatus.SUCCESS;\n}\n\n/** Schema for a trace span (root span with computed status) */\nexport const traceSpanSchema = spanRecordSchema\n .extend({\n status: traceStatusField,\n })\n .describe('Trace span with computed status (root spans only)');\n\n/** Trace span (root span with computed status) */\nexport type TraceSpan = z.infer<typeof traceSpanSchema>;\n\n/**\n * Converts a SpanRecord to a TraceSpan by adding computed status.\n * Used when returning root spans from listTraces.\n */\nexport function toTraceSpan(span: SpanRecord): TraceSpan {\n return {\n ...span,\n status: computeTraceStatus(span),\n };\n}\n\n/**\n * Converts an array of SpanRecords to TraceSpans by adding computed status.\n * Used when returning root spans from listTraces.\n */\nexport function toTraceSpans(spans: SpanRecord[]): TraceSpan[] {\n return spans.map(toTraceSpan);\n}\n\n// ============================================================================\n// Storage Operation Schemas\n// ============================================================================\n\n/**\n * Schema for creating a span (without db timestamps)\n */\nexport const createSpanRecordSchema = spanRecordSchema.omit(omitDbTimestamps);\n\n/** Span record for creation (excludes db timestamps) */\nexport type CreateSpanRecord = z.infer<typeof createSpanRecordSchema>;\n\n/**\n * Schema for createSpan operation arguments\n */\nexport const createSpanArgsSchema = z\n .object({\n span: createSpanRecordSchema,\n })\n .describe('Arguments for creating a single span');\n\n/** Arguments for creating a single span */\nexport type CreateSpanArgs = z.infer<typeof createSpanArgsSchema>;\n\n/**\n * Schema for batchCreateSpans operation arguments\n */\nexport const batchCreateSpansArgsSchema = z\n .object({\n records: z.array(createSpanRecordSchema),\n })\n .describe('Arguments for batch creating spans');\n\n/** Arguments for batch creating multiple spans */\nexport type BatchCreateSpansArgs = z.infer<typeof batchCreateSpansArgsSchema>;\n\n/**\n * Schema for getSpan operation arguments\n */\nexport const getSpanArgsSchema = z\n .object({\n traceId: traceIdField.min(1),\n spanId: spanIdField.min(1),\n })\n .describe('Arguments for getting a single span');\n\n/** Arguments for retrieving a single span */\nexport type GetSpanArgs = z.infer<typeof getSpanArgsSchema>;\n\n/**\n * Response schema for getSpan operation\n */\nexport const getSpanResponseSchema = z.object({\n span: spanRecordSchema,\n});\n\n/** Response containing a single span */\nexport type GetSpanResponse = z.infer<typeof getSpanResponseSchema>;\n\n/**\n * Schema for getRootSpan operation arguments\n */\nexport const getRootSpanArgsSchema = z\n .object({\n traceId: traceIdField.min(1),\n })\n .describe('Arguments for getting a root span');\n\n/** Arguments for retrieving a root span */\nexport type GetRootSpanArgs = z.infer<typeof getRootSpanArgsSchema>;\n\n/**\n * Response schema for getRootSpan operation\n */\nexport const getRootSpanResponseSchema = z.object({\n span: spanRecordSchema,\n});\n\n/** Response containing a single root span */\nexport type GetRootSpanResponse = z.infer<typeof getRootSpanResponseSchema>;\n\n/**\n * Schema for getTrace operation arguments\n */\nexport const getTraceArgsSchema = z\n .object({\n traceId: traceIdField.min(1),\n })\n .describe('Arguments for getting a single trace');\n\n/** Arguments for retrieving a single trace */\nexport type GetTraceArgs = z.infer<typeof getTraceArgsSchema>;\n\n/**\n * Response schema for getTrace operation\n */\nexport const getTraceResponseSchema = z.object({\n traceId: traceIdField,\n spans: z.array(spanRecordSchema),\n});\n\n/** Response containing a trace with all its spans */\nexport type GetTraceResponse = z.infer<typeof getTraceResponseSchema>;\n\nexport type TraceRecord = GetTraceResponse;\n\n/** Schema for filtering traces in list queries */\nexport const tracesFilterSchema = z\n .object({\n // Date range filters\n startedAt: dateRangeSchema.optional().describe('Filter by span start time range'),\n endedAt: dateRangeSchema.optional().describe('Filter by span end time range'),\n\n // Span type filter\n spanType: spanTypeField.optional(),\n\n // Shared fields\n ...sharedFields,\n\n // Filter-specific derived status fields\n status: traceStatusField.optional(),\n hasChildError: hasChildErrorField.optional(),\n })\n .describe('Filters for querying traces');\n\n/**\n * Fields available for ordering trace results\n */\nexport const tracesOrderByFieldSchema = z\n .enum(['startedAt', 'endedAt'])\n .describe(\"Field to order by: 'startedAt' | 'endedAt'\");\n\n/**\n * Order by configuration for trace queries\n * Follows the existing StorageOrderBy pattern\n * Defaults to startedAt desc (newest first)\n */\nexport const tracesOrderBySchema = z\n .object({\n field: tracesOrderByFieldSchema.default('startedAt').describe('Field to order by'),\n direction: sortDirectionSchema.default('DESC').describe('Sort direction'),\n })\n .describe('Order by configuration');\n\n/**\n * Arguments for listing traces\n */\nexport const listTracesArgsSchema = z\n .object({\n filters: tracesFilterSchema.optional().describe('Optional filters to apply'),\n pagination: paginationArgsSchema.default({}).describe('Pagination settings'),\n orderBy: tracesOrderBySchema.default({}).describe('Ordering configuration (defaults to startedAt desc)'),\n })\n .describe('Arguments for listing traces');\n\n/** Arguments for listing traces with optional filters, pagination, and ordering */\nexport type ListTracesArgs = z.input<typeof listTracesArgsSchema>;\n\n/** Schema for listTraces operation response */\nexport const listTracesResponseSchema = z.object({\n pagination: paginationInfoSchema,\n spans: z.array(traceSpanSchema),\n});\n\n/** Response containing paginated root spans with computed status */\nexport type ListTracesResponse = z.infer<typeof listTracesResponseSchema>;\n\n/**\n * Schema for updating a span (without db timestamps and span IDs)\n */\nexport const updateSpanRecordSchema = createSpanRecordSchema.omit(omitSpanIds);\n\n/** Partial span data for updates (excludes db timestamps and span IDs) */\nexport type UpdateSpanRecord = z.infer<typeof updateSpanRecordSchema>;\n\n/**\n * Schema for updateSpan operation arguments\n */\nexport const updateSpanArgsSchema = z\n .object({\n spanId: spanIdField,\n traceId: traceIdField,\n updates: updateSpanRecordSchema.partial(),\n })\n .describe('Arguments for updating a single span');\n\n/** Arguments for updating a single span */\nexport type UpdateSpanArgs = z.infer<typeof updateSpanArgsSchema>;\n\n/**\n * Schema for batchUpdateSpans operation arguments\n */\nexport const batchUpdateSpansArgsSchema = z\n .object({\n records: z.array(\n z.object({\n traceId: traceIdField,\n spanId: spanIdField,\n updates: updateSpanRecordSchema.partial(),\n }),\n ),\n })\n .describe('Arguments for batch updating spans');\n\n/** Arguments for batch updating multiple spans */\nexport type BatchUpdateSpansArgs = z.infer<typeof batchUpdateSpansArgsSchema>;\n\n/**\n * Schema for batchDeleteTraces operation arguments\n */\nexport const batchDeleteTracesArgsSchema = z\n .object({\n traceIds: z.array(traceIdField),\n })\n .describe('Arguments for batch deleting traces');\n\n/** Arguments for batch deleting multiple traces */\nexport type BatchDeleteTracesArgs = z.infer<typeof batchDeleteTracesArgsSchema>;\n\n// ============================================================================\n// Scoring related schemas\n// ============================================================================\n\n/** Schema for listScoresBySpan operation response */\nexport const listScoresBySpanResponseSchema = z.object({\n pagination: paginationInfoSchema,\n scores: z.array(scoreRowDataSchema),\n});\n\n/** Schema for scoreTraces operation request */\nexport const scoreTracesRequestSchema = z.object({\n scorerName: z.string().min(1),\n targets: z\n .array(\n z.object({\n traceId: traceIdField,\n spanId: spanIdField.optional(),\n }),\n )\n .min(1),\n});\n\n/** Request to score traces using a specific scorer */\nexport type ScoreTracesRequest = z.infer<typeof scoreTracesRequestSchema>;\n\n/** Schema for scoreTraces operation response */\nexport const scoreTracesResponseSchema = z.object({\n status: z.string(),\n message: z.string(),\n traceCount: z.number(),\n});\n\n/** Response from scoring traces */\nexport type ScoreTracesResponse = z.infer<typeof scoreTracesResponseSchema>;\n","import type { z } from 'zod';\nimport type { AgentExecutionOptionsBase } from '../agent/agent.types';\nimport type { SerializedError } from '../error';\nimport type { ScoringSamplingConfig } from '../evals/types';\nimport type { MastraDBMessage, StorageThreadType, SerializedMemoryConfig } from '../memory/types';\nimport { getZodTypeName } from '../utils/zod-utils';\nimport type { StepResult, WorkflowRunState, WorkflowRunStatus } from '../workflows';\n\nexport type StoragePagination = {\n page: number;\n perPage: number | false;\n};\n\nexport type StorageColumnType = 'text' | 'timestamp' | 'uuid' | 'jsonb' | 'integer' | 'float' | 'bigint' | 'boolean';\n\nexport interface StorageColumn {\n type: StorageColumnType;\n primaryKey?: boolean;\n nullable?: boolean;\n references?: {\n table: string;\n column: string;\n };\n}\nexport interface WorkflowRuns {\n runs: WorkflowRun[];\n total: number;\n}\n\nexport interface StorageWorkflowRun {\n workflow_name: string;\n run_id: string;\n resourceId?: string;\n snapshot: WorkflowRunState | string;\n createdAt: Date;\n updatedAt: Date;\n}\nexport interface WorkflowRun {\n workflowName: string;\n runId: string;\n snapshot: WorkflowRunState | string;\n createdAt: Date;\n updatedAt: Date;\n resourceId?: string;\n}\n\nexport type PaginationInfo = {\n total: number;\n page: number;\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * When `false`, all matching records are returned in a single response.\n */\n perPage: number | false;\n hasMore: boolean;\n};\n\nexport type MastraMessageFormat = 'v1' | 'v2';\n\n/**\n * Common options for listing messages (pagination, filtering, ordering)\n */\ntype StorageListMessagesOptions = {\n include?: {\n id: string;\n threadId?: string;\n withPreviousMessages?: number;\n withNextMessages?: number;\n }[];\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * Defaults to 40 if not specified.\n */\n perPage?: number | false;\n /**\n * Zero-indexed page number for pagination.\n * Defaults to 0 if not specified.\n */\n page?: number;\n filter?: {\n dateRange?: {\n start?: Date;\n end?: Date;\n /**\n * When true, excludes the start date from results (uses > instead of >=).\n * Useful for cursor-based pagination to avoid duplicates.\n * @default false\n */\n startExclusive?: boolean;\n /**\n * When true, excludes the end date from results (uses < instead of <=).\n * Useful for cursor-based pagination to avoid duplicates.\n * @default false\n */\n endExclusive?: boolean;\n };\n };\n orderBy?: StorageOrderBy<'createdAt'>;\n};\n\n/**\n * Input for listing messages by thread ID.\n * The resource ID can be optionally provided to filter messages within the thread.\n */\nexport type StorageListMessagesInput = StorageListMessagesOptions & {\n /**\n * Thread ID(s) to query messages from.\n */\n threadId: string | string[];\n /**\n * Optional resource ID to further filter messages within the thread(s).\n */\n resourceId?: string;\n};\n\nexport type StorageListMessagesOutput = PaginationInfo & {\n messages: MastraDBMessage[];\n};\n\n/**\n * Input for listing messages by resource ID only (across all threads).\n * Used by Observational Memory and LongMemEval for resource-scoped queries.\n */\nexport type StorageListMessagesByResourceIdInput = StorageListMessagesOptions & {\n /**\n * Resource ID to query ALL messages for the resource across all threads.\n */\n resourceId: string;\n};\n\nexport type StorageListWorkflowRunsInput = {\n workflowName?: string;\n fromDate?: Date;\n toDate?: Date;\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * When undefined, returns all workflow runs without pagination.\n * When both perPage and page are provided, pagination is applied.\n */\n perPage?: number | false;\n /**\n * Zero-indexed page number for pagination.\n * When both perPage and page are provided, pagination is applied.\n * When either is undefined, all results are returned.\n */\n page?: number;\n resourceId?: string;\n status?: WorkflowRunStatus;\n};\n\nexport type StorageListThreadsInput = {\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * Defaults to 100 if not specified.\n */\n perPage?: number | false;\n /**\n * Zero-indexed page number for pagination.\n * Defaults to 0 if not specified.\n */\n page?: number;\n orderBy?: StorageOrderBy;\n /**\n * Filter options for querying threads.\n */\n filter?: {\n /**\n * Filter threads by resource ID.\n */\n resourceId?: string;\n /**\n * Filter threads by metadata key-value pairs.\n * All specified key-value pairs must match (AND logic).\n */\n metadata?: Record<string, unknown>;\n };\n};\n\nexport type StorageListThreadsOutput = PaginationInfo & {\n threads: StorageThreadType[];\n};\n\n/**\n * Metadata stored on cloned threads to track their origin\n */\nexport type ThreadCloneMetadata = {\n /** ID of the thread this was cloned from */\n sourceThreadId: string;\n /** Timestamp when the clone was created */\n clonedAt: Date;\n /** ID of the last message included in the clone (if messages were copied) */\n lastMessageId?: string;\n};\n\n/**\n * Input options for cloning a thread\n */\nexport type StorageCloneThreadInput = {\n /** ID of the thread to clone */\n sourceThreadId: string;\n /** ID for the new cloned thread (if not provided, a random UUID will be generated) */\n newThreadId?: string;\n /** Resource ID for the new thread (defaults to source thread's resourceId) */\n resourceId?: string;\n /** Title for the new cloned thread */\n title?: string;\n /** Additional metadata to merge with clone metadata */\n metadata?: Record<string, unknown>;\n /** Options for filtering which messages to include */\n options?: {\n /** Maximum number of messages to copy (from most recent) */\n messageLimit?: number;\n /** Filter messages by date range or specific IDs */\n messageFilter?: {\n /** Only include messages created on or after this date */\n startDate?: Date;\n /** Only include messages created on or before this date */\n endDate?: Date;\n /** Only include messages with these specific IDs */\n messageIds?: string[];\n };\n };\n};\n\n/**\n * Output from cloning a thread\n */\nexport type StorageCloneThreadOutput = {\n /** The newly created cloned thread */\n thread: StorageThreadType;\n /** The messages that were copied to the new thread */\n clonedMessages: MastraDBMessage[];\n};\n\nexport type StorageResourceType = {\n id: string;\n workingMemory?: string;\n metadata?: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n};\n\nexport type StorageMessageType = {\n id: string;\n thread_id: string;\n content: string;\n role: string;\n type: string;\n createdAt: Date;\n resourceId: string | null;\n};\n\nexport interface StorageOrderBy<TField extends ThreadOrderBy = ThreadOrderBy> {\n field?: TField;\n direction?: ThreadSortDirection;\n}\n\nexport interface ThreadSortOptions {\n orderBy?: ThreadOrderBy;\n sortDirection?: ThreadSortDirection;\n}\n\nexport type ThreadOrderBy = 'createdAt' | 'updatedAt';\n\nexport type ThreadSortDirection = 'ASC' | 'DESC';\n\n// Agent Storage Types\n\n/**\n * Scorer reference with optional sampling configuration\n */\nexport interface StorageScorerConfig {\n /** Sampling configuration for this scorer */\n sampling?: ScoringSamplingConfig;\n}\n\n/**\n * Model configuration stored in agent snapshots.\n */\nexport interface StorageModelConfig {\n /** Model provider (e.g., 'openai', 'anthropic') */\n provider: string;\n /** Model name (e.g., 'gpt-4o', 'claude-3-opus') */\n name: string;\n /** Temperature for generation */\n temperature?: number;\n /** Top-p sampling parameter */\n topP?: number;\n /** Frequency penalty */\n frequencyPenalty?: number;\n /** Presence penalty */\n presencePenalty?: number;\n /** Maximum completion tokens */\n maxCompletionTokens?: number;\n /** Additional provider-specific options */\n [key: string]: unknown;\n}\n\n/**\n * Default options stored in agent snapshots.\n * Based on AgentExecutionOptionsBase but omitting non-serializable properties.\n *\n * Non-serializable properties that are omitted:\n * - Callbacks (onStepFinish, onFinish, onChunk, onError, onAbort, prepareStep)\n * - Runtime objects (requestContext, abortSignal, tracingContext)\n * - Functions and processor instances (inputProcessors, outputProcessors, clientTools, scorers)\n * - Tools/toolsets (contain functions, stored separately as references)\n * - Complex types (context, memory, instructions, system, stopWhen)\n */\nexport type StorageDefaultOptions = Omit<\n AgentExecutionOptionsBase<any>,\n // Callback functions\n | 'onStepFinish'\n | 'onFinish'\n | 'onChunk'\n | 'onError'\n | 'onAbort'\n | 'prepareStep'\n // Runtime objects\n | 'abortSignal'\n | 'requestContext'\n | 'tracingContext'\n // Functions and processor instances\n | 'inputProcessors'\n | 'outputProcessors'\n | 'clientTools'\n | 'scorers'\n | 'toolsets'\n // Complex types\n | 'context' // ModelMessage includes complex content types (images, files)\n | 'memory' // AgentMemoryOption might contain runtime memory instances\n | 'instructions' // SystemMessage can be arrays or complex message objects\n | 'system' // SystemMessage can be arrays or complex message objects\n | 'stopWhen' // StopCondition is a complex union type from AI SDK\n | 'providerOptions' // ProviderOptions includes provider-specific types from external packages\n>;\n\n/**\n * Agent version snapshot type containing ALL agent configuration fields.\n * These fields live exclusively in version snapshot rows, not on the agent record.\n */\nexport interface StorageAgentSnapshotType {\n /** Display name of the agent */\n name: string;\n /** Purpose description */\n description?: string;\n /** System instructions/prompt */\n instructions: string;\n /** Model configuration (provider, name, etc.) */\n model: StorageModelConfig;\n /** Array of tool keys to resolve from Mastra's tool registry */\n tools?: string[];\n /** Default options for generate/stream calls */\n defaultOptions?: StorageDefaultOptions;\n /** Array of workflow keys to resolve from Mastra's workflow registry */\n workflows?: string[];\n /** Array of agent keys to resolve from Mastra's agent registry */\n agents?: string[];\n /**\n * Array of specific integration tool IDs selected for this agent.\n * Format: \"provider_toolkitSlug_toolSlug\" (e.g., \"composio_hackernews_HACKERNEWS_GET_FRONTPAGE\")\n */\n integrationTools?: string[];\n /** Array of processor keys to resolve from Mastra's processor registry */\n inputProcessors?: string[];\n /** Array of processor keys to resolve from Mastra's processor registry */\n outputProcessors?: string[];\n /** Memory configuration object */\n memory?: SerializedMemoryConfig;\n /** Scorer keys with optional sampling config, to resolve from Mastra's scorer registry */\n scorers?: Record<string, StorageScorerConfig>;\n}\n\n/**\n * Thin agent record type containing only metadata fields.\n * All configuration lives in version snapshots (StorageAgentSnapshotType).\n */\nexport interface StorageAgentType {\n /** Unique, immutable identifier */\n id: string;\n /** Agent status: 'draft' on creation, 'published' when a version is activated */\n status: string;\n /** FK to agent_versions.id - the currently active version */\n activeVersionId?: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata for the agent */\n metadata?: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/**\n * Resolved agent type that combines the thin agent record with version snapshot config.\n * Returned by getAgentByIdResolved and listAgentsResolved.\n */\nexport type StorageResolvedAgentType = StorageAgentType & StorageAgentSnapshotType;\n\n/**\n * Input for creating a new agent. Flat union of thin record fields\n * and initial configuration (used to create version 1).\n */\nexport type StorageCreateAgentInput = {\n /** Unique identifier for the agent */\n id: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata for the agent */\n metadata?: Record<string, unknown>;\n} & StorageAgentSnapshotType;\n\n/**\n * Input for updating an agent. Includes metadata-level fields and optional config fields.\n * The handler layer separates these into agent-record updates vs new-version creation.\n */\nexport type StorageUpdateAgentInput = {\n id: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata for the agent */\n metadata?: Record<string, unknown>;\n /** FK to agent_versions.id - the currently active version */\n activeVersionId?: string;\n /** Agent status: 'draft' or 'published' */\n status?: string;\n} & Partial<StorageAgentSnapshotType>;\n\nexport type StorageListAgentsInput = {\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * Defaults to 100 if not specified.\n */\n perPage?: number | false;\n /**\n * Zero-indexed page number for pagination.\n * Defaults to 0 if not specified.\n */\n page?: number;\n orderBy?: StorageOrderBy;\n /**\n * Filter agents by author identifier (indexed for fast lookups).\n * Only agents with matching authorId will be returned.\n */\n authorId?: string;\n /**\n * Filter agents by metadata key-value pairs.\n * All specified key-value pairs must match (AND logic).\n */\n metadata?: Record<string, unknown>;\n};\n\nexport type StorageListAgentsOutput = PaginationInfo & {\n agents: StorageAgentType[];\n};\n\nexport type StorageListAgentsResolvedOutput = PaginationInfo & {\n agents: StorageResolvedAgentType[];\n};\n\n// Basic Index Management Types\nexport interface CreateIndexOptions {\n name: string;\n table: string;\n columns: string[];\n unique?: boolean;\n concurrent?: boolean;\n /**\n * SQL WHERE clause for creating partial indexes.\n * @internal Reserved for internal use only. Callers must pre-validate this value.\n * DDL statements cannot use parameterized queries for WHERE clauses, so this value\n * is concatenated directly into the SQL. Any user-facing usage must validate input.\n */\n where?: string;\n method?: 'btree' | 'hash' | 'gin' | 'gist' | 'spgist' | 'brin';\n opclass?: string; // Operator class for GIN/GIST indexes\n storage?: Record<string, any>; // Storage parameters\n tablespace?: string; // Tablespace name\n}\n\nexport interface IndexInfo {\n name: string;\n table: string;\n columns: string[];\n unique: boolean;\n size: string;\n definition: string;\n}\n\nexport interface StorageIndexStats extends IndexInfo {\n scans: number; // Number of index scans\n tuples_read: number; // Number of tuples read\n tuples_fetched: number; // Number of tuples fetched\n last_used?: Date; // Last time index was used\n method?: string; // Index method (btree, hash, etc)\n}\n\n// ============================================\n// Observational Memory Types\n// ============================================\n\n/**\n * Scope of observational memory\n */\nexport type ObservationalMemoryScope = 'thread' | 'resource';\n\n/**\n * How the observational memory record was created\n */\nexport type ObservationalMemoryOriginType = 'initial' | 'reflection';\n\n/**\n * Core database record for observational memory\n *\n * For resource scope: One active record per resource, containing observations from ALL threads.\n * For thread scope: One record per thread.\n *\n * Derived values (not stored, computed at runtime):\n * - reflectionCount: count records with originType: 'reflection'\n * - lastReflectionAt: createdAt of most recent reflection record\n * - previousGeneration: record with next-oldest createdAt\n */\nexport interface ObservationalMemoryRecord {\n // Identity\n /** Unique record ID */\n id: string;\n /** Memory scope - thread or resource */\n scope: ObservationalMemoryScope;\n /** Thread ID (null for resource scope) */\n threadId: string | null;\n /** Resource ID (always present) */\n resourceId: string;\n\n // Timestamps (top-level for easy querying)\n /** When this record was created */\n createdAt: Date;\n /** When this record was last updated */\n updatedAt: Date;\n /**\n * Single cursor for message loading - when we last observed ANY thread for this resource.\n * Undefined means no observations have been made yet (all messages are \"unobserved\").\n */\n lastObservedAt?: Date;\n\n // Generation tracking\n /** How this record was created */\n originType: ObservationalMemoryOriginType;\n /** Generation counter - incremented each time a reflection creates a new record */\n generationCount: number;\n\n // Observation content\n /**\n * Currently active observations.\n * For resource scope: Contains <thread id=\"...\">...</thread> sections for attribution.\n * For thread scope: Plain observation text.\n */\n activeObservations: string;\n /** Observations waiting to be activated (async buffering) */\n bufferedObservations?: string;\n /** Reflection waiting to be swapped in (async buffering) */\n bufferedReflection?: string;\n\n /**\n * Message IDs observed in the current generation.\n * Used as a safeguard against re-observation if timestamp filtering fails.\n * Reset on reflection (new generation starts fresh).\n */\n observedMessageIds?: string[];\n\n /**\n * The timezone used when formatting dates for the Observer agent.\n * Stored for debugging and auditing observation dates.\n * Example: \"America/Los_Angeles\", \"Europe/London\"\n */\n observedTimezone?: string;\n\n // Token tracking\n /** Running total of all tokens observed */\n totalTokensObserved: number;\n /** Current size of active observations */\n observationTokenCount: number;\n /** Accumulated tokens from pending (unobserved) messages across sessions */\n pendingMessageTokens: number;\n\n // State flags\n /** Is a reflection currently in progress? */\n isReflecting: boolean;\n /** Is observation currently in progress? */\n isObserving: boolean;\n\n // Configuration\n /** Current configuration (stored as JSON) */\n config: Record<string, unknown>;\n\n // Extensible metadata (app-specific, optional)\n /** Optional metadata for app-specific extensions */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Input for creating a new observational memory record\n */\nexport interface CreateObservationalMemoryInput {\n threadId: string | null;\n resourceId: string;\n scope: ObservationalMemoryScope;\n config: Record<string, unknown>;\n /** The timezone used when formatting dates for the Observer agent (e.g., \"America/Los_Angeles\") */\n observedTimezone?: string;\n}\n\n/**\n * Input for updating active observations.\n * Uses cursor-based message tracking via lastObservedAt instead of message IDs.\n */\nexport interface UpdateActiveObservationsInput {\n id: string;\n observations: string;\n tokenCount: number;\n /** Timestamp when these observations were created (for cursor-based message loading) */\n lastObservedAt: Date;\n /**\n * IDs of messages that were observed in this cycle.\n * Stored in record metadata as a safeguard against re-observation on process restart.\n * These are appended to any existing IDs and pruned to only include IDs newer than lastObservedAt.\n */\n observedMessageIds?: string[];\n /**\n * The timezone used when formatting dates for the Observer agent.\n * Captured from Intl.DateTimeFormat().resolvedOptions().timeZone\n */\n observedTimezone?: string;\n}\n\n/**\n * Input for updating buffered observations.\n * Note: Async buffering is currently disabled but types are retained for future use.\n */\nexport interface UpdateBufferedObservationsInput {\n id: string;\n observations: string;\n suggestedContinuation?: string;\n}\n\n/**\n * Input for creating a reflection generation (creates a new record, archives the old one)\n */\nexport interface CreateReflectionGenerationInput {\n currentRecord: ObservationalMemoryRecord;\n reflection: string;\n tokenCount: number;\n}\n\n// ============================================\n// Workflow Storage Types\n// ============================================\n\nexport interface UpdateWorkflowStateOptions {\n status: WorkflowRunStatus;\n result?: StepResult<any, any, any, any>;\n error?: SerializedError;\n suspendedPaths?: Record<string, number[]>;\n waitingPaths?: Record<string, number[]>;\n resumeLabels?: Record<string, { stepId: string; foreachIndex?: number }>;\n}\n\n/**\n * Get the inner type from a wrapper schema (nullable, optional, default, effects, branded).\n * Compatible with both Zod 3 and Zod 4.\n */\nfunction getInnerType(schema: z.ZodTypeAny, typeName: string): z.ZodTypeAny | undefined {\n const schemaAny = schema as any;\n\n // For nullable, optional, default - the inner type is at _def.innerType\n if (typeName === 'ZodNullable' || typeName === 'ZodOptional' || typeName === 'ZodDefault') {\n return schemaAny._zod?.def?.innerType ?? schemaAny._def?.innerType;\n }\n\n // For effects - the inner type is at _def.schema\n if (typeName === 'ZodEffects') {\n return schemaAny._zod?.def?.schema ?? schemaAny._def?.schema;\n }\n\n // For branded - the inner type is at _def.type\n if (typeName === 'ZodBranded') {\n return schemaAny._zod?.def?.type ?? schemaAny._def?.type;\n }\n\n return undefined;\n}\n\nfunction unwrapSchema(schema: z.ZodTypeAny): { base: z.ZodTypeAny; nullable: boolean } {\n let current = schema;\n let nullable = false;\n\n while (true) {\n const typeName = getZodTypeName(current);\n\n if (typeName === 'ZodNullable') {\n nullable = true;\n const inner = getInnerType(current, typeName);\n if (inner) {\n current = inner;\n continue;\n }\n }\n\n if (typeName === 'ZodOptional') {\n // For DB purposes, we usually treat \"optional\" as \"nullable\"\n nullable = true;\n const inner = getInnerType(current, typeName);\n if (inner) {\n current = inner;\n continue;\n }\n }\n\n if (typeName === 'ZodDefault') {\n const inner = getInnerType(current, typeName);\n if (inner) {\n current = inner;\n continue;\n }\n }\n\n if (typeName === 'ZodEffects') {\n const inner = getInnerType(current, typeName);\n if (inner) {\n current = inner;\n continue;\n }\n }\n\n if (typeName === 'ZodBranded') {\n const inner = getInnerType(current, typeName);\n if (inner) {\n current = inner;\n continue;\n }\n }\n\n // If you ever use ZodCatch/ZodPipeline, you can unwrap them here too.\n break;\n }\n\n return { base: current, nullable };\n}\n\n/**\n * Extract checks array from Zod schema, compatible with both Zod 3 and Zod 4.\n * Zod 3 uses _def.checks, Zod 4 uses _zod.def.checks.\n */\nfunction getZodChecks(schema: z.ZodTypeAny): Array<{ kind: string }> {\n const schemaAny = schema as any;\n // Zod 4 structure\n if (schemaAny._zod?.def?.checks) {\n return schemaAny._zod.def.checks;\n }\n // Zod 3 structure\n if (schemaAny._def?.checks) {\n return schemaAny._def.checks;\n }\n return [];\n}\n\nfunction zodToStorageType(schema: z.ZodTypeAny): StorageColumnType {\n const typeName = getZodTypeName(schema);\n\n if (typeName === 'ZodString') {\n // Check for UUID validation\n const checks = getZodChecks(schema);\n if (checks.some(c => c.kind === 'uuid')) {\n return 'uuid';\n }\n return 'text';\n }\n if (typeName === 'ZodNativeEnum' || typeName === 'ZodEnum') {\n return 'text';\n }\n if (typeName === 'ZodNumber') {\n // Check for integer validation\n const checks = getZodChecks(schema);\n return checks.some(c => c.kind === 'int') ? 'integer' : 'float';\n }\n if (typeName === 'ZodBigInt') {\n return 'bigint';\n }\n if (typeName === 'ZodDate') {\n return 'timestamp';\n }\n if (typeName === 'ZodBoolean') {\n return 'boolean';\n }\n // fall back for objects/records/unknown\n return 'jsonb';\n}\n\n/**\n * Converts a zod schema into a database schema\n * @param zObject A zod schema object\n * @returns database schema record with StorageColumns\n */\nexport function buildStorageSchema<Shape extends z.ZodRawShape>(\n zObject: z.ZodObject<Shape>,\n): Record<keyof Shape & string, StorageColumn> {\n const shape = zObject.shape;\n const result: Record<string, StorageColumn> = {};\n\n for (const [key, field] of Object.entries(shape)) {\n const { base, nullable } = unwrapSchema(field as z.ZodTypeAny);\n result[key] = {\n type: zodToStorageType(base),\n nullable,\n };\n }\n\n return result as Record<keyof Shape & string, StorageColumn>;\n}\n","import { spanRecordSchema } from './domains/observability/types';\nimport { buildStorageSchema } from './types';\nimport type { StorageColumn } from './types';\n\nexport const TABLE_WORKFLOW_SNAPSHOT = 'mastra_workflow_snapshot';\nexport const TABLE_MESSAGES = 'mastra_messages';\nexport const TABLE_THREADS = 'mastra_threads';\nexport const TABLE_TRACES = 'mastra_traces';\nexport const TABLE_RESOURCES = 'mastra_resources';\nexport const TABLE_SCORERS = 'mastra_scorers';\nexport const TABLE_SPANS = 'mastra_ai_spans';\nexport const TABLE_AGENTS = 'mastra_agents';\nexport const TABLE_AGENT_VERSIONS = 'mastra_agent_versions';\nexport const TABLE_OBSERVATIONAL_MEMORY = 'mastra_observational_memory';\n\nexport type TABLE_NAMES =\n | typeof TABLE_WORKFLOW_SNAPSHOT\n | typeof TABLE_MESSAGES\n | typeof TABLE_THREADS\n | typeof TABLE_TRACES\n | typeof TABLE_RESOURCES\n | typeof TABLE_SCORERS\n | typeof TABLE_SPANS\n | typeof TABLE_AGENTS\n | typeof TABLE_AGENT_VERSIONS;\n\nexport const SCORERS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n scorerId: { type: 'text' },\n traceId: { type: 'text', nullable: true },\n spanId: { type: 'text', nullable: true },\n runId: { type: 'text' },\n scorer: { type: 'jsonb' },\n preprocessStepResult: { type: 'jsonb', nullable: true },\n extractStepResult: { type: 'jsonb', nullable: true },\n analyzeStepResult: { type: 'jsonb', nullable: true },\n score: { type: 'float' },\n reason: { type: 'text', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n preprocessPrompt: { type: 'text', nullable: true },\n extractPrompt: { type: 'text', nullable: true },\n generateScorePrompt: { type: 'text', nullable: true },\n generateReasonPrompt: { type: 'text', nullable: true },\n analyzePrompt: { type: 'text', nullable: true },\n\n // Deprecated\n reasonPrompt: { type: 'text', nullable: true },\n input: { type: 'jsonb' },\n output: { type: 'jsonb' }, // MESSAGE OUTPUT\n additionalContext: { type: 'jsonb', nullable: true }, // DATA FROM THE CONTEXT PARAM ON AN AGENT\n requestContext: { type: 'jsonb', nullable: true }, // THE EVALUATE Request Context FOR THE RUN\n /**\n * Things you can evaluate\n */\n entityType: { type: 'text', nullable: true }, // WORKFLOW, AGENT, TOOL, STEP, NETWORK\n entity: { type: 'jsonb', nullable: true }, // MINIMAL JSON DATA ABOUT WORKFLOW, AGENT, TOOL, STEP, NETWORK\n entityId: { type: 'text', nullable: true },\n source: { type: 'text' },\n resourceId: { type: 'text', nullable: true },\n threadId: { type: 'text', nullable: true },\n createdAt: { type: 'timestamp' },\n updatedAt: { type: 'timestamp' },\n};\n\nexport const SPAN_SCHEMA = buildStorageSchema(spanRecordSchema);\n\n/**\n * @deprecated Use SPAN_SCHEMA instead. This legacy schema is retained only for migration purposes.\n * @internal\n */\nexport const OLD_SPAN_SCHEMA: Record<string, StorageColumn> = {\n // Composite primary key of traceId and spanId\n traceId: { type: 'text', nullable: false },\n spanId: { type: 'text', nullable: false },\n parentSpanId: { type: 'text', nullable: true },\n name: { type: 'text', nullable: false },\n scope: { type: 'jsonb', nullable: true }, // Mastra package info {\"core-version\": \"0.1.0\"}\n spanType: { type: 'text', nullable: false }, // WORKFLOW_RUN, WORKFLOW_STEP, AGENT_RUN, AGENT_STEP, TOOL_RUN, TOOL_STEP, etc.\n attributes: { type: 'jsonb', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n links: { type: 'jsonb', nullable: true },\n input: { type: 'jsonb', nullable: true },\n output: { type: 'jsonb', nullable: true },\n error: { type: 'jsonb', nullable: true },\n startedAt: { type: 'timestamp', nullable: false }, // When the span started\n endedAt: { type: 'timestamp', nullable: true }, // When the span ended\n createdAt: { type: 'timestamp', nullable: false }, // The time the database record was created\n updatedAt: { type: 'timestamp', nullable: true }, // The time the database record was last updated\n isEvent: { type: 'boolean', nullable: false },\n};\n\nexport const AGENTS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n status: { type: 'text', nullable: false }, // 'draft' or 'published'\n activeVersionId: { type: 'text', nullable: true }, // FK to agent_versions.id\n authorId: { type: 'text', nullable: true }, // Author identifier for multi-tenant filtering\n metadata: { type: 'jsonb', nullable: true }, // Additional metadata for the agent\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const AGENT_VERSIONS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true }, // UUID\n agentId: { type: 'text', nullable: false },\n versionNumber: { type: 'integer', nullable: false },\n // Agent config fields\n name: { type: 'text', nullable: false }, // Agent display name\n description: { type: 'text', nullable: true },\n instructions: { type: 'text', nullable: false },\n model: { type: 'jsonb', nullable: false },\n tools: { type: 'jsonb', nullable: true },\n defaultOptions: { type: 'jsonb', nullable: true },\n workflows: { type: 'jsonb', nullable: true },\n agents: { type: 'jsonb', nullable: true },\n integrationTools: { type: 'jsonb', nullable: true },\n inputProcessors: { type: 'jsonb', nullable: true },\n outputProcessors: { type: 'jsonb', nullable: true },\n memory: { type: 'jsonb', nullable: true },\n scorers: { type: 'jsonb', nullable: true },\n // Version metadata\n changedFields: { type: 'jsonb', nullable: true }, // Array of field names\n changeMessage: { type: 'text', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n};\n\nexport const OBSERVATIONAL_MEMORY_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n lookupKey: { type: 'text', nullable: false }, // 'resource:{resourceId}' or 'thread:{threadId}'\n scope: { type: 'text', nullable: false }, // 'resource' or 'thread'\n resourceId: { type: 'text', nullable: true },\n threadId: { type: 'text', nullable: true },\n activeObservations: { type: 'text', nullable: false }, // JSON array of observations\n activeObservationsPendingUpdate: { type: 'text', nullable: true }, // JSON array, used during updates\n originType: { type: 'text', nullable: false }, // 'initialization', 'observation', or 'reflection'\n config: { type: 'text', nullable: false }, // JSON object\n generationCount: { type: 'integer', nullable: false },\n lastObservedAt: { type: 'timestamp', nullable: true },\n lastReflectionAt: { type: 'timestamp', nullable: true },\n pendingMessageTokens: { type: 'integer', nullable: false }, // Token count\n totalTokensObserved: { type: 'integer', nullable: false }, // Running total of all observed tokens\n observationTokenCount: { type: 'integer', nullable: false }, // Current observation size in tokens\n isObserving: { type: 'boolean', nullable: false },\n isReflecting: { type: 'boolean', nullable: false },\n observedMessageIds: { type: 'jsonb', nullable: true }, // JSON array of message IDs already observed\n observedTimezone: { type: 'text', nullable: true }, // Timezone used for Observer date formatting (e.g., \"America/Los_Angeles\")\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\n/**\n * Schema definitions for all core tables.\n */\nexport const TABLE_SCHEMAS: Record<TABLE_NAMES, Record<string, StorageColumn>> = {\n [TABLE_WORKFLOW_SNAPSHOT]: {\n workflow_name: {\n type: 'text',\n },\n run_id: {\n type: 'text',\n },\n resourceId: { type: 'text', nullable: true },\n snapshot: {\n type: 'jsonb',\n },\n createdAt: {\n type: 'timestamp',\n },\n updatedAt: {\n type: 'timestamp',\n },\n },\n [TABLE_SCORERS]: SCORERS_SCHEMA,\n [TABLE_THREADS]: {\n id: { type: 'text', nullable: false, primaryKey: true },\n resourceId: { type: 'text', nullable: false },\n title: { type: 'text', nullable: false },\n metadata: { type: 'jsonb', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n },\n [TABLE_MESSAGES]: {\n id: { type: 'text', nullable: false, primaryKey: true },\n thread_id: { type: 'text', nullable: false },\n content: { type: 'text', nullable: false },\n role: { type: 'text', nullable: false },\n type: { type: 'text', nullable: false },\n createdAt: { type: 'timestamp', nullable: false },\n resourceId: { type: 'text', nullable: true },\n },\n [TABLE_SPANS]: SPAN_SCHEMA,\n [TABLE_TRACES]: {\n id: { type: 'text', nullable: false, primaryKey: true },\n parentSpanId: { type: 'text', nullable: true },\n name: { type: 'text', nullable: false },\n traceId: { type: 'text', nullable: false },\n scope: { type: 'text', nullable: false },\n kind: { type: 'integer', nullable: false },\n attributes: { type: 'jsonb', nullable: true },\n status: { type: 'jsonb', nullable: true },\n events: { type: 'jsonb', nullable: true },\n links: { type: 'jsonb', nullable: true },\n other: { type: 'text', nullable: true },\n startTime: { type: 'bigint', nullable: false },\n endTime: { type: 'bigint', nullable: false },\n createdAt: { type: 'timestamp', nullable: false },\n },\n [TABLE_RESOURCES]: {\n id: { type: 'text', nullable: false, primaryKey: true },\n workingMemory: { type: 'text', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n },\n [TABLE_AGENTS]: AGENTS_SCHEMA,\n [TABLE_AGENT_VERSIONS]: AGENT_VERSIONS_SCHEMA,\n};\n\n/**\n * Schema for the observational memory table.\n * Exported separately as OM is optional and not part of TABLE_NAMES.\n */\nexport const OBSERVATIONAL_MEMORY_TABLE_SCHEMA = {\n [TABLE_OBSERVATIONAL_MEMORY]: OBSERVATIONAL_MEMORY_SCHEMA,\n};\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/storage/domains/shared.ts","../src/evals/types.ts","../src/storage/domains/observability/types.ts","../src/storage/types.ts","../src/storage/constants.ts"],"names":["z","TraceStatus"],"mappings":";;;;AAMO,IAAM,cAAA,GAAiB,CAAA,CAAE,IAAA,EAAK,CAAE,SAAS,+BAA+B;AAExE,IAAM,cAAA,GAAiB,CAAA,CAAE,IAAA,EAAK,CAAE,SAAS,kCAAkC;AAE3E,IAAM,YAAA,GAAe;AAAA,EAC1B,SAAA,EAAW,cAAA;AAAA,EACX,SAAA,EAAW,eAAe,QAAA;AAC5B;AAMO,IA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EAAQ,UAAU,IAAA,EAAK;AAAA,IAC9C,QAAA,EAAU,EAAE,IAAA,EAAM,OAAA,EAAS,UAAU,IAAA,EAAK;AAAA,IAC1C,SAAA,EAAW,EAAE,IAAA,EAAM,WAAA,EAAa,UAAU,KAAA,EAAM;AAAA,IAChD,SAAA,EAAW,EAAE,IAAA,EAAM,WAAA,EAAa,UAAU,KAAA;AAAM,GAClD;AAAA,EACA,CAAC,YAAY,GAAG,aAAA;AAAA,EAChB,CAAC,oBAAoB,GAAG;AAC1B;AAMO,IAAM,iCAAA,GAAoC;AAAA,EAC/C,CAAC,0BAA0B,GAAG;AAChC","file":"chunk-MNWW2R3U.js","sourcesContent":["import { z } from 'zod';\nimport { EntityType } from '../../observability';\n\n/**\n * Common DB fields\n */\nexport const createdAtField = z.date().describe('Database record creation time');\n\nexport const updatedAtField = z.date().describe('Database record last update time');\n\nexport const dbTimestamps = {\n createdAt: createdAtField,\n updatedAt: updatedAtField.nullable(),\n} as const satisfies z.ZodRawShape;\n\n/**\n * Pagination arguments for list queries (page and perPage only)\n * Uses z.coerce to handle string → number conversion from query params\n */\nexport const paginationArgsSchema = z\n .object({\n page: z.coerce.number().int().min(0).optional().default(0).describe('Zero-indexed page number'),\n perPage: z.coerce.number().int().min(1).max(100).optional().default(10).describe('Number of items per page'),\n })\n .describe('Pagination options for list queries');\n\nexport type PaginationArgs = z.input<typeof paginationArgsSchema>;\n\n/**\n * Pagination response info\n * Used across all paginated endpoints\n */\nexport const paginationInfoSchema = z.object({\n total: z.number().describe('Total number of items available'),\n page: z.number().describe('Current page'),\n perPage: z\n .union([z.number(), z.literal(false)])\n .describe('Number of items per page, or false if pagination is disabled'),\n hasMore: z.boolean().describe('True if more pages are available'),\n});\n\n/**\n * Date range for filtering by time\n * Uses z.coerce to handle ISO string → Date conversion from query params\n */\nexport const dateRangeSchema = z\n .object({\n start: z.coerce.date().optional().describe('Start of date range (inclusive by default)'),\n end: z.coerce.date().optional().describe('End of date range (inclusive by default)'),\n startExclusive: z\n .boolean()\n .optional()\n .describe('When true, excludes the start date from results (uses > instead of >=)'),\n endExclusive: z\n .boolean()\n .optional()\n .describe('When true, excludes the end date from results (uses < instead of <=)'),\n })\n .describe('Date range filter for timestamps');\n\nexport type DateRange = z.infer<typeof dateRangeSchema>;\n\nexport const sortDirectionSchema = z.enum(['ASC', 'DESC']).describe(\"Sort direction: 'ASC' | 'DESC'\");\n\nexport const entityTypeField = z\n .nativeEnum(EntityType)\n .describe(`Entity type (e.g., 'agent' | 'processor' | 'tool' | 'workflow')`);\n\nexport const entityIdField = z.string().describe('ID of the entity (e.g., \"weatherAgent\", \"orderWorkflow\")');\n\nexport const entityNameField = z.string().describe('Name of the entity');\n\nexport const userIdField = z.string().describe('Human end-user who triggered execution');\n\nexport const organizationIdField = z.string().describe('Multi-tenant organization/account');\n\nexport const resourceIdField = z.string().describe('Broader resource context (Mastra memory compatibility)');\n\nexport const runIdField = z.string().describe('Unique execution run identifier');\n\nexport const sessionIdField = z.string().describe('Session identifier for grouping traces');\n\nexport const threadIdField = z.string().describe('Conversation thread identifier');\n\nexport const requestIdField = z.string().describe('HTTP request ID for log correlation');\n\nexport const environmentField = z.string().describe(`Environment (e.g., \"production\" | \"staging\" | \"development\")`);\n\nexport const sourceField = z.string().describe(`Source of execution (e.g., \"local\" | \"cloud\" | \"ci\")`);\n\nexport const serviceNameField = z.string().describe('Name of the service');\n","import type { CoreMessage, CoreSystemMessage } from '@internal/ai-sdk-v4';\nimport { z } from 'zod';\nimport type { MastraDBMessage } from '../agent';\nimport { SpanType } from '../observability';\nimport type { TracingContext } from '../observability';\nimport { dbTimestamps, paginationInfoSchema } from '../storage/domains/shared';\n\n// ============================================================================\n// Sampling Config\n// ============================================================================\n\nexport type ScoringSamplingConfig = { type: 'none' } | { type: 'ratio'; rate: number };\n\n// ============================================================================\n// Scoring Source & Entity Type\n// ============================================================================\n\nexport const scoringSourceSchema = z.enum(['LIVE', 'TEST']);\n\nexport type ScoringSource = z.infer<typeof scoringSourceSchema>;\n\nexport const scoringEntityTypeSchema = z.enum(['AGENT', 'WORKFLOW', ...Object.values(SpanType)] as [\n string,\n string,\n ...string[],\n]);\n\nexport type ScoringEntityType = z.infer<typeof scoringEntityTypeSchema>;\n\n// ============================================================================\n// Scoring Prompts\n// ============================================================================\n\nexport const scoringPromptsSchema = z.object({\n description: z.string(),\n prompt: z.string(),\n});\n\nexport type ScoringPrompts = z.infer<typeof scoringPromptsSchema>;\n\n// ============================================================================\n// Shared Record Schemas\n// ============================================================================\n\n/** Reusable schema for required record fields (e.g., scorer, entity) */\nconst recordSchema = z.record(z.string(), z.unknown());\n\n/** Reusable schema for optional record fields (e.g., metadata, additionalContext) */\nconst optionalRecordSchema = recordSchema.optional();\n\n// ============================================================================\n// Base Scoring Input (used for scorer functions)\n// ============================================================================\n\nexport const scoringInputSchema = z.object({\n runId: z.string().optional(),\n input: z.unknown().optional(),\n output: z.unknown(),\n additionalContext: optionalRecordSchema,\n requestContext: optionalRecordSchema,\n // Note: tracingContext is not serializable, so we don't include it in the schema\n // It's added at runtime when needed\n});\n\nexport type ScoringInput = z.infer<typeof scoringInputSchema> & {\n tracingContext?: TracingContext;\n};\n\n// ============================================================================\n// Scoring Hook Input\n// ============================================================================\n\nexport const scoringHookInputSchema = z.object({\n runId: z.string().optional(),\n scorer: recordSchema,\n input: z.unknown(),\n output: z.unknown(),\n metadata: optionalRecordSchema,\n additionalContext: optionalRecordSchema,\n source: scoringSourceSchema,\n entity: recordSchema,\n entityType: scoringEntityTypeSchema,\n requestContext: optionalRecordSchema,\n structuredOutput: z.boolean().optional(),\n traceId: z.string().optional(),\n spanId: z.string().optional(),\n resourceId: z.string().optional(),\n threadId: z.string().optional(),\n // Note: tracingContext is not serializable, so we don't include it in the schema\n});\n\nexport type ScoringHookInput = z.infer<typeof scoringHookInputSchema> & {\n tracingContext?: TracingContext;\n};\n\n// ============================================================================\n// Extract Step Result\n// ============================================================================\n\nexport const scoringExtractStepResultSchema = optionalRecordSchema;\n\nexport type ScoringExtractStepResult = z.infer<typeof scoringExtractStepResultSchema>;\n\n// ============================================================================\n// Analyze Step Result (Score Result)\n// ============================================================================\n\nexport const scoringValueSchema = z.number();\n\nexport const scoreResultSchema = z.object({\n result: optionalRecordSchema,\n score: scoringValueSchema,\n prompt: z.string().optional(),\n});\n\nexport type ScoringAnalyzeStepResult = z.infer<typeof scoreResultSchema>;\n\n// ============================================================================\n// Composite Input Types (for scorer step functions)\n// ============================================================================\n\nexport const scoringInputWithExtractStepResultSchema = scoringInputSchema.extend({\n runId: z.string(), // Required in this context\n extractStepResult: optionalRecordSchema,\n extractPrompt: z.string().optional(),\n});\n\nexport type ScoringInputWithExtractStepResult<TExtract = any> = Omit<\n z.infer<typeof scoringInputWithExtractStepResultSchema>,\n 'extractStepResult'\n> & {\n extractStepResult?: TExtract;\n tracingContext?: TracingContext;\n};\n\nexport const scoringInputWithExtractStepResultAndAnalyzeStepResultSchema =\n scoringInputWithExtractStepResultSchema.extend({\n score: z.number(),\n analyzeStepResult: optionalRecordSchema,\n analyzePrompt: z.string().optional(),\n });\n\nexport type ScoringInputWithExtractStepResultAndAnalyzeStepResult<TExtract = any, TScore = any> = Omit<\n z.infer<typeof scoringInputWithExtractStepResultAndAnalyzeStepResultSchema>,\n 'extractStepResult' | 'analyzeStepResult'\n> & {\n extractStepResult?: TExtract;\n analyzeStepResult?: TScore;\n tracingContext?: TracingContext;\n};\n\nexport const scoringInputWithExtractStepResultAndScoreAndReasonSchema =\n scoringInputWithExtractStepResultAndAnalyzeStepResultSchema.extend({\n reason: z.string().optional(),\n reasonPrompt: z.string().optional(),\n });\n\nexport type ScoringInputWithExtractStepResultAndScoreAndReason = z.infer<\n typeof scoringInputWithExtractStepResultAndScoreAndReasonSchema\n> & {\n tracingContext?: TracingContext;\n};\n\n// ============================================================================\n// Score Row Data (stored in DB)\n// ============================================================================\n\nexport const scoreRowDataSchema = z.object({\n id: z.string(),\n scorerId: z.string(),\n entityId: z.string(),\n\n // From ScoringInputWithExtractStepResultAndScoreAndReason\n runId: z.string(),\n input: z.unknown().optional(),\n output: z.unknown(),\n additionalContext: optionalRecordSchema,\n requestContext: optionalRecordSchema,\n extractStepResult: optionalRecordSchema,\n extractPrompt: z.string().optional(),\n score: z.number(),\n analyzeStepResult: optionalRecordSchema,\n analyzePrompt: z.string().optional(),\n reason: z.string().optional(),\n reasonPrompt: z.string().optional(),\n\n // From ScoringHookInput\n scorer: recordSchema,\n metadata: optionalRecordSchema,\n source: scoringSourceSchema,\n entity: recordSchema,\n entityType: scoringEntityTypeSchema.optional(),\n structuredOutput: z.boolean().optional(),\n traceId: z.string().optional(),\n spanId: z.string().optional(),\n resourceId: z.string().optional(),\n threadId: z.string().optional(),\n\n // Additional ScoreRowData fields\n preprocessStepResult: optionalRecordSchema,\n preprocessPrompt: z.string().optional(),\n generateScorePrompt: z.string().optional(),\n generateReasonPrompt: z.string().optional(),\n\n // Timestamps\n ...dbTimestamps,\n});\n\nexport type ScoreRowData = z.infer<typeof scoreRowDataSchema>;\n\n// ============================================================================\n// Save Score Payload (for creating new scores)\n// ============================================================================\n\nexport const saveScorePayloadSchema = scoreRowDataSchema.omit({\n id: true,\n createdAt: true,\n updatedAt: true,\n});\n\nexport type SaveScorePayload = z.infer<typeof saveScorePayloadSchema>;\n\n// ============================================================================\n// List Scores Response\n// ============================================================================\n\nexport const listScoresResponseSchema = z.object({\n pagination: paginationInfoSchema,\n scores: z.array(scoreRowDataSchema),\n});\n\nexport type ListScoresResponse = z.infer<typeof listScoresResponseSchema>;\n\nexport type ExtractionStepFn = (input: ScoringInput) => Promise<Record<string, any>>;\n\nexport type AnalyzeStepFn = (input: ScoringInputWithExtractStepResult) => Promise<ScoringAnalyzeStepResult>;\n\nexport type ReasonStepFn = (\n input: ScoringInputWithExtractStepResultAndAnalyzeStepResult,\n) => Promise<{ reason: string; reasonPrompt?: string } | null>;\n\nexport type ScorerOptions = {\n name: string;\n description: string;\n extract?: ExtractionStepFn;\n analyze: AnalyzeStepFn;\n reason?: ReasonStepFn;\n metadata?: Record<string, any>;\n isLLMScorer?: boolean;\n};\n\nexport type ScorerRunInputForAgent = {\n inputMessages: MastraDBMessage[];\n rememberedMessages: MastraDBMessage[];\n systemMessages: CoreMessage[];\n taggedSystemMessages: Record<string, CoreSystemMessage[]>;\n};\n\nexport type ScorerRunOutputForAgent = MastraDBMessage[];\n","import { z } from 'zod';\nimport { scoreRowDataSchema } from '../../../evals/types';\nimport { SpanType } from '../../../observability/types';\nimport {\n dateRangeSchema,\n dbTimestamps,\n entityIdField,\n entityNameField,\n entityTypeField,\n environmentField,\n organizationIdField,\n paginationArgsSchema,\n paginationInfoSchema,\n requestIdField,\n resourceIdField,\n runIdField,\n serviceNameField,\n sessionIdField,\n sortDirectionSchema,\n sourceField,\n threadIdField,\n userIdField,\n} from '../shared';\n\n/** Strategy for how tracing data is persisted to storage */\nexport type TracingStorageStrategy = 'realtime' | 'batch-with-updates' | 'insert-only';\n\n// ============================================================================\n// Helper utilities for creating omit key objects from schema shapes\n// ============================================================================\n\n/**\n * Creates an omit key object from a Zod schema shape.\n * This allows dynamically deriving omit keys from existing schema definitions.\n */\nconst createOmitKeys = <T extends z.ZodRawShape>(shape: T): { [K in keyof T]: true } =>\n Object.fromEntries(Object.keys(shape).map(k => [k, true])) as { [K in keyof T]: true };\n\n// ============================================================================\n// Primitive Field Definitions\n// ============================================================================\n\n/** Zod schema for trace ID field */\nexport const traceIdField = z.string().describe('Unique trace identifier');\n\n/** Zod schema for span ID field */\nexport const spanIdField = z.string().describe('Unique span identifier within a trace');\n\nconst spanNameField = z.string().describe('Human-readable span name');\nconst parentSpanIdField = z.string().describe('Parent span reference (null = root span)');\nconst spanTypeField = z.nativeEnum(SpanType).describe('Span type (e.g., WORKFLOW_RUN, AGENT_RUN, TOOL_CALL, etc.)');\nconst attributesField = z.record(z.unknown()).describe('Span-type specific attributes (e.g., model, tokens, tools)');\nconst metadataField = z.record(z.unknown()).describe('User-defined metadata for custom filtering');\nconst tagsField = z.array(z.string()).describe('Labels for filtering traces (only on the root span)');\nconst scopeField = z\n .record(z.unknown())\n .describe('Arbitrary package/app version info (e.g., {\"core\": \"1.0.0\", \"memory\": \"1.0.0\", \"gitSha\": \"abcd1234\"})');\nconst linksField = z.array(z.unknown()).describe('References to related spans in other traces');\nconst inputField = z.unknown().describe('Input data passed to the span');\nconst outputField = z.unknown().describe('Output data returned from the span');\nconst errorField = z.unknown().describe('Error info - presence indicates failure (status derived from this)');\nconst isEventField = z.boolean().describe('Whether this is an event (point-in-time) vs a span (duration)');\nconst startedAtField = z.date().describe('When the span started');\nconst endedAtField = z.date().describe('When the span ended (null = running, status derived from this)');\n\n/** Status of a trace derived from the root span's state */\nexport enum TraceStatus {\n SUCCESS = 'success',\n ERROR = 'error',\n RUNNING = 'running',\n}\n\nconst traceStatusField = z.nativeEnum(TraceStatus).describe('Current status of the trace');\n\nconst hasChildErrorField = z\n .preprocess(v => {\n // Handle string \"true\"/\"false\" from query params correctly\n // z.coerce.boolean() would convert \"false\" to true (Boolean(\"false\") === true)\n if (v === 'true') return true;\n if (v === 'false') return false;\n return v;\n }, z.boolean())\n .describe('True if any span in the trace encountered an error');\n\n// ============================================================================\n// Shared Fields (used by both spanRecordSchema and tracesFilterSchema)\n// ============================================================================\n\n/**\n * All optional fields shared between span records and trace filters.\n * Note: When filtering traces, these fields are matched against the root span.\n */\nconst sharedFields = {\n // Entity identification - first-class fields for filtering (e.g., agent, workflow, tool)\n entityType: entityTypeField.nullish(),\n entityId: entityIdField.nullish(),\n entityName: entityNameField.nullish(),\n\n // Identity & tenancy - for multi-tenant applications\n userId: userIdField.nullish(),\n organizationId: organizationIdField.nullish(),\n resourceId: resourceIdField.nullish(),\n\n // Correlation IDs - for linking related operations\n runId: runIdField.nullish(),\n sessionId: sessionIdField.nullish(),\n threadId: threadIdField.nullish(),\n requestId: requestIdField.nullish(),\n\n // Deployment context - these fields only exist on the root span\n environment: environmentField.nullish(),\n source: sourceField.nullish(),\n serviceName: serviceNameField.nullish(),\n scope: scopeField.nullish(),\n\n // Filterable data - user-defined metadata and tags (tags only on root span)\n metadata: metadataField.nullish(),\n tags: tagsField.nullish(),\n} as const;\n\n// ============================================================================\n// Span Record Schema (for storage)\n// ============================================================================\n\n/** Shape containing trace and span identifier fields */\nexport const spanIds = {\n traceId: traceIdField,\n spanId: spanIdField,\n} as const satisfies z.ZodRawShape;\n\n/** Schema for span identifiers (traceId and spanId) */\nexport const spanIdsSchema = z.object({\n ...spanIds,\n});\n\n/** Span identifier pair (traceId and spanId) */\nexport type SpanIds = z.infer<typeof spanIdsSchema>;\n\n// Omit key objects derived from schema shapes for use with .omit()\nconst omitDbTimestamps = createOmitKeys(dbTimestamps);\nconst omitSpanIds = createOmitKeys(spanIds);\n\n/** Schema for a complete span record as stored in the database */\nexport const spanRecordSchema = z\n .object({\n // Required identifiers\n ...spanIds,\n name: spanNameField,\n spanType: spanTypeField,\n isEvent: isEventField,\n startedAt: startedAtField,\n\n // Shared fields\n parentSpanId: parentSpanIdField.nullish(),\n ...sharedFields,\n\n // Additional span-specific nullish fields\n attributes: attributesField.nullish(),\n links: linksField.nullish(),\n input: inputField.nullish(),\n output: outputField.nullish(),\n error: errorField.nullish(),\n endedAt: endedAtField.nullish(),\n\n // Database timestamps\n ...dbTimestamps,\n })\n .describe('Span record data');\n\n/** Complete span record as stored in the database */\nexport type SpanRecord = z.infer<typeof spanRecordSchema>;\n\n// ============================================================================\n// Trace Span Schema (SpanRecord + computed status for list responses)\n// ============================================================================\n\n/**\n * Computes the trace status from a root span's error and endedAt fields.\n * - ERROR: if error is present (regardless of endedAt)\n * - RUNNING: if endedAt is null/undefined and no error\n * - SUCCESS: if endedAt is present and no error\n */\nexport function computeTraceStatus(span: SpanRecord): TraceStatus {\n if (span.error != null) return TraceStatus.ERROR;\n if (span.endedAt == null) return TraceStatus.RUNNING;\n return TraceStatus.SUCCESS;\n}\n\n/** Schema for a trace span (root span with computed status) */\nexport const traceSpanSchema = spanRecordSchema\n .extend({\n status: traceStatusField,\n })\n .describe('Trace span with computed status (root spans only)');\n\n/** Trace span (root span with computed status) */\nexport type TraceSpan = z.infer<typeof traceSpanSchema>;\n\n/**\n * Converts a SpanRecord to a TraceSpan by adding computed status.\n * Used when returning root spans from listTraces.\n */\nexport function toTraceSpan(span: SpanRecord): TraceSpan {\n return {\n ...span,\n status: computeTraceStatus(span),\n };\n}\n\n/**\n * Converts an array of SpanRecords to TraceSpans by adding computed status.\n * Used when returning root spans from listTraces.\n */\nexport function toTraceSpans(spans: SpanRecord[]): TraceSpan[] {\n return spans.map(toTraceSpan);\n}\n\n// ============================================================================\n// Storage Operation Schemas\n// ============================================================================\n\n/**\n * Schema for creating a span (without db timestamps)\n */\nexport const createSpanRecordSchema = spanRecordSchema.omit(omitDbTimestamps);\n\n/** Span record for creation (excludes db timestamps) */\nexport type CreateSpanRecord = z.infer<typeof createSpanRecordSchema>;\n\n/**\n * Schema for createSpan operation arguments\n */\nexport const createSpanArgsSchema = z\n .object({\n span: createSpanRecordSchema,\n })\n .describe('Arguments for creating a single span');\n\n/** Arguments for creating a single span */\nexport type CreateSpanArgs = z.infer<typeof createSpanArgsSchema>;\n\n/**\n * Schema for batchCreateSpans operation arguments\n */\nexport const batchCreateSpansArgsSchema = z\n .object({\n records: z.array(createSpanRecordSchema),\n })\n .describe('Arguments for batch creating spans');\n\n/** Arguments for batch creating multiple spans */\nexport type BatchCreateSpansArgs = z.infer<typeof batchCreateSpansArgsSchema>;\n\n/**\n * Schema for getSpan operation arguments\n */\nexport const getSpanArgsSchema = z\n .object({\n traceId: traceIdField.min(1),\n spanId: spanIdField.min(1),\n })\n .describe('Arguments for getting a single span');\n\n/** Arguments for retrieving a single span */\nexport type GetSpanArgs = z.infer<typeof getSpanArgsSchema>;\n\n/**\n * Response schema for getSpan operation\n */\nexport const getSpanResponseSchema = z.object({\n span: spanRecordSchema,\n});\n\n/** Response containing a single span */\nexport type GetSpanResponse = z.infer<typeof getSpanResponseSchema>;\n\n/**\n * Schema for getRootSpan operation arguments\n */\nexport const getRootSpanArgsSchema = z\n .object({\n traceId: traceIdField.min(1),\n })\n .describe('Arguments for getting a root span');\n\n/** Arguments for retrieving a root span */\nexport type GetRootSpanArgs = z.infer<typeof getRootSpanArgsSchema>;\n\n/**\n * Response schema for getRootSpan operation\n */\nexport const getRootSpanResponseSchema = z.object({\n span: spanRecordSchema,\n});\n\n/** Response containing a single root span */\nexport type GetRootSpanResponse = z.infer<typeof getRootSpanResponseSchema>;\n\n/**\n * Schema for getTrace operation arguments\n */\nexport const getTraceArgsSchema = z\n .object({\n traceId: traceIdField.min(1),\n })\n .describe('Arguments for getting a single trace');\n\n/** Arguments for retrieving a single trace */\nexport type GetTraceArgs = z.infer<typeof getTraceArgsSchema>;\n\n/**\n * Response schema for getTrace operation\n */\nexport const getTraceResponseSchema = z.object({\n traceId: traceIdField,\n spans: z.array(spanRecordSchema),\n});\n\n/** Response containing a trace with all its spans */\nexport type GetTraceResponse = z.infer<typeof getTraceResponseSchema>;\n\nexport type TraceRecord = GetTraceResponse;\n\n/** Schema for filtering traces in list queries */\nexport const tracesFilterSchema = z\n .object({\n // Date range filters\n startedAt: dateRangeSchema.optional().describe('Filter by span start time range'),\n endedAt: dateRangeSchema.optional().describe('Filter by span end time range'),\n\n // Span type filter\n spanType: spanTypeField.optional(),\n\n // Shared fields\n ...sharedFields,\n\n // Filter-specific derived status fields\n status: traceStatusField.optional(),\n hasChildError: hasChildErrorField.optional(),\n })\n .describe('Filters for querying traces');\n\n/**\n * Fields available for ordering trace results\n */\nexport const tracesOrderByFieldSchema = z\n .enum(['startedAt', 'endedAt'])\n .describe(\"Field to order by: 'startedAt' | 'endedAt'\");\n\n/**\n * Order by configuration for trace queries\n * Follows the existing StorageOrderBy pattern\n * Defaults to startedAt desc (newest first)\n */\nexport const tracesOrderBySchema = z\n .object({\n field: tracesOrderByFieldSchema.default('startedAt').describe('Field to order by'),\n direction: sortDirectionSchema.default('DESC').describe('Sort direction'),\n })\n .describe('Order by configuration');\n\n/**\n * Arguments for listing traces\n */\nexport const listTracesArgsSchema = z\n .object({\n filters: tracesFilterSchema.optional().describe('Optional filters to apply'),\n pagination: paginationArgsSchema.default({}).describe('Pagination settings'),\n orderBy: tracesOrderBySchema.default({}).describe('Ordering configuration (defaults to startedAt desc)'),\n })\n .describe('Arguments for listing traces');\n\n/** Arguments for listing traces with optional filters, pagination, and ordering */\nexport type ListTracesArgs = z.input<typeof listTracesArgsSchema>;\n\n/** Schema for listTraces operation response */\nexport const listTracesResponseSchema = z.object({\n pagination: paginationInfoSchema,\n spans: z.array(traceSpanSchema),\n});\n\n/** Response containing paginated root spans with computed status */\nexport type ListTracesResponse = z.infer<typeof listTracesResponseSchema>;\n\n/**\n * Schema for updating a span (without db timestamps and span IDs)\n */\nexport const updateSpanRecordSchema = createSpanRecordSchema.omit(omitSpanIds);\n\n/** Partial span data for updates (excludes db timestamps and span IDs) */\nexport type UpdateSpanRecord = z.infer<typeof updateSpanRecordSchema>;\n\n/**\n * Schema for updateSpan operation arguments\n */\nexport const updateSpanArgsSchema = z\n .object({\n spanId: spanIdField,\n traceId: traceIdField,\n updates: updateSpanRecordSchema.partial(),\n })\n .describe('Arguments for updating a single span');\n\n/** Arguments for updating a single span */\nexport type UpdateSpanArgs = z.infer<typeof updateSpanArgsSchema>;\n\n/**\n * Schema for batchUpdateSpans operation arguments\n */\nexport const batchUpdateSpansArgsSchema = z\n .object({\n records: z.array(\n z.object({\n traceId: traceIdField,\n spanId: spanIdField,\n updates: updateSpanRecordSchema.partial(),\n }),\n ),\n })\n .describe('Arguments for batch updating spans');\n\n/** Arguments for batch updating multiple spans */\nexport type BatchUpdateSpansArgs = z.infer<typeof batchUpdateSpansArgsSchema>;\n\n/**\n * Schema for batchDeleteTraces operation arguments\n */\nexport const batchDeleteTracesArgsSchema = z\n .object({\n traceIds: z.array(traceIdField),\n })\n .describe('Arguments for batch deleting traces');\n\n/** Arguments for batch deleting multiple traces */\nexport type BatchDeleteTracesArgs = z.infer<typeof batchDeleteTracesArgsSchema>;\n\n// ============================================================================\n// Scoring related schemas\n// ============================================================================\n\n/** Schema for listScoresBySpan operation response */\nexport const listScoresBySpanResponseSchema = z.object({\n pagination: paginationInfoSchema,\n scores: z.array(scoreRowDataSchema),\n});\n\n/** Schema for scoreTraces operation request */\nexport const scoreTracesRequestSchema = z.object({\n scorerName: z.string().min(1),\n targets: z\n .array(\n z.object({\n traceId: traceIdField,\n spanId: spanIdField.optional(),\n }),\n )\n .min(1),\n});\n\n/** Request to score traces using a specific scorer */\nexport type ScoreTracesRequest = z.infer<typeof scoreTracesRequestSchema>;\n\n/** Schema for scoreTraces operation response */\nexport const scoreTracesResponseSchema = z.object({\n status: z.string(),\n message: z.string(),\n traceCount: z.number(),\n});\n\n/** Response from scoring traces */\nexport type ScoreTracesResponse = z.infer<typeof scoreTracesResponseSchema>;\n","import type { z } from 'zod';\nimport type { AgentExecutionOptionsBase } from '../agent/agent.types';\nimport type { SerializedError } from '../error';\nimport type { ScoringSamplingConfig } from '../evals/types';\nimport type { MastraDBMessage, StorageThreadType, SerializedMemoryConfig } from '../memory/types';\nimport { getZodTypeName } from '../utils/zod-utils';\nimport type { StepResult, WorkflowRunState, WorkflowRunStatus } from '../workflows';\n\nexport type StoragePagination = {\n page: number;\n perPage: number | false;\n};\n\nexport type StorageColumnType = 'text' | 'timestamp' | 'uuid' | 'jsonb' | 'integer' | 'float' | 'bigint' | 'boolean';\n\nexport interface StorageColumn {\n type: StorageColumnType;\n primaryKey?: boolean;\n nullable?: boolean;\n references?: {\n table: string;\n column: string;\n };\n}\nexport interface WorkflowRuns {\n runs: WorkflowRun[];\n total: number;\n}\n\nexport interface StorageWorkflowRun {\n workflow_name: string;\n run_id: string;\n resourceId?: string;\n snapshot: WorkflowRunState | string;\n createdAt: Date;\n updatedAt: Date;\n}\nexport interface WorkflowRun {\n workflowName: string;\n runId: string;\n snapshot: WorkflowRunState | string;\n createdAt: Date;\n updatedAt: Date;\n resourceId?: string;\n}\n\nexport type PaginationInfo = {\n total: number;\n page: number;\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * When `false`, all matching records are returned in a single response.\n */\n perPage: number | false;\n hasMore: boolean;\n};\n\nexport type MastraMessageFormat = 'v1' | 'v2';\n\n/**\n * Common options for listing messages (pagination, filtering, ordering)\n */\ntype StorageListMessagesOptions = {\n include?: {\n id: string;\n threadId?: string;\n withPreviousMessages?: number;\n withNextMessages?: number;\n }[];\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * Defaults to 40 if not specified.\n */\n perPage?: number | false;\n /**\n * Zero-indexed page number for pagination.\n * Defaults to 0 if not specified.\n */\n page?: number;\n filter?: {\n dateRange?: {\n start?: Date;\n end?: Date;\n /**\n * When true, excludes the start date from results (uses > instead of >=).\n * Useful for cursor-based pagination to avoid duplicates.\n * @default false\n */\n startExclusive?: boolean;\n /**\n * When true, excludes the end date from results (uses < instead of <=).\n * Useful for cursor-based pagination to avoid duplicates.\n * @default false\n */\n endExclusive?: boolean;\n };\n };\n orderBy?: StorageOrderBy<'createdAt'>;\n};\n\n/**\n * Input for listing messages by thread ID.\n * The resource ID can be optionally provided to filter messages within the thread.\n */\nexport type StorageListMessagesInput = StorageListMessagesOptions & {\n /**\n * Thread ID(s) to query messages from.\n */\n threadId: string | string[];\n /**\n * Optional resource ID to further filter messages within the thread(s).\n */\n resourceId?: string;\n};\n\nexport type StorageListMessagesOutput = PaginationInfo & {\n messages: MastraDBMessage[];\n};\n\n/**\n * Input for listing messages by resource ID only (across all threads).\n * Used by Observational Memory and LongMemEval for resource-scoped queries.\n */\nexport type StorageListMessagesByResourceIdInput = StorageListMessagesOptions & {\n /**\n * Resource ID to query ALL messages for the resource across all threads.\n */\n resourceId: string;\n};\n\nexport type StorageListWorkflowRunsInput = {\n workflowName?: string;\n fromDate?: Date;\n toDate?: Date;\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * When undefined, returns all workflow runs without pagination.\n * When both perPage and page are provided, pagination is applied.\n */\n perPage?: number | false;\n /**\n * Zero-indexed page number for pagination.\n * When both perPage and page are provided, pagination is applied.\n * When either is undefined, all results are returned.\n */\n page?: number;\n resourceId?: string;\n status?: WorkflowRunStatus;\n};\n\nexport type StorageListThreadsInput = {\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * Defaults to 100 if not specified.\n */\n perPage?: number | false;\n /**\n * Zero-indexed page number for pagination.\n * Defaults to 0 if not specified.\n */\n page?: number;\n orderBy?: StorageOrderBy;\n /**\n * Filter options for querying threads.\n */\n filter?: {\n /**\n * Filter threads by resource ID.\n */\n resourceId?: string;\n /**\n * Filter threads by metadata key-value pairs.\n * All specified key-value pairs must match (AND logic).\n */\n metadata?: Record<string, unknown>;\n };\n};\n\nexport type StorageListThreadsOutput = PaginationInfo & {\n threads: StorageThreadType[];\n};\n\n/**\n * Metadata stored on cloned threads to track their origin\n */\nexport type ThreadCloneMetadata = {\n /** ID of the thread this was cloned from */\n sourceThreadId: string;\n /** Timestamp when the clone was created */\n clonedAt: Date;\n /** ID of the last message included in the clone (if messages were copied) */\n lastMessageId?: string;\n};\n\n/**\n * Input options for cloning a thread\n */\nexport type StorageCloneThreadInput = {\n /** ID of the thread to clone */\n sourceThreadId: string;\n /** ID for the new cloned thread (if not provided, a random UUID will be generated) */\n newThreadId?: string;\n /** Resource ID for the new thread (defaults to source thread's resourceId) */\n resourceId?: string;\n /** Title for the new cloned thread */\n title?: string;\n /** Additional metadata to merge with clone metadata */\n metadata?: Record<string, unknown>;\n /** Options for filtering which messages to include */\n options?: {\n /** Maximum number of messages to copy (from most recent) */\n messageLimit?: number;\n /** Filter messages by date range or specific IDs */\n messageFilter?: {\n /** Only include messages created on or after this date */\n startDate?: Date;\n /** Only include messages created on or before this date */\n endDate?: Date;\n /** Only include messages with these specific IDs */\n messageIds?: string[];\n };\n };\n};\n\n/**\n * Output from cloning a thread\n */\nexport type StorageCloneThreadOutput = {\n /** The newly created cloned thread */\n thread: StorageThreadType;\n /** The messages that were copied to the new thread */\n clonedMessages: MastraDBMessage[];\n};\n\nexport type StorageResourceType = {\n id: string;\n workingMemory?: string;\n metadata?: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n};\n\nexport type StorageMessageType = {\n id: string;\n thread_id: string;\n content: string;\n role: string;\n type: string;\n createdAt: Date;\n resourceId: string | null;\n};\n\nexport interface StorageOrderBy<TField extends ThreadOrderBy = ThreadOrderBy> {\n field?: TField;\n direction?: ThreadSortDirection;\n}\n\nexport interface ThreadSortOptions {\n orderBy?: ThreadOrderBy;\n sortDirection?: ThreadSortDirection;\n}\n\nexport type ThreadOrderBy = 'createdAt' | 'updatedAt';\n\nexport type ThreadSortDirection = 'ASC' | 'DESC';\n\n// Agent Storage Types\n\n/**\n * Scorer reference with optional sampling configuration\n */\nexport interface StorageScorerConfig {\n /** Sampling configuration for this scorer */\n sampling?: ScoringSamplingConfig;\n}\n\n/**\n * Model configuration stored in agent snapshots.\n */\nexport interface StorageModelConfig {\n /** Model provider (e.g., 'openai', 'anthropic') */\n provider: string;\n /** Model name (e.g., 'gpt-4o', 'claude-3-opus') */\n name: string;\n /** Temperature for generation */\n temperature?: number;\n /** Top-p sampling parameter */\n topP?: number;\n /** Frequency penalty */\n frequencyPenalty?: number;\n /** Presence penalty */\n presencePenalty?: number;\n /** Maximum completion tokens */\n maxCompletionTokens?: number;\n /** Additional provider-specific options */\n [key: string]: unknown;\n}\n\n/**\n * Default options stored in agent snapshots.\n * Based on AgentExecutionOptionsBase but omitting non-serializable properties.\n *\n * Non-serializable properties that are omitted:\n * - Callbacks (onStepFinish, onFinish, onChunk, onError, onAbort, prepareStep)\n * - Runtime objects (requestContext, abortSignal, tracingContext)\n * - Functions and processor instances (inputProcessors, outputProcessors, clientTools, scorers)\n * - Tools/toolsets (contain functions, stored separately as references)\n * - Complex types (context, memory, instructions, system, stopWhen)\n */\nexport type StorageDefaultOptions = Omit<\n AgentExecutionOptionsBase<any>,\n // Callback functions\n | 'onStepFinish'\n | 'onFinish'\n | 'onChunk'\n | 'onError'\n | 'onAbort'\n | 'prepareStep'\n // Runtime objects\n | 'abortSignal'\n | 'requestContext'\n | 'tracingContext'\n // Functions and processor instances\n | 'inputProcessors'\n | 'outputProcessors'\n | 'clientTools'\n | 'scorers'\n | 'toolsets'\n // Complex types\n | 'context' // ModelMessage includes complex content types (images, files)\n | 'memory' // AgentMemoryOption might contain runtime memory instances\n | 'instructions' // SystemMessage can be arrays or complex message objects\n | 'system' // SystemMessage can be arrays or complex message objects\n | 'stopWhen' // StopCondition is a complex union type from AI SDK\n | 'providerOptions' // ProviderOptions includes provider-specific types from external packages\n>;\n\n/**\n * Agent version snapshot type containing ALL agent configuration fields.\n * These fields live exclusively in version snapshot rows, not on the agent record.\n */\nexport interface StorageAgentSnapshotType {\n /** Display name of the agent */\n name: string;\n /** Purpose description */\n description?: string;\n /** System instructions/prompt */\n instructions: string;\n /** Model configuration (provider, name, etc.) */\n model: StorageModelConfig;\n /** Array of tool keys to resolve from Mastra's tool registry */\n tools?: string[];\n /** Default options for generate/stream calls */\n defaultOptions?: StorageDefaultOptions;\n /** Array of workflow keys to resolve from Mastra's workflow registry */\n workflows?: string[];\n /** Array of agent keys to resolve from Mastra's agent registry */\n agents?: string[];\n /**\n * Array of specific integration tool IDs selected for this agent.\n * Format: \"provider_toolkitSlug_toolSlug\" (e.g., \"composio_hackernews_HACKERNEWS_GET_FRONTPAGE\")\n */\n integrationTools?: string[];\n /** Array of processor keys to resolve from Mastra's processor registry */\n inputProcessors?: string[];\n /** Array of processor keys to resolve from Mastra's processor registry */\n outputProcessors?: string[];\n /** Memory configuration object */\n memory?: SerializedMemoryConfig;\n /** Scorer keys with optional sampling config, to resolve from Mastra's scorer registry */\n scorers?: Record<string, StorageScorerConfig>;\n}\n\n/**\n * Thin agent record type containing only metadata fields.\n * All configuration lives in version snapshots (StorageAgentSnapshotType).\n */\nexport interface StorageAgentType {\n /** Unique, immutable identifier */\n id: string;\n /** Agent status: 'draft' on creation, 'published' when a version is activated */\n status: string;\n /** FK to agent_versions.id - the currently active version */\n activeVersionId?: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata for the agent */\n metadata?: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/**\n * Resolved agent type that combines the thin agent record with version snapshot config.\n * Returned by getAgentByIdResolved and listAgentsResolved.\n */\nexport type StorageResolvedAgentType = StorageAgentType & StorageAgentSnapshotType;\n\n/**\n * Input for creating a new agent. Flat union of thin record fields\n * and initial configuration (used to create version 1).\n */\nexport type StorageCreateAgentInput = {\n /** Unique identifier for the agent */\n id: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata for the agent */\n metadata?: Record<string, unknown>;\n} & StorageAgentSnapshotType;\n\n/**\n * Input for updating an agent. Includes metadata-level fields and optional config fields.\n * The handler layer separates these into agent-record updates vs new-version creation.\n */\nexport type StorageUpdateAgentInput = {\n id: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata for the agent */\n metadata?: Record<string, unknown>;\n /** FK to agent_versions.id - the currently active version */\n activeVersionId?: string;\n /** Agent status: 'draft' or 'published' */\n status?: string;\n} & Partial<StorageAgentSnapshotType>;\n\nexport type StorageListAgentsInput = {\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * Defaults to 100 if not specified.\n */\n perPage?: number | false;\n /**\n * Zero-indexed page number for pagination.\n * Defaults to 0 if not specified.\n */\n page?: number;\n orderBy?: StorageOrderBy;\n /**\n * Filter agents by author identifier (indexed for fast lookups).\n * Only agents with matching authorId will be returned.\n */\n authorId?: string;\n /**\n * Filter agents by metadata key-value pairs.\n * All specified key-value pairs must match (AND logic).\n */\n metadata?: Record<string, unknown>;\n};\n\nexport type StorageListAgentsOutput = PaginationInfo & {\n agents: StorageAgentType[];\n};\n\nexport type StorageListAgentsResolvedOutput = PaginationInfo & {\n agents: StorageResolvedAgentType[];\n};\n\n// Basic Index Management Types\nexport interface CreateIndexOptions {\n name: string;\n table: string;\n columns: string[];\n unique?: boolean;\n concurrent?: boolean;\n /**\n * SQL WHERE clause for creating partial indexes.\n * @internal Reserved for internal use only. Callers must pre-validate this value.\n * DDL statements cannot use parameterized queries for WHERE clauses, so this value\n * is concatenated directly into the SQL. Any user-facing usage must validate input.\n */\n where?: string;\n method?: 'btree' | 'hash' | 'gin' | 'gist' | 'spgist' | 'brin';\n opclass?: string; // Operator class for GIN/GIST indexes\n storage?: Record<string, any>; // Storage parameters\n tablespace?: string; // Tablespace name\n}\n\nexport interface IndexInfo {\n name: string;\n table: string;\n columns: string[];\n unique: boolean;\n size: string;\n definition: string;\n}\n\nexport interface StorageIndexStats extends IndexInfo {\n scans: number; // Number of index scans\n tuples_read: number; // Number of tuples read\n tuples_fetched: number; // Number of tuples fetched\n last_used?: Date; // Last time index was used\n method?: string; // Index method (btree, hash, etc)\n}\n\n// ============================================\n// Observational Memory Types\n// ============================================\n\n/**\n * Scope of observational memory\n */\nexport type ObservationalMemoryScope = 'thread' | 'resource';\n\n/**\n * How the observational memory record was created\n */\nexport type ObservationalMemoryOriginType = 'initial' | 'reflection';\n\n/**\n * Core database record for observational memory\n *\n * For resource scope: One active record per resource, containing observations from ALL threads.\n * For thread scope: One record per thread.\n *\n * Derived values (not stored, computed at runtime):\n * - reflectionCount: count records with originType: 'reflection'\n * - lastReflectionAt: createdAt of most recent reflection record\n * - previousGeneration: record with next-oldest createdAt\n */\nexport interface ObservationalMemoryRecord {\n // Identity\n /** Unique record ID */\n id: string;\n /** Memory scope - thread or resource */\n scope: ObservationalMemoryScope;\n /** Thread ID (null for resource scope) */\n threadId: string | null;\n /** Resource ID (always present) */\n resourceId: string;\n\n // Timestamps (top-level for easy querying)\n /** When this record was created */\n createdAt: Date;\n /** When this record was last updated */\n updatedAt: Date;\n /**\n * Single cursor for message loading - when we last observed ANY thread for this resource.\n * Undefined means no observations have been made yet (all messages are \"unobserved\").\n */\n lastObservedAt?: Date;\n\n // Generation tracking\n /** How this record was created */\n originType: ObservationalMemoryOriginType;\n /** Generation counter - incremented each time a reflection creates a new record */\n generationCount: number;\n\n // Observation content\n /**\n * Currently active observations.\n * For resource scope: Contains <thread id=\"...\">...</thread> sections for attribution.\n * For thread scope: Plain observation text.\n */\n activeObservations: string;\n /** Observations waiting to be activated (async buffering) */\n bufferedObservations?: string;\n /** Reflection waiting to be swapped in (async buffering) */\n bufferedReflection?: string;\n\n /**\n * Message IDs observed in the current generation.\n * Used as a safeguard against re-observation if timestamp filtering fails.\n * Reset on reflection (new generation starts fresh).\n */\n observedMessageIds?: string[];\n\n /**\n * The timezone used when formatting dates for the Observer agent.\n * Stored for debugging and auditing observation dates.\n * Example: \"America/Los_Angeles\", \"Europe/London\"\n */\n observedTimezone?: string;\n\n // Token tracking\n /** Running total of all tokens observed */\n totalTokensObserved: number;\n /** Current size of active observations */\n observationTokenCount: number;\n /** Accumulated tokens from pending (unobserved) messages across sessions */\n pendingMessageTokens: number;\n\n // State flags\n /** Is a reflection currently in progress? */\n isReflecting: boolean;\n /** Is observation currently in progress? */\n isObserving: boolean;\n\n // Configuration\n /** Current configuration (stored as JSON) */\n config: Record<string, unknown>;\n\n // Extensible metadata (app-specific, optional)\n /** Optional metadata for app-specific extensions */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Input for creating a new observational memory record\n */\nexport interface CreateObservationalMemoryInput {\n threadId: string | null;\n resourceId: string;\n scope: ObservationalMemoryScope;\n config: Record<string, unknown>;\n /** The timezone used when formatting dates for the Observer agent (e.g., \"America/Los_Angeles\") */\n observedTimezone?: string;\n}\n\n/**\n * Input for updating active observations.\n * Uses cursor-based message tracking via lastObservedAt instead of message IDs.\n */\nexport interface UpdateActiveObservationsInput {\n id: string;\n observations: string;\n tokenCount: number;\n /** Timestamp when these observations were created (for cursor-based message loading) */\n lastObservedAt: Date;\n /**\n * IDs of messages that were observed in this cycle.\n * Stored in record metadata as a safeguard against re-observation on process restart.\n * These are appended to any existing IDs and pruned to only include IDs newer than lastObservedAt.\n */\n observedMessageIds?: string[];\n /**\n * The timezone used when formatting dates for the Observer agent.\n * Captured from Intl.DateTimeFormat().resolvedOptions().timeZone\n */\n observedTimezone?: string;\n}\n\n/**\n * Input for updating buffered observations.\n * Note: Async buffering is currently disabled but types are retained for future use.\n */\nexport interface UpdateBufferedObservationsInput {\n id: string;\n observations: string;\n suggestedContinuation?: string;\n}\n\n/**\n * Input for creating a reflection generation (creates a new record, archives the old one)\n */\nexport interface CreateReflectionGenerationInput {\n currentRecord: ObservationalMemoryRecord;\n reflection: string;\n tokenCount: number;\n}\n\n// ============================================\n// Workflow Storage Types\n// ============================================\n\nexport interface UpdateWorkflowStateOptions {\n status: WorkflowRunStatus;\n result?: StepResult<any, any, any, any>;\n error?: SerializedError;\n suspendedPaths?: Record<string, number[]>;\n waitingPaths?: Record<string, number[]>;\n resumeLabels?: Record<string, { stepId: string; foreachIndex?: number }>;\n}\n\n/**\n * Get the inner type from a wrapper schema (nullable, optional, default, effects, branded).\n * Compatible with both Zod 3 and Zod 4.\n */\nfunction getInnerType(schema: z.ZodTypeAny, typeName: string): z.ZodTypeAny | undefined {\n const schemaAny = schema as any;\n\n // For nullable, optional, default - the inner type is at _def.innerType\n if (typeName === 'ZodNullable' || typeName === 'ZodOptional' || typeName === 'ZodDefault') {\n return schemaAny._zod?.def?.innerType ?? schemaAny._def?.innerType;\n }\n\n // For effects - the inner type is at _def.schema\n if (typeName === 'ZodEffects') {\n return schemaAny._zod?.def?.schema ?? schemaAny._def?.schema;\n }\n\n // For branded - the inner type is at _def.type\n if (typeName === 'ZodBranded') {\n return schemaAny._zod?.def?.type ?? schemaAny._def?.type;\n }\n\n return undefined;\n}\n\nfunction unwrapSchema(schema: z.ZodTypeAny): { base: z.ZodTypeAny; nullable: boolean } {\n let current = schema;\n let nullable = false;\n\n while (true) {\n const typeName = getZodTypeName(current);\n\n if (typeName === 'ZodNullable') {\n nullable = true;\n const inner = getInnerType(current, typeName);\n if (inner) {\n current = inner;\n continue;\n }\n }\n\n if (typeName === 'ZodOptional') {\n // For DB purposes, we usually treat \"optional\" as \"nullable\"\n nullable = true;\n const inner = getInnerType(current, typeName);\n if (inner) {\n current = inner;\n continue;\n }\n }\n\n if (typeName === 'ZodDefault') {\n const inner = getInnerType(current, typeName);\n if (inner) {\n current = inner;\n continue;\n }\n }\n\n if (typeName === 'ZodEffects') {\n const inner = getInnerType(current, typeName);\n if (inner) {\n current = inner;\n continue;\n }\n }\n\n if (typeName === 'ZodBranded') {\n const inner = getInnerType(current, typeName);\n if (inner) {\n current = inner;\n continue;\n }\n }\n\n // If you ever use ZodCatch/ZodPipeline, you can unwrap them here too.\n break;\n }\n\n return { base: current, nullable };\n}\n\n/**\n * Extract checks array from Zod schema, compatible with both Zod 3 and Zod 4.\n * Zod 3 uses _def.checks, Zod 4 uses _zod.def.checks.\n */\nfunction getZodChecks(schema: z.ZodTypeAny): Array<{ kind: string }> {\n const schemaAny = schema as any;\n // Zod 4 structure\n if (schemaAny._zod?.def?.checks) {\n return schemaAny._zod.def.checks;\n }\n // Zod 3 structure\n if (schemaAny._def?.checks) {\n return schemaAny._def.checks;\n }\n return [];\n}\n\nfunction zodToStorageType(schema: z.ZodTypeAny): StorageColumnType {\n const typeName = getZodTypeName(schema);\n\n if (typeName === 'ZodString') {\n // Check for UUID validation\n const checks = getZodChecks(schema);\n if (checks.some(c => c.kind === 'uuid')) {\n return 'uuid';\n }\n return 'text';\n }\n if (typeName === 'ZodNativeEnum' || typeName === 'ZodEnum') {\n return 'text';\n }\n if (typeName === 'ZodNumber') {\n // Check for integer validation\n const checks = getZodChecks(schema);\n return checks.some(c => c.kind === 'int') ? 'integer' : 'float';\n }\n if (typeName === 'ZodBigInt') {\n return 'bigint';\n }\n if (typeName === 'ZodDate') {\n return 'timestamp';\n }\n if (typeName === 'ZodBoolean') {\n return 'boolean';\n }\n // fall back for objects/records/unknown\n return 'jsonb';\n}\n\n/**\n * Converts a zod schema into a database schema\n * @param zObject A zod schema object\n * @returns database schema record with StorageColumns\n */\nexport function buildStorageSchema<Shape extends z.ZodRawShape>(\n zObject: z.ZodObject<Shape>,\n): Record<keyof Shape & string, StorageColumn> {\n const shape = zObject.shape;\n const result: Record<string, StorageColumn> = {};\n\n for (const [key, field] of Object.entries(shape)) {\n const { base, nullable } = unwrapSchema(field as z.ZodTypeAny);\n result[key] = {\n type: zodToStorageType(base),\n nullable,\n };\n }\n\n return result as Record<keyof Shape & string, StorageColumn>;\n}\n","import { spanRecordSchema } from './domains/observability/types';\nimport { buildStorageSchema } from './types';\nimport type { StorageColumn } from './types';\n\nexport const TABLE_WORKFLOW_SNAPSHOT = 'mastra_workflow_snapshot';\nexport const TABLE_MESSAGES = 'mastra_messages';\nexport const TABLE_THREADS = 'mastra_threads';\nexport const TABLE_TRACES = 'mastra_traces';\nexport const TABLE_RESOURCES = 'mastra_resources';\nexport const TABLE_SCORERS = 'mastra_scorers';\nexport const TABLE_SPANS = 'mastra_ai_spans';\nexport const TABLE_AGENTS = 'mastra_agents';\nexport const TABLE_AGENT_VERSIONS = 'mastra_agent_versions';\nexport const TABLE_OBSERVATIONAL_MEMORY = 'mastra_observational_memory';\n\nexport type TABLE_NAMES =\n | typeof TABLE_WORKFLOW_SNAPSHOT\n | typeof TABLE_MESSAGES\n | typeof TABLE_THREADS\n | typeof TABLE_TRACES\n | typeof TABLE_RESOURCES\n | typeof TABLE_SCORERS\n | typeof TABLE_SPANS\n | typeof TABLE_AGENTS\n | typeof TABLE_AGENT_VERSIONS;\n\nexport const SCORERS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n scorerId: { type: 'text' },\n traceId: { type: 'text', nullable: true },\n spanId: { type: 'text', nullable: true },\n runId: { type: 'text' },\n scorer: { type: 'jsonb' },\n preprocessStepResult: { type: 'jsonb', nullable: true },\n extractStepResult: { type: 'jsonb', nullable: true },\n analyzeStepResult: { type: 'jsonb', nullable: true },\n score: { type: 'float' },\n reason: { type: 'text', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n preprocessPrompt: { type: 'text', nullable: true },\n extractPrompt: { type: 'text', nullable: true },\n generateScorePrompt: { type: 'text', nullable: true },\n generateReasonPrompt: { type: 'text', nullable: true },\n analyzePrompt: { type: 'text', nullable: true },\n\n // Deprecated\n reasonPrompt: { type: 'text', nullable: true },\n input: { type: 'jsonb' },\n output: { type: 'jsonb' }, // MESSAGE OUTPUT\n additionalContext: { type: 'jsonb', nullable: true }, // DATA FROM THE CONTEXT PARAM ON AN AGENT\n requestContext: { type: 'jsonb', nullable: true }, // THE EVALUATE Request Context FOR THE RUN\n /**\n * Things you can evaluate\n */\n entityType: { type: 'text', nullable: true }, // WORKFLOW, AGENT, TOOL, STEP, NETWORK\n entity: { type: 'jsonb', nullable: true }, // MINIMAL JSON DATA ABOUT WORKFLOW, AGENT, TOOL, STEP, NETWORK\n entityId: { type: 'text', nullable: true },\n source: { type: 'text' },\n resourceId: { type: 'text', nullable: true },\n threadId: { type: 'text', nullable: true },\n createdAt: { type: 'timestamp' },\n updatedAt: { type: 'timestamp' },\n};\n\nexport const SPAN_SCHEMA = buildStorageSchema(spanRecordSchema);\n\n/**\n * @deprecated Use SPAN_SCHEMA instead. This legacy schema is retained only for migration purposes.\n * @internal\n */\nexport const OLD_SPAN_SCHEMA: Record<string, StorageColumn> = {\n // Composite primary key of traceId and spanId\n traceId: { type: 'text', nullable: false },\n spanId: { type: 'text', nullable: false },\n parentSpanId: { type: 'text', nullable: true },\n name: { type: 'text', nullable: false },\n scope: { type: 'jsonb', nullable: true }, // Mastra package info {\"core-version\": \"0.1.0\"}\n spanType: { type: 'text', nullable: false }, // WORKFLOW_RUN, WORKFLOW_STEP, AGENT_RUN, AGENT_STEP, TOOL_RUN, TOOL_STEP, etc.\n attributes: { type: 'jsonb', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n links: { type: 'jsonb', nullable: true },\n input: { type: 'jsonb', nullable: true },\n output: { type: 'jsonb', nullable: true },\n error: { type: 'jsonb', nullable: true },\n startedAt: { type: 'timestamp', nullable: false }, // When the span started\n endedAt: { type: 'timestamp', nullable: true }, // When the span ended\n createdAt: { type: 'timestamp', nullable: false }, // The time the database record was created\n updatedAt: { type: 'timestamp', nullable: true }, // The time the database record was last updated\n isEvent: { type: 'boolean', nullable: false },\n};\n\nexport const AGENTS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n status: { type: 'text', nullable: false }, // 'draft' or 'published'\n activeVersionId: { type: 'text', nullable: true }, // FK to agent_versions.id\n authorId: { type: 'text', nullable: true }, // Author identifier for multi-tenant filtering\n metadata: { type: 'jsonb', nullable: true }, // Additional metadata for the agent\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const AGENT_VERSIONS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true }, // UUID\n agentId: { type: 'text', nullable: false },\n versionNumber: { type: 'integer', nullable: false },\n // Agent config fields\n name: { type: 'text', nullable: false }, // Agent display name\n description: { type: 'text', nullable: true },\n instructions: { type: 'text', nullable: false },\n model: { type: 'jsonb', nullable: false },\n tools: { type: 'jsonb', nullable: true },\n defaultOptions: { type: 'jsonb', nullable: true },\n workflows: { type: 'jsonb', nullable: true },\n agents: { type: 'jsonb', nullable: true },\n integrationTools: { type: 'jsonb', nullable: true },\n inputProcessors: { type: 'jsonb', nullable: true },\n outputProcessors: { type: 'jsonb', nullable: true },\n memory: { type: 'jsonb', nullable: true },\n scorers: { type: 'jsonb', nullable: true },\n // Version metadata\n changedFields: { type: 'jsonb', nullable: true }, // Array of field names\n changeMessage: { type: 'text', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n};\n\nexport const OBSERVATIONAL_MEMORY_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n lookupKey: { type: 'text', nullable: false }, // 'resource:{resourceId}' or 'thread:{threadId}'\n scope: { type: 'text', nullable: false }, // 'resource' or 'thread'\n resourceId: { type: 'text', nullable: true },\n threadId: { type: 'text', nullable: true },\n activeObservations: { type: 'text', nullable: false }, // JSON array of observations\n activeObservationsPendingUpdate: { type: 'text', nullable: true }, // JSON array, used during updates\n originType: { type: 'text', nullable: false }, // 'initialization', 'observation', or 'reflection'\n config: { type: 'text', nullable: false }, // JSON object\n generationCount: { type: 'integer', nullable: false },\n lastObservedAt: { type: 'timestamp', nullable: true },\n lastReflectionAt: { type: 'timestamp', nullable: true },\n pendingMessageTokens: { type: 'integer', nullable: false }, // Token count\n totalTokensObserved: { type: 'integer', nullable: false }, // Running total of all observed tokens\n observationTokenCount: { type: 'integer', nullable: false }, // Current observation size in tokens\n isObserving: { type: 'boolean', nullable: false },\n isReflecting: { type: 'boolean', nullable: false },\n observedMessageIds: { type: 'jsonb', nullable: true }, // JSON array of message IDs already observed\n observedTimezone: { type: 'text', nullable: true }, // Timezone used for Observer date formatting (e.g., \"America/Los_Angeles\")\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\n/**\n * Schema definitions for all core tables.\n */\nexport const TABLE_SCHEMAS: Record<TABLE_NAMES, Record<string, StorageColumn>> = {\n [TABLE_WORKFLOW_SNAPSHOT]: {\n workflow_name: {\n type: 'text',\n },\n run_id: {\n type: 'text',\n },\n resourceId: { type: 'text', nullable: true },\n snapshot: {\n type: 'jsonb',\n },\n createdAt: {\n type: 'timestamp',\n },\n updatedAt: {\n type: 'timestamp',\n },\n },\n [TABLE_SCORERS]: SCORERS_SCHEMA,\n [TABLE_THREADS]: {\n id: { type: 'text', nullable: false, primaryKey: true },\n resourceId: { type: 'text', nullable: false },\n title: { type: 'text', nullable: false },\n metadata: { type: 'jsonb', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n },\n [TABLE_MESSAGES]: {\n id: { type: 'text', nullable: false, primaryKey: true },\n thread_id: { type: 'text', nullable: false },\n content: { type: 'text', nullable: false },\n role: { type: 'text', nullable: false },\n type: { type: 'text', nullable: false },\n createdAt: { type: 'timestamp', nullable: false },\n resourceId: { type: 'text', nullable: true },\n },\n [TABLE_SPANS]: SPAN_SCHEMA,\n [TABLE_TRACES]: {\n id: { type: 'text', nullable: false, primaryKey: true },\n parentSpanId: { type: 'text', nullable: true },\n name: { type: 'text', nullable: false },\n traceId: { type: 'text', nullable: false },\n scope: { type: 'text', nullable: false },\n kind: { type: 'integer', nullable: false },\n attributes: { type: 'jsonb', nullable: true },\n status: { type: 'jsonb', nullable: true },\n events: { type: 'jsonb', nullable: true },\n links: { type: 'jsonb', nullable: true },\n other: { type: 'text', nullable: true },\n startTime: { type: 'bigint', nullable: false },\n endTime: { type: 'bigint', nullable: false },\n createdAt: { type: 'timestamp', nullable: false },\n },\n [TABLE_RESOURCES]: {\n id: { type: 'text', nullable: false, primaryKey: true },\n workingMemory: { type: 'text', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n },\n [TABLE_AGENTS]: AGENTS_SCHEMA,\n [TABLE_AGENT_VERSIONS]: AGENT_VERSIONS_SCHEMA,\n};\n\n/**\n * Schema for the observational memory table.\n * Exported separately as OM is optional and not part of TABLE_NAMES.\n */\nexport const OBSERVATIONAL_MEMORY_TABLE_SCHEMA = {\n [TABLE_OBSERVATIONAL_MEMORY]: OBSERVATIONAL_MEMORY_SCHEMA,\n};\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/mastra/hooks.ts","../src/evals/run/scorerAccumulator.ts","../src/evals/run/index.ts"],"names":["pMap"],"mappings":";;;;;AAOO,SAAS,mBAAmB,MAAA,EAAgB;AACjD,EAAA,OAAO,OAAO,QAAA,KAA+B;AAC3C,IAAA,MAAM,OAAA,GAAU,OAAO,UAAA,EAAW;AAElC,IAAA,IAAI,CAAC,OAAA,EAAS;AACZ,MAAA,MAAA,CAAO,SAAA,EA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K,WAAA;AAAA,IACvC;AAEA,IAAA,MAAM,OAAA,GAAU;AAAA,MACd,GAAG,WAAA;AAAA,MACH,QAAA;AAAA,MACA,QAAA;AAAA,MACA,UAAA;AAAA,MACA,MAAA,EAAQ,MAAA;AAAA,MACR,MAAA,EAAQ;AAAA,QACN,EAAA,EAAI,QAAQ,EAAA,IAAM,QAAA;AAAA,QAClB,IAAA,EAAM,QAAQ,IAAA,IAAQ,QAAA;AAAA,QACtB,WAAA,EAAa,QAAQ,WAAA,IAAe,EAAA;AAAA,QACpC,IAAA,EAAM,QAAQ,IAAA,IAAQ;AAAA,OACxB;AAAA,MACA,MAAA,EAAQ;AAAA,QACN,IAAI,MAAA,CAAO,EAAA;AAAA,QACX,IAAA,EAAO,MAAA,CAAe,IAAA,IAAQ,MAAA,CAAO;AAAA,OACvC;AAAA;AAAA,MAEA,cAAA,EAAgB,KAAK,cAAA,GAAiB,MAAA,CAAO,YAAY,IAAA,CAAK,cAAA,CAAe,OAAA,EAAS,CAAA,GAAI,MAAA;AAAA;AAAA,MAE1F,mBAAmB,MAAA,CAAO,IAAA,CAAK,iBAAiB,CAAA,CAAE,MAAA,GAAS,IAAI,iBAAA,GAAoB,MAAA;AAAA;AAAA,MAEnF,OAAA;AAAA,MACA;AAAA,KACF;AAEA,IAAA,MAAM,oBAAA,CAAqB,SAAS,OAAO,CAAA;AAAA,EAC7C,SAAS,KAAA,EAAO;AAEd,IAAA,MAAA,EAAQ,aAAY,EAAG,IAAA,GAAO,CAAA,gCAAA,EAAmC,QAAQ,KAAK,KAAK,CAAA;AAAA,EACrF;AACF","file":"chunk-MSWXEOZC.js","sourcesContent":["import pMap from 'p-map';\nimport { ErrorCategory, ErrorDomain, MastraError } from '../error';\nimport { saveScorePayloadSchema } from '../evals';\nimport type { ScoringHookInput } from '../evals/types';\nimport type { Mastra } from '../mastra';\nimport type { MastraStorage } from '../storage';\n\nexport function createOnScorerHook(mastra: Mastra) {\n return async (hookData: ScoringHookInput) => {\n const storage = mastra.getStorage();\n\n if (!storage) {\n mastra.getLogger()?.warn('Storage not found, skipping score validation and saving');\n return;\n }\n\n const entityId = hookData.entity.id as string;\n const entityType = hookData.entityType;\n const scorer = hookData.scorer;\n const scorerId = scorer.id as string;\n\n if (!scorerId) {\n mastra.getLogger()?.warn('Scorer ID not found, skipping score validation and saving');\n return;\n }\n\n try {\n const scorerToUse = await findScorer(mastra, entityId, entityType, scorerId);\n\n if (!scorerToUse) {\n throw new MastraError({\n id: 'MASTRA_SCORER_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Scorer with ID ${scorerId} not found`,\n });\n }\n\n let input = hookData.input;\n let output = hookData.output;\n\n const { structuredOutput, ...rest } = hookData;\n\n const runResult = await scorerToUse.scorer.run({\n ...rest,\n input,\n output,\n });\n\n let spanId;\n let traceId;\n const currentSpan = hookData.tracingContext?.currentSpan;\n if (currentSpan && currentSpan.isValid) {\n spanId = currentSpan.id;\n traceId = currentSpan.traceId;\n }\n\n const payload = {\n ...rest,\n ...runResult,\n entityId,\n scorerId: scorerId,\n spanId,\n traceId,\n metadata: {\n structuredOutput: !!structuredOutput,\n },\n };\n await validateAndSaveScore(storage, payload);\n\n if (currentSpan && spanId && traceId) {\n await pMap(\n currentSpan.observabilityInstance.getExporters(),\n async exporter => {\n if (exporter.addScoreToTrace) {\n try {\n await exporter.addScoreToTrace({\n traceId: traceId,\n spanId: spanId,\n score: runResult.score as number,\n reason: runResult.reason as string,\n scorerName: scorerToUse.scorer.id,\n metadata: {\n ...(currentSpan.metadata ?? {}),\n },\n });\n } catch (error) {\n // Log error but don't fail the hook if exporter fails\n mastra.getLogger()?.error(`Failed to add score to trace via exporter: ${error}`);\n }\n }\n },\n { concurrency: 3 },\n );\n }\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MASTRA_SCORER_FAILED_TO_RUN_HOOK',\n domain: ErrorDomain.SCORER,\n category: ErrorCategory.USER,\n details: {\n scorerId,\n entityId,\n entityType,\n },\n },\n error,\n );\n\n mastra.getLogger()?.trackException(mastraError);\n mastra.getLogger()?.error(mastraError.toString());\n }\n };\n}\n\nexport async function validateAndSaveScore(storage: MastraStorage, payload: unknown) {\n const scoresStore = await storage.getStore('scores');\n if (!scoresStore) {\n throw new MastraError({\n id: 'MASTRA_SCORES_STORAGE_NOT_AVAILABLE',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n text: 'Scores storage domain is not available',\n });\n }\n const payloadToSave = saveScorePayloadSchema.parse(payload);\n await scoresStore.saveScore(payloadToSave);\n}\n\nasync function findScorer(mastra: Mastra, entityId: string, entityType: string, scorerId: string) {\n let scorerToUse;\n if (entityType === 'AGENT') {\n // Try code-defined agents first\n try {\n const agent = mastra.getAgentById(entityId);\n const scorers = await agent.listScorers();\n for (const [_, scorer] of Object.entries(scorers)) {\n if (scorer.scorer.id === scorerId) {\n scorerToUse = scorer;\n break;\n }\n }\n } catch {\n // Agent not found in code-defined agents, try stored agents via editor\n try {\n const storedAgent = (await mastra.getEditor()?.getStoredAgentById(entityId)) ?? null;\n if (storedAgent) {\n const scorers = await storedAgent.listScorers();\n for (const [_, scorer] of Object.entries(scorers) as [string, any][]) {\n if (scorer.scorer.id === scorerId) {\n scorerToUse = scorer;\n break;\n }\n }\n }\n } catch {\n // Stored agent also not found, will fall back to mastra-registered scorer\n }\n }\n } else if (entityType === 'WORKFLOW') {\n const scorers = await mastra.getWorkflowById(entityId).listScorers();\n for (const [_, scorer] of Object.entries(scorers)) {\n if (scorer.scorer.id === scorerId) {\n scorerToUse = scorer;\n break;\n }\n }\n }\n\n // Fallback to mastra-registered scorer\n if (!scorerToUse) {\n const mastraRegisteredScorer = mastra.getScorerById(scorerId);\n scorerToUse = mastraRegisteredScorer ? { scorer: mastraRegisteredScorer } : undefined;\n }\n\n return scorerToUse;\n}\n","export class ScoreAccumulator {\n private flatScores: Record<string, number[]> = {};\n private workflowScores: Record<string, number[]> = {};\n private stepScores: Record<string, Record<string, number[]>> = {};\n\n addScores(scorerResults: Record<string, any>) {\n const isTargetWorkflowAndHasStepScores = 'steps' in scorerResults;\n if (isTargetWorkflowAndHasStepScores) {\n this.addNestedScores(scorerResults);\n } else {\n this.addFlatScores(scorerResults);\n }\n }\n\n private addFlatScores(scorerResults: Record<string, any>) {\n for (const [scorerName, result] of Object.entries(scorerResults)) {\n if (!this.flatScores[scorerName]) {\n this.flatScores[scorerName] = [];\n }\n this.flatScores[scorerName].push((result as { score: number }).score);\n }\n }\n\n private addNestedScores(scorerResults: Record<string, any>) {\n if ('workflow' in scorerResults && scorerResults.workflow) {\n for (const [scorerName, result] of Object.entries(scorerResults.workflow)) {\n if (!this.workflowScores[scorerName]) {\n this.workflowScores[scorerName] = [];\n }\n this.workflowScores[scorerName].push((result as { score: number }).score);\n }\n }\n\n if ('steps' in scorerResults && scorerResults.steps) {\n for (const [stepId, stepResults] of Object.entries(scorerResults.steps)) {\n if (!this.stepScores[stepId]) {\n this.stepScores[stepId] = {};\n }\n for (const [scorerName, result] of Object.entries(stepResults as Record<string, any>)) {\n if (!this.stepScores[stepId][scorerName]) {\n this.stepScores[stepId][scorerName] = [];\n }\n this.stepScores[stepId][scorerName].push((result as { score: number }).score);\n }\n }\n }\n }\n\n addStepScores(stepScorerResults: Record<string, Record<string, any>>) {\n for (const [stepId, stepResults] of Object.entries(stepScorerResults)) {\n if (!this.stepScores[stepId]) {\n this.stepScores[stepId] = {};\n }\n for (const [scorerName, result] of Object.entries(stepResults)) {\n if (!this.stepScores[stepId][scorerName]) {\n this.stepScores[stepId][scorerName] = [];\n }\n this.stepScores[stepId][scorerName].push((result as { score: number }).score);\n }\n }\n }\n\n getAverageScores(): Record<string, any> {\n const result: Record<string, any> = {};\n\n for (const [scorerName, scoreArray] of Object.entries(this.flatScores)) {\n result[scorerName] = this.getAverageScore(scoreArray);\n }\n\n // Add workflow scores\n if (Object.keys(this.workflowScores).length > 0) {\n result.workflow = {};\n for (const [scorerName, scoreArray] of Object.entries(this.workflowScores)) {\n result.workflow[scorerName] = this.getAverageScore(scoreArray);\n }\n }\n\n if (Object.keys(this.stepScores).length > 0) {\n result.steps = {};\n for (const [stepId, stepScorers] of Object.entries(this.stepScores)) {\n result.steps[stepId] = {};\n for (const [scorerName, scoreArray] of Object.entries(stepScorers)) {\n result.steps[stepId][scorerName] = this.getAverageScore(scoreArray);\n }\n }\n }\n\n return result;\n }\n\n private getAverageScore(scoreArray: number[]): number {\n if (scoreArray.length > 0) {\n return scoreArray.reduce((a, b) => a + b, 0) / scoreArray.length;\n } else {\n return 0;\n }\n }\n}\n","import type { CoreMessage } from '@internal/ai-sdk-v4';\nimport type { Agent, AiMessageType, UIMessageWithMetadata } from '../../agent';\nimport { isSupportedLanguageModel } from '../../agent';\nimport { MastraError } from '../../error';\nimport { validateAndSaveScore } from '../../mastra/hooks';\nimport type { TracingContext } from '../../observability';\nimport type { RequestContext } from '../../request-context';\nimport { Workflow } from '../../workflows';\nimport type { WorkflowResult, StepResult } from '../../workflows';\nimport type { MastraScorer } from '../base';\nimport { ScoreAccumulator } from './scorerAccumulator';\n\ntype RunEvalsDataItem<TTarget = unknown> = {\n input: TTarget extends Workflow<any, any>\n ? any\n : TTarget extends Agent\n ? string | string[] | CoreMessage[] | AiMessageType[] | UIMessageWithMetadata[]\n : unknown;\n groundTruth?: any;\n requestContext?: RequestContext;\n tracingContext?: TracingContext;\n};\n\ntype WorkflowScorerConfig = {\n workflow?: MastraScorer<any, any, any, any>[];\n steps?: Record<string, MastraScorer<any, any, any, any>[]>;\n};\n\ntype RunEvalsResult = {\n scores: Record<string, any>;\n summary: {\n totalItems: number;\n };\n};\n\n// Agent with scorers array\nexport function runEvals<TAgent extends Agent>(config: {\n data: RunEvalsDataItem<TAgent>[];\n scorers: MastraScorer<any, any, any, any>[];\n target: TAgent;\n onItemComplete?: (params: {\n item: RunEvalsDataItem<TAgent>;\n targetResult: Awaited<ReturnType<Agent['generate']>>;\n scorerResults: Record<string, any>; // Flat structure: { scorerName: result }\n }) => void | Promise<void>;\n concurrency?: number;\n}): Promise<RunEvalsResult>;\n\n// Workflow with scorers array\nexport function runEvals<TWorkflow extends Workflow<any, any, any, any, any, any, any>>(config: {\n data: RunEvalsDataItem<TWorkflow>[];\n scorers: MastraScorer<any, any, any, any>[];\n target: TWorkflow;\n onItemComplete?: (params: {\n item: RunEvalsDataItem<TWorkflow>;\n targetResult: WorkflowResult<any, any, any, any>;\n scorerResults: Record<string, any>; // Flat structure: { scorerName: result }\n }) => void | Promise<void>;\n concurrency?: number;\n}): Promise<RunEvalsResult>;\n\n// Workflow with workflow configuration\nexport function runEvals<TWorkflow extends Workflow<any, any, any, any, any, any, any>>(config: {\n data: RunEvalsDataItem<TWorkflow>[];\n scorers: WorkflowScorerConfig;\n target: TWorkflow;\n onItemComplete?: (params: {\n item: RunEvalsDataItem<TWorkflow>;\n targetResult: WorkflowResult<any, any, any, any>;\n scorerResults: {\n workflow?: Record<string, any>;\n steps?: Record<string, Record<string, any>>;\n };\n }) => void | Promise<void>;\n concurrency?: number;\n}): Promise<RunEvalsResult>;\nexport async function runEvals(config: {\n data: RunEvalsDataItem<any>[];\n scorers: MastraScorer<any, any, any, any>[] | WorkflowScorerConfig;\n target: Agent | Workflow;\n onItemComplete?: (params: {\n item: RunEvalsDataItem<any>;\n targetResult: any;\n scorerResults: any;\n }) => void | Promise<void>;\n concurrency?: number;\n}): Promise<RunEvalsResult> {\n const { data, scorers, target, onItemComplete, concurrency = 1 } = config;\n\n validateEvalsInputs(data, scorers, target);\n\n let totalItems = 0;\n const scoreAccumulator = new ScoreAccumulator();\n\n // Get storage from target's Mastra instance if available\n // Agent uses getMastraInstance(), Workflow uses .mastra getter\n const mastra = (target as any).getMastraInstance?.() || (target as any).mastra;\n const storage = mastra?.getStorage();\n\n const pMap = (await import('p-map')).default;\n await pMap(\n data,\n async (item: RunEvalsDataItem<any>) => {\n const targetResult = await executeTarget(target, item);\n const scorerResults = await runScorers(scorers, targetResult, item);\n scoreAccumulator.addScores(scorerResults);\n\n // Save scores to storage if available\n if (storage) {\n await saveScoresToStorage({\n storage,\n scorerResults,\n target,\n item,\n mastra,\n });\n }\n\n if (onItemComplete) {\n await onItemComplete({\n item,\n targetResult: targetResult as any,\n scorerResults: scorerResults as any,\n });\n }\n\n totalItems++;\n },\n { concurrency },\n );\n\n return {\n scores: scoreAccumulator.getAverageScores(),\n summary: {\n totalItems,\n },\n };\n}\n\nfunction isWorkflow(target: Agent | Workflow): target is Workflow {\n return target instanceof Workflow;\n}\n\nfunction isWorkflowScorerConfig(scorers: any): scorers is WorkflowScorerConfig {\n return typeof scorers === 'object' && !Array.isArray(scorers) && ('workflow' in scorers || 'steps' in scorers);\n}\n\nfunction validateEvalsInputs(\n data: RunEvalsDataItem<any>[],\n scorers: MastraScorer<any, any, any, any>[] | WorkflowScorerConfig,\n target: Agent | Workflow,\n): void {\n if (data.length === 0) {\n throw new MastraError({\n domain: 'SCORER',\n id: 'RUN_EXPERIMENT_FAILED_NO_DATA_PROVIDED',\n category: 'USER',\n text: 'Failed to run experiment: Data array is empty',\n });\n }\n\n for (let i = 0; i < data.length; i++) {\n const item = data[i];\n if (!item || typeof item !== 'object' || !('input' in item)) {\n throw new MastraError({\n domain: 'SCORER',\n id: 'INVALID_DATA_ITEM',\n category: 'USER',\n text: `Invalid data item at index ${i}: must have 'input' properties`,\n });\n }\n }\n\n // Validate scorers\n if (Array.isArray(scorers)) {\n if (scorers.length === 0) {\n throw new MastraError({\n domain: 'SCORER',\n id: 'NO_SCORERS_PROVIDED',\n category: 'USER',\n text: 'At least one scorer must be provided',\n });\n }\n } else if (isWorkflow(target) && isWorkflowScorerConfig(scorers)) {\n const hasScorers =\n (scorers.workflow && scorers.workflow.length > 0) || (scorers.steps && Object.keys(scorers.steps).length > 0);\n\n if (!hasScorers) {\n throw new MastraError({\n domain: 'SCORER',\n id: 'NO_SCORERS_PROVIDED',\n category: 'USER',\n text: 'At least one workflow or step scorer must be provided',\n });\n }\n } else if (!isWorkflow(target) && !Array.isArray(scorers)) {\n throw new MastraError({\n domain: 'SCORER',\n id: 'INVALID_AGENT_SCORERS',\n category: 'USER',\n text: 'Agent scorers must be an array of scorers',\n });\n }\n}\n\nasync function executeTarget(target: Agent | Workflow, item: RunEvalsDataItem<any>) {\n try {\n if (isWorkflow(target)) {\n return await executeWorkflow(target, item);\n } else {\n return await executeAgent(target, item);\n }\n } catch (error) {\n throw new MastraError(\n {\n domain: 'SCORER',\n id: 'RUN_EXPERIMENT_TARGET_FAILED_TO_GENERATE_RESULT',\n category: 'USER',\n text: 'Failed to run experiment: Error generating result from target',\n details: {\n item: JSON.stringify(item),\n },\n },\n error,\n );\n }\n}\n\nasync function executeWorkflow(target: Workflow, item: RunEvalsDataItem<any>) {\n const run = await target.createRun({ disableScorers: true });\n const workflowResult = await run.start({\n inputData: item.input,\n requestContext: item.requestContext,\n });\n\n return {\n scoringData: {\n input: item.input,\n output: workflowResult.status === 'success' ? workflowResult.result : undefined,\n stepResults: workflowResult.steps as Record<string, StepResult<any, any, any, any>>,\n },\n };\n}\n\nasync function executeAgent(agent: Agent, item: RunEvalsDataItem<any>) {\n const model = await agent.getModel();\n if (isSupportedLanguageModel(model)) {\n return await agent.generate(item.input as any, {\n scorers: {},\n returnScorerData: true,\n requestContext: item.requestContext,\n });\n } else {\n return await agent.generateLegacy(item.input as any, {\n scorers: {},\n returnScorerData: true,\n requestContext: item.requestContext,\n });\n }\n}\n\nasync function runScorers(\n scorers: MastraScorer<any, any, any, any>[] | WorkflowScorerConfig,\n targetResult: any,\n item: RunEvalsDataItem<any>,\n): Promise<Record<string, any>> {\n const scorerResults: Record<string, any> = {};\n\n if (Array.isArray(scorers)) {\n for (const scorer of scorers) {\n try {\n const score = await scorer.run({\n input: targetResult.scoringData?.input,\n output: targetResult.scoringData?.output,\n groundTruth: item.groundTruth,\n requestContext: item.requestContext,\n tracingContext: item.tracingContext,\n });\n\n scorerResults[scorer.id] = score;\n } catch (error) {\n throw new MastraError(\n {\n domain: 'SCORER',\n id: 'RUN_EXPERIMENT_SCORER_FAILED_TO_SCORE_RESULT',\n category: 'USER',\n text: `Failed to run experiment: Error running scorer ${scorer.id}`,\n details: {\n scorerId: scorer.id,\n item: JSON.stringify(item),\n },\n },\n error,\n );\n }\n }\n } else {\n // Handle workflow scorer config\n if (scorers.workflow) {\n const workflowScorerResults: Record<string, any> = {};\n for (const scorer of scorers.workflow) {\n const score = await scorer.run({\n input: targetResult.scoringData.input,\n output: targetResult.scoringData.output,\n groundTruth: item.groundTruth,\n requestContext: item.requestContext,\n tracingContext: item.tracingContext,\n });\n workflowScorerResults[scorer.id] = score;\n }\n if (Object.keys(workflowScorerResults).length > 0) {\n scorerResults.workflow = workflowScorerResults;\n }\n }\n\n if (scorers.steps) {\n const stepScorerResults: Record<string, any> = {};\n for (const [stepId, stepScorers] of Object.entries(scorers.steps)) {\n const stepResult = targetResult.scoringData.stepResults?.[stepId];\n if (stepResult?.status === 'success' && stepResult.payload && stepResult.output) {\n const stepResults: Record<string, any> = {};\n for (const scorer of stepScorers) {\n try {\n const score = await scorer.run({\n input: stepResult.payload,\n output: stepResult.output,\n groundTruth: item.groundTruth,\n requestContext: item.requestContext,\n tracingContext: item.tracingContext,\n });\n stepResults[scorer.id] = score;\n } catch (error) {\n throw new MastraError(\n {\n domain: 'SCORER',\n id: 'RUN_EXPERIMENT_SCORER_FAILED_TO_SCORE_STEP_RESULT',\n category: 'USER',\n text: `Failed to run experiment: Error running scorer ${scorer.id} on step ${stepId}`,\n details: {\n scorerId: scorer.id,\n stepId,\n },\n },\n error,\n );\n }\n }\n if (Object.keys(stepResults).length > 0) {\n stepScorerResults[stepId] = stepResults;\n }\n }\n }\n if (Object.keys(stepScorerResults).length > 0) {\n scorerResults.steps = stepScorerResults;\n }\n }\n }\n\n return scorerResults;\n}\n\n/**\n * Saves scorer results to storage when running evaluations.\n * This makes scores visible in Studio's observability section.\n */\nasync function saveScoresToStorage({\n storage,\n scorerResults,\n target,\n item,\n mastra,\n}: {\n storage: any;\n scorerResults: Record<string, any>;\n target: Agent | Workflow;\n item: RunEvalsDataItem<any>;\n mastra: any;\n}): Promise<void> {\n const entityId = target.id;\n const entityType = isWorkflow(target) ? 'WORKFLOW' : 'AGENT';\n\n // Handle flat scorer results (for agents or workflow-level scorers)\n if (Array.isArray(scorerResults) || !('workflow' in scorerResults && 'steps' in scorerResults)) {\n for (const [scorerId, scoreResult] of Object.entries(scorerResults)) {\n if (scoreResult && typeof scoreResult === 'object' && 'score' in scoreResult) {\n await saveSingleScore({\n storage,\n scoreResult,\n scorerId,\n entityId,\n entityType,\n mastra,\n target,\n item,\n });\n }\n }\n } else {\n // Handle workflow scorer config with workflow and step scorers\n if (scorerResults.workflow) {\n for (const [scorerId, scoreResult] of Object.entries(scorerResults.workflow)) {\n if (scoreResult && typeof scoreResult === 'object' && 'score' in scoreResult) {\n await saveSingleScore({\n storage,\n scoreResult,\n scorerId,\n entityId,\n entityType: 'WORKFLOW',\n mastra,\n target,\n item,\n });\n }\n }\n }\n\n if (scorerResults.steps) {\n for (const [stepId, stepScorers] of Object.entries(scorerResults.steps)) {\n for (const [scorerId, scoreResult] of Object.entries(stepScorers as Record<string, any>)) {\n if (scoreResult && typeof scoreResult === 'object' && 'score' in scoreResult) {\n await saveSingleScore({\n storage,\n scoreResult,\n scorerId,\n entityId: stepId,\n entityType: 'STEP',\n mastra,\n target,\n item,\n });\n }\n }\n }\n }\n }\n}\n\n/**\n * Saves a single scorer result to storage\n */\nasync function saveSingleScore({\n storage,\n scoreResult,\n scorerId,\n entityId,\n entityType,\n mastra,\n target,\n item,\n}: {\n storage: any;\n scoreResult: any;\n scorerId: string;\n entityId: string;\n entityType: string;\n mastra: any;\n target: Agent | Workflow;\n item: RunEvalsDataItem<any>;\n}): Promise<void> {\n try {\n // Get scorer information\n let scorer = mastra?.getScorerById?.(scorerId);\n\n if (!scorer) {\n // Try to get from target's scorers\n const targetScorers = await (target as any).listScorers?.();\n if (targetScorers) {\n for (const [_, scorerEntry] of Object.entries(targetScorers)) {\n if ((scorerEntry as any).scorer?.id === scorerId) {\n scorer = (scorerEntry as any).scorer;\n break;\n }\n }\n }\n }\n\n // Extract tracing context if available\n let traceId: string | undefined;\n let spanId: string | undefined;\n if (item.tracingContext?.currentSpan && item.tracingContext.currentSpan.isValid) {\n spanId = item.tracingContext.currentSpan.id;\n traceId = item.tracingContext.currentSpan.traceId;\n }\n\n // Build additional context with groundTruth if available\n const additionalContext: Record<string, any> = {};\n if (item.groundTruth !== undefined) {\n additionalContext.groundTruth = item.groundTruth;\n }\n\n const payload = {\n ...scoreResult,\n scorerId,\n entityId,\n entityType,\n source: 'TEST' as const,\n scorer: {\n id: scorer?.id || scorerId,\n name: scorer?.name || scorerId,\n description: scorer?.description || '',\n type: scorer?.type || 'unknown',\n },\n entity: {\n id: target.id,\n name: (target as any).name || target.id,\n },\n // Include requestContext from item\n requestContext: item.requestContext ? Object.fromEntries(item.requestContext.entries()) : undefined,\n // Include additionalContext with groundTruth\n additionalContext: Object.keys(additionalContext).length > 0 ? additionalContext : undefined,\n // Include tracing information\n traceId,\n spanId,\n };\n\n await validateAndSaveScore(storage, payload);\n } catch (error) {\n // Log error but don't fail the evaluation\n mastra?.getLogger?.()?.warn?.(`Failed to save score for scorer ${scorerId}:`, error);\n }\n}\n"]}