@mastra/core 0.24.0 → 1.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (810) hide show
  1. package/CHANGELOG.md +478 -141
  2. package/README.md +2 -3
  3. package/agent/message-list.d.ts +1 -0
  4. package/dist/action/index.d.ts +0 -2
  5. package/dist/action/index.d.ts.map +1 -1
  6. package/dist/agent/__tests__/mock-model.d.ts +3 -1
  7. package/dist/agent/__tests__/mock-model.d.ts.map +1 -1
  8. package/dist/agent/agent-legacy.d.ts +176 -0
  9. package/dist/agent/agent-legacy.d.ts.map +1 -0
  10. package/dist/agent/agent.d.ts +83 -229
  11. package/dist/agent/agent.d.ts.map +1 -1
  12. package/dist/agent/agent.types.d.ts +10 -25
  13. package/dist/agent/agent.types.d.ts.map +1 -1
  14. package/dist/agent/index.cjs +10 -26
  15. package/dist/agent/index.d.ts +1 -2
  16. package/dist/agent/index.d.ts.map +1 -1
  17. package/dist/agent/index.js +2 -2
  18. package/dist/agent/message-list/index.cjs +16 -0
  19. package/dist/agent/message-list/index.d.ts +77 -87
  20. package/dist/agent/message-list/index.d.ts.map +1 -1
  21. package/dist/agent/message-list/index.js +3 -0
  22. package/dist/agent/message-list/prompt/attachments-to-parts.d.ts +2 -2
  23. package/dist/agent/message-list/prompt/attachments-to-parts.d.ts.map +1 -1
  24. package/dist/agent/message-list/prompt/convert-to-mastra-v1.d.ts +2 -2
  25. package/dist/agent/message-list/prompt/download-assets.d.ts.map +1 -1
  26. package/dist/agent/message-list/prompt/invalid-content-error.d.ts +1 -1
  27. package/dist/agent/message-list/prompt/invalid-content-error.d.ts.map +1 -1
  28. package/dist/agent/message-list/types.d.ts +2 -1
  29. package/dist/agent/message-list/types.d.ts.map +1 -1
  30. package/dist/agent/message-list/utils/ai-v4-v5/core-model-message.d.ts +3 -2
  31. package/dist/agent/message-list/utils/ai-v4-v5/core-model-message.d.ts.map +1 -1
  32. package/dist/agent/message-list/utils/ai-v4-v5/ui-message.d.ts +3 -2
  33. package/dist/agent/message-list/utils/ai-v4-v5/ui-message.d.ts.map +1 -1
  34. package/dist/agent/message-list/utils/ai-v5/gemini-compatibility.d.ts +1 -1
  35. package/dist/agent/message-list/utils/ai-v5/gemini-compatibility.d.ts.map +1 -1
  36. package/dist/agent/message-list/utils/convert-messages.d.ts +4 -4
  37. package/dist/agent/message-list/utils/convert-messages.d.ts.map +1 -1
  38. package/dist/agent/test-utils.d.ts +2 -79
  39. package/dist/agent/test-utils.d.ts.map +1 -1
  40. package/dist/agent/trip-wire.d.ts +1 -1
  41. package/dist/agent/trip-wire.d.ts.map +1 -1
  42. package/dist/agent/types.d.ts +23 -37
  43. package/dist/agent/types.d.ts.map +1 -1
  44. package/dist/agent/utils.d.ts +15 -64
  45. package/dist/agent/utils.d.ts.map +1 -1
  46. package/dist/agent/workflows/prepare-stream/index.d.ts +16 -20
  47. package/dist/agent/workflows/prepare-stream/index.d.ts.map +1 -1
  48. package/dist/agent/workflows/prepare-stream/map-results-step.d.ts +5 -7
  49. package/dist/agent/workflows/prepare-stream/map-results-step.d.ts.map +1 -1
  50. package/dist/agent/workflows/prepare-stream/prepare-memory-step.d.ts +14 -18
  51. package/dist/agent/workflows/prepare-stream/prepare-memory-step.d.ts.map +1 -1
  52. package/dist/agent/workflows/prepare-stream/prepare-tools-step.d.ts +6 -6
  53. package/dist/agent/workflows/prepare-stream/prepare-tools-step.d.ts.map +1 -1
  54. package/dist/agent/workflows/prepare-stream/schema.d.ts +10 -12
  55. package/dist/agent/workflows/prepare-stream/schema.d.ts.map +1 -1
  56. package/dist/agent/workflows/prepare-stream/stream-step.d.ts +3 -7
  57. package/dist/agent/workflows/prepare-stream/stream-step.d.ts.map +1 -1
  58. package/dist/ai-sdk.types.d.ts +4705 -0
  59. package/dist/base.cjs +2 -2
  60. package/dist/base.d.ts +0 -16
  61. package/dist/base.d.ts.map +1 -1
  62. package/dist/base.js +1 -1
  63. package/dist/bundler/index.cjs +2 -2
  64. package/dist/bundler/index.d.ts +2 -1
  65. package/dist/bundler/index.d.ts.map +1 -1
  66. package/dist/bundler/index.js +1 -1
  67. package/dist/cache/index.cjs +3 -3
  68. package/dist/cache/index.js +1 -1
  69. package/dist/chunk-26SQQNMU.js +15754 -0
  70. package/dist/chunk-26SQQNMU.js.map +1 -0
  71. package/dist/{chunk-FHVFGVIO.js → chunk-32CTMD2C.js} +90 -32
  72. package/dist/chunk-32CTMD2C.js.map +1 -0
  73. package/dist/chunk-4CDL2QJT.js +649 -0
  74. package/dist/chunk-4CDL2QJT.js.map +1 -0
  75. package/dist/chunk-5WRI5ZAA.js +29 -0
  76. package/dist/{chunk-3HXBPDKN.js.map → chunk-5WRI5ZAA.js.map} +1 -1
  77. package/dist/{chunk-KAEQISOW.js → chunk-76K3IYWM.js} +5 -5
  78. package/dist/chunk-76K3IYWM.js.map +1 -0
  79. package/dist/chunk-7AHYOMHJ.js +149 -0
  80. package/dist/chunk-7AHYOMHJ.js.map +1 -0
  81. package/dist/{chunk-BWGXM3D4.js → chunk-7SKXKUYT.js} +712 -541
  82. package/dist/chunk-7SKXKUYT.js.map +1 -0
  83. package/dist/{chunk-UZKIGB7M.cjs → chunk-BMAFVZ2D.cjs} +5 -5
  84. package/dist/chunk-BMAFVZ2D.cjs.map +1 -0
  85. package/dist/chunk-BNBRQS7N.js +910 -0
  86. package/dist/chunk-BNBRQS7N.js.map +1 -0
  87. package/dist/{chunk-34ZCWSUA.js → chunk-BU4IAJWF.js} +6 -9
  88. package/dist/chunk-BU4IAJWF.js.map +1 -0
  89. package/dist/{chunk-ABZOBBLL.cjs → chunk-BXOL277H.cjs} +735 -562
  90. package/dist/chunk-BXOL277H.cjs.map +1 -0
  91. package/dist/{chunk-6TEQIYXV.cjs → chunk-CBAB7GOD.cjs} +15 -15
  92. package/dist/chunk-CBAB7GOD.cjs.map +1 -0
  93. package/dist/{chunk-A5KDVZDL.cjs → chunk-DSNPWVIG.cjs} +9 -9
  94. package/dist/chunk-DSNPWVIG.cjs.map +1 -0
  95. package/dist/chunk-DZUJEN5N.cjs +32 -0
  96. package/dist/{chunk-EBVYYC2Q.cjs.map → chunk-DZUJEN5N.cjs.map} +1 -1
  97. package/dist/chunk-E7K4FTLN.cjs +273 -0
  98. package/dist/chunk-E7K4FTLN.cjs.map +1 -0
  99. package/dist/{chunk-MJMID7LX.cjs → chunk-ECFXGXWO.cjs} +609 -644
  100. package/dist/chunk-ECFXGXWO.cjs.map +1 -0
  101. package/dist/chunk-ET6UOTTU.cjs +154 -0
  102. package/dist/chunk-ET6UOTTU.cjs.map +1 -0
  103. package/dist/chunk-FD734TPS.cjs +15818 -0
  104. package/dist/chunk-FD734TPS.cjs.map +1 -0
  105. package/dist/chunk-GGYKYORQ.cjs +2060 -0
  106. package/dist/chunk-GGYKYORQ.cjs.map +1 -0
  107. package/dist/{chunk-HLRWYUFN.js → chunk-GRBGQ2GE.js} +5 -5
  108. package/dist/{chunk-HLRWYUFN.js.map → chunk-GRBGQ2GE.js.map} +1 -1
  109. package/dist/chunk-IU2SZXJQ.cjs +913 -0
  110. package/dist/chunk-IU2SZXJQ.cjs.map +1 -0
  111. package/dist/{chunk-GPWMM745.cjs → chunk-J7O6WENZ.cjs} +5 -5
  112. package/dist/{chunk-GPWMM745.cjs.map → chunk-J7O6WENZ.cjs.map} +1 -1
  113. package/dist/{chunk-PZUZNPFM.js → chunk-JJ5O45LH.js} +3 -4
  114. package/dist/chunk-JJ5O45LH.js.map +1 -0
  115. package/dist/{chunk-E3PG7G6E.js → chunk-JV2KH24V.js} +599 -633
  116. package/dist/chunk-JV2KH24V.js.map +1 -0
  117. package/dist/chunk-KEXGB7FK.cjs +29 -0
  118. package/dist/chunk-KEXGB7FK.cjs.map +1 -0
  119. package/dist/chunk-KIZIOFZC.js +265 -0
  120. package/dist/chunk-KIZIOFZC.js.map +1 -0
  121. package/dist/{chunk-UXG7PYML.js → chunk-KJ2SW6VA.js} +9 -9
  122. package/dist/chunk-KJ2SW6VA.js.map +1 -0
  123. package/dist/{chunk-TTELJD4F.js → chunk-L54GIUCB.js} +2 -2
  124. package/dist/chunk-L54GIUCB.js.map +1 -0
  125. package/dist/chunk-L7XKOKOW.js +12385 -0
  126. package/dist/chunk-L7XKOKOW.js.map +1 -0
  127. package/dist/{chunk-TSNDVBUU.cjs → chunk-MR7ZWBL6.cjs} +2 -2
  128. package/dist/chunk-MR7ZWBL6.cjs.map +1 -0
  129. package/dist/chunk-MV7KHWUT.js +2031 -0
  130. package/dist/chunk-MV7KHWUT.js.map +1 -0
  131. package/dist/{chunk-3NTOFNIU.js → chunk-OJNJA5ZI.js} +3 -3
  132. package/dist/{chunk-3NTOFNIU.js.map → chunk-OJNJA5ZI.js.map} +1 -1
  133. package/dist/{chunk-3VXXCPKX.js → chunk-P6APHXPZ.js} +334 -410
  134. package/dist/chunk-P6APHXPZ.js.map +1 -0
  135. package/dist/{chunk-77JHIM4E.cjs → chunk-QCQLOMJM.cjs} +348 -424
  136. package/dist/chunk-QCQLOMJM.cjs.map +1 -0
  137. package/dist/chunk-QM5SRDJX.js +9022 -0
  138. package/dist/chunk-QM5SRDJX.js.map +1 -0
  139. package/dist/{chunk-WBAXXG34.cjs → chunk-QUKUN6NR.cjs} +32 -66
  140. package/dist/chunk-QUKUN6NR.cjs.map +1 -0
  141. package/dist/{chunk-ROS5CMJS.cjs → chunk-QUZGDSWE.cjs} +63 -50
  142. package/dist/chunk-QUZGDSWE.cjs.map +1 -0
  143. package/dist/chunk-S5MJLXMG.cjs +12424 -0
  144. package/dist/chunk-S5MJLXMG.cjs.map +1 -0
  145. package/dist/chunk-S6URFGCZ.js +27 -0
  146. package/dist/chunk-S6URFGCZ.js.map +1 -0
  147. package/dist/chunk-SVLMF4UZ.cjs +9033 -0
  148. package/dist/chunk-SVLMF4UZ.cjs.map +1 -0
  149. package/dist/{chunk-ZMELUU72.js → chunk-TQTAMPSC.js} +3 -3
  150. package/dist/chunk-TQTAMPSC.js.map +1 -0
  151. package/dist/{chunk-5NTO7S5I.cjs → chunk-TWH4PTDG.cjs} +2 -4
  152. package/dist/chunk-TWH4PTDG.cjs.map +1 -0
  153. package/dist/{chunk-WCHE6FJ7.js → chunk-UIZSWUKP.js} +15 -50
  154. package/dist/chunk-UIZSWUKP.js.map +1 -0
  155. package/dist/{chunk-Z4RIRDU3.js → chunk-VJUZZB2I.js} +45 -32
  156. package/dist/chunk-VJUZZB2I.js.map +1 -0
  157. package/dist/{chunk-MCASUJWY.cjs → chunk-VOY2RXOC.cjs} +36 -59
  158. package/dist/chunk-VOY2RXOC.cjs.map +1 -0
  159. package/dist/{chunk-3JX2Y3WH.cjs → chunk-VV753WCB.cjs} +18 -21
  160. package/dist/chunk-VV753WCB.cjs.map +1 -0
  161. package/dist/chunk-WM6CK2F3.cjs +674 -0
  162. package/dist/chunk-WM6CK2F3.cjs.map +1 -0
  163. package/dist/{chunk-PFXXH2RP.js → chunk-X7JMA3IY.js} +15 -15
  164. package/dist/chunk-X7JMA3IY.js.map +1 -0
  165. package/dist/{chunk-NR77P3TK.js → chunk-XEVG546F.js} +14 -37
  166. package/dist/chunk-XEVG546F.js.map +1 -0
  167. package/dist/{chunk-QFF5JUKT.cjs → chunk-Y63IFHEZ.cjs} +4 -4
  168. package/dist/chunk-Y63IFHEZ.cjs.map +1 -0
  169. package/dist/{chunk-B7V6NYWH.cjs → chunk-Y6ROD72V.cjs} +4 -4
  170. package/dist/{chunk-B7V6NYWH.cjs.map → chunk-Y6ROD72V.cjs.map} +1 -1
  171. package/dist/{chunk-7J3XX4AO.cjs → chunk-YIK3ASEG.cjs} +100 -42
  172. package/dist/chunk-YIK3ASEG.cjs.map +1 -0
  173. package/dist/deployer/index.cjs +8 -6
  174. package/dist/deployer/index.cjs.map +1 -1
  175. package/dist/deployer/index.js +10 -1
  176. package/dist/deployer/index.js.map +1 -1
  177. package/dist/di/index.cjs +3 -3
  178. package/dist/di/index.d.ts +1 -1
  179. package/dist/di/index.js +1 -1
  180. package/dist/error/index.cjs +6 -6
  181. package/dist/error/index.d.ts +0 -1
  182. package/dist/error/index.d.ts.map +1 -1
  183. package/dist/error/index.js +1 -1
  184. package/dist/{scores → evals}/base.d.ts +20 -18
  185. package/dist/evals/base.d.ts.map +1 -0
  186. package/dist/{scores → evals}/base.test-utils.d.ts +25 -25
  187. package/dist/evals/base.test-utils.d.ts.map +1 -0
  188. package/dist/{scores → evals}/hooks.d.ts +3 -3
  189. package/dist/evals/hooks.d.ts.map +1 -0
  190. package/dist/evals/index.cjs +37 -0
  191. package/dist/evals/index.d.ts +4 -0
  192. package/dist/evals/index.d.ts.map +1 -0
  193. package/dist/evals/index.js +4 -0
  194. package/dist/{scores/run-experiment → evals/run}/index.d.ts +18 -18
  195. package/dist/evals/run/index.d.ts.map +1 -0
  196. package/dist/evals/run/scorerAccumulator.d.ts.map +1 -0
  197. package/dist/{scores → evals}/scoreTraces/index.cjs +79 -99
  198. package/dist/evals/scoreTraces/index.cjs.map +1 -0
  199. package/dist/evals/scoreTraces/index.d.ts.map +1 -0
  200. package/dist/{scores → evals}/scoreTraces/index.js +72 -92
  201. package/dist/evals/scoreTraces/index.js.map +1 -0
  202. package/dist/{scores → evals}/scoreTraces/scoreTraces.d.ts +2 -2
  203. package/dist/evals/scoreTraces/scoreTraces.d.ts.map +1 -0
  204. package/dist/{scores → evals}/scoreTraces/scoreTracesWorkflow.d.ts +11 -11
  205. package/dist/evals/scoreTraces/scoreTracesWorkflow.d.ts.map +1 -0
  206. package/dist/{scores → evals}/scoreTraces/utils.d.ts +7 -7
  207. package/dist/evals/scoreTraces/utils.d.ts.map +1 -0
  208. package/dist/{scores → evals}/types.d.ts +22 -22
  209. package/dist/evals/types.d.ts.map +1 -0
  210. package/dist/features/index.cjs +8 -0
  211. package/dist/features/index.cjs.map +1 -0
  212. package/dist/features/index.d.ts +17 -0
  213. package/dist/features/index.d.ts.map +1 -0
  214. package/dist/features/index.js +6 -0
  215. package/dist/features/index.js.map +1 -0
  216. package/dist/hooks/index.cjs +4 -4
  217. package/dist/hooks/index.d.ts +1 -27
  218. package/dist/hooks/index.d.ts.map +1 -1
  219. package/dist/hooks/index.js +1 -1
  220. package/dist/index.cjs +2 -340
  221. package/dist/index.cjs.map +1 -1
  222. package/dist/index.d.ts +1 -18
  223. package/dist/index.d.ts.map +1 -1
  224. package/dist/index.js +1 -113
  225. package/dist/index.js.map +1 -1
  226. package/dist/integration/index.cjs +87 -10
  227. package/dist/integration/index.cjs.map +1 -1
  228. package/dist/integration/index.js +88 -1
  229. package/dist/integration/index.js.map +1 -1
  230. package/dist/integration/integration.d.ts +3 -3
  231. package/dist/integration/integration.d.ts.map +1 -1
  232. package/dist/llm/index.cjs +7 -7
  233. package/dist/llm/index.d.ts +5 -6
  234. package/dist/llm/index.d.ts.map +1 -1
  235. package/dist/llm/index.js +1 -1
  236. package/dist/llm/model/base.types.d.ts +6 -7
  237. package/dist/llm/model/base.types.d.ts.map +1 -1
  238. package/dist/llm/model/model.d.ts +7 -7
  239. package/dist/llm/model/model.d.ts.map +1 -1
  240. package/dist/llm/model/model.loop.d.ts +1 -1
  241. package/dist/llm/model/model.loop.d.ts.map +1 -1
  242. package/dist/llm/model/model.loop.types.d.ts +3 -3
  243. package/dist/llm/model/model.loop.types.d.ts.map +1 -1
  244. package/dist/llm/model/provider-types.generated.d.ts +32 -7
  245. package/dist/llm/model/resolve-model.d.ts +8 -8
  246. package/dist/llm/model/shared.types.d.ts +2 -2
  247. package/dist/llm/model/shared.types.d.ts.map +1 -1
  248. package/dist/logger/constants.d.ts +1 -1
  249. package/dist/logger/default-logger.d.ts +2 -2
  250. package/dist/logger/default-logger.d.ts.map +1 -1
  251. package/dist/logger/index.cjs +11 -11
  252. package/dist/logger/index.js +2 -2
  253. package/dist/logger/logger.d.ts +4 -4
  254. package/dist/logger/logger.d.ts.map +1 -1
  255. package/dist/logger/multi-logger.d.ts +2 -2
  256. package/dist/logger/multi-logger.d.ts.map +1 -1
  257. package/dist/logger/transport.d.ts +3 -3
  258. package/dist/logger/transport.d.ts.map +1 -1
  259. package/dist/loop/index.cjs +2 -2
  260. package/dist/loop/index.js +1 -1
  261. package/dist/loop/loop.d.ts +1 -1
  262. package/dist/loop/loop.d.ts.map +1 -1
  263. package/dist/loop/network/index.d.ts +15 -15
  264. package/dist/loop/network/index.d.ts.map +1 -1
  265. package/dist/loop/test-utils/generateText.d.ts.map +1 -1
  266. package/dist/loop/test-utils/options.d.ts.map +1 -1
  267. package/dist/loop/test-utils/resultObject.d.ts.map +1 -1
  268. package/dist/loop/test-utils/streamObject.d.ts.map +1 -1
  269. package/dist/loop/types.d.ts +4 -7
  270. package/dist/loop/types.d.ts.map +1 -1
  271. package/dist/loop/workflows/agentic-execution/index.d.ts +55 -55
  272. package/dist/loop/workflows/agentic-execution/index.d.ts.map +1 -1
  273. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts +38 -38
  274. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts.map +1 -1
  275. package/dist/loop/workflows/agentic-execution/llm-mapping-step.d.ts +20 -20
  276. package/dist/loop/workflows/agentic-execution/llm-mapping-step.d.ts.map +1 -1
  277. package/dist/loop/workflows/agentic-execution/tool-call-step.d.ts +2 -2
  278. package/dist/loop/workflows/agentic-execution/tool-call-step.d.ts.map +1 -1
  279. package/dist/loop/workflows/agentic-loop/index.d.ts +55 -55
  280. package/dist/loop/workflows/agentic-loop/index.d.ts.map +1 -1
  281. package/dist/loop/workflows/schema.d.ts +19 -20
  282. package/dist/loop/workflows/schema.d.ts.map +1 -1
  283. package/dist/loop/workflows/stream.d.ts +1 -1
  284. package/dist/loop/workflows/stream.d.ts.map +1 -1
  285. package/dist/mastra/hooks.d.ts +2 -2
  286. package/dist/mastra/hooks.d.ts.map +1 -1
  287. package/dist/mastra/index.cjs +2 -2
  288. package/dist/mastra/index.d.ts +389 -180
  289. package/dist/mastra/index.d.ts.map +1 -1
  290. package/dist/mastra/index.js +1 -1
  291. package/dist/mcp/index.cjs +41 -4
  292. package/dist/mcp/index.cjs.map +1 -1
  293. package/dist/mcp/index.d.ts +6 -4
  294. package/dist/mcp/index.d.ts.map +1 -1
  295. package/dist/mcp/index.js +39 -2
  296. package/dist/mcp/index.js.map +1 -1
  297. package/dist/mcp/types.d.ts +0 -15
  298. package/dist/mcp/types.d.ts.map +1 -1
  299. package/dist/memory/index.cjs +327 -13
  300. package/dist/memory/index.cjs.map +1 -1
  301. package/dist/memory/index.d.ts +1 -0
  302. package/dist/memory/index.d.ts.map +1 -1
  303. package/dist/memory/index.js +327 -1
  304. package/dist/memory/index.js.map +1 -1
  305. package/dist/memory/memory.d.ts +33 -57
  306. package/dist/memory/memory.d.ts.map +1 -1
  307. package/dist/memory/mock.d.ts +61 -0
  308. package/dist/memory/mock.d.ts.map +1 -0
  309. package/dist/memory/types.d.ts +48 -45
  310. package/dist/memory/types.d.ts.map +1 -1
  311. package/dist/models-dev-7U4NRMM3.js +3 -0
  312. package/dist/{models-dev-4VGIWYS3.js.map → models-dev-7U4NRMM3.js.map} +1 -1
  313. package/dist/models-dev-VKSAQPRK.cjs +12 -0
  314. package/dist/{models-dev-AXZASLL2.cjs.map → models-dev-VKSAQPRK.cjs.map} +1 -1
  315. package/dist/netlify-2IDXTNFW.cjs +12 -0
  316. package/dist/{netlify-TX6V7SJJ.cjs.map → netlify-2IDXTNFW.cjs.map} +1 -1
  317. package/dist/netlify-42ZNWIDQ.js +3 -0
  318. package/dist/{netlify-VJXBII33.js.map → netlify-42ZNWIDQ.js.map} +1 -1
  319. package/dist/{ai-tracing → observability}/context.d.ts +5 -5
  320. package/dist/observability/context.d.ts.map +1 -0
  321. package/dist/observability/index.cjs +36 -0
  322. package/dist/observability/index.d.ts +11 -0
  323. package/dist/observability/index.d.ts.map +1 -0
  324. package/dist/observability/index.js +3 -0
  325. package/dist/observability/no-op.d.ts +22 -0
  326. package/dist/observability/no-op.d.ts.map +1 -0
  327. package/dist/observability/types/index.d.ts +2 -0
  328. package/dist/observability/types/index.d.ts.map +1 -0
  329. package/dist/{ai-tracing/types.d.ts → observability/types/tracing.d.ts} +161 -107
  330. package/dist/observability/types/tracing.d.ts.map +1 -0
  331. package/dist/observability/utils.d.ts +12 -0
  332. package/dist/observability/utils.d.ts.map +1 -0
  333. package/dist/processors/index.cjs +11 -11
  334. package/dist/processors/index.d.ts +10 -9
  335. package/dist/processors/index.d.ts.map +1 -1
  336. package/dist/processors/index.js +1 -1
  337. package/dist/processors/processors/batch-parts.d.ts +2 -1
  338. package/dist/processors/processors/batch-parts.d.ts.map +1 -1
  339. package/dist/processors/processors/language-detector.d.ts +6 -5
  340. package/dist/processors/processors/language-detector.d.ts.map +1 -1
  341. package/dist/processors/processors/moderation.d.ts +8 -7
  342. package/dist/processors/processors/moderation.d.ts.map +1 -1
  343. package/dist/processors/processors/pii-detector.d.ts +8 -7
  344. package/dist/processors/processors/pii-detector.d.ts.map +1 -1
  345. package/dist/processors/processors/prompt-injection-detector.d.ts +6 -5
  346. package/dist/processors/processors/prompt-injection-detector.d.ts.map +1 -1
  347. package/dist/processors/processors/structured-output.d.ts +3 -2
  348. package/dist/processors/processors/structured-output.d.ts.map +1 -1
  349. package/dist/processors/processors/system-prompt-scrubber.d.ts +6 -5
  350. package/dist/processors/processors/system-prompt-scrubber.d.ts.map +1 -1
  351. package/dist/processors/processors/token-limiter.d.ts +5 -4
  352. package/dist/processors/processors/token-limiter.d.ts.map +1 -1
  353. package/dist/processors/processors/unicode-normalizer.d.ts +5 -4
  354. package/dist/processors/processors/unicode-normalizer.d.ts.map +1 -1
  355. package/dist/processors/runner.d.ts +5 -5
  356. package/dist/processors/runner.d.ts.map +1 -1
  357. package/dist/provider-registry.json +76 -18
  358. package/dist/{registry-generator-DXRSYYYT.js → registry-generator-H4YNODDH.js} +2 -2
  359. package/dist/{registry-generator-DXRSYYYT.js.map → registry-generator-H4YNODDH.js.map} +1 -1
  360. package/dist/{registry-generator-6WVOHM2L.cjs → registry-generator-MK63POJO.cjs} +2 -2
  361. package/dist/{registry-generator-6WVOHM2L.cjs.map → registry-generator-MK63POJO.cjs.map} +1 -1
  362. package/dist/relevance/index.cjs +47 -13
  363. package/dist/relevance/index.cjs.map +1 -1
  364. package/dist/relevance/index.d.ts +0 -1
  365. package/dist/relevance/index.d.ts.map +1 -1
  366. package/dist/relevance/index.js +49 -1
  367. package/dist/relevance/index.js.map +1 -1
  368. package/dist/relevance/mastra-agent/index.d.ts.map +1 -1
  369. package/dist/request-context/index.cjs +12 -0
  370. package/dist/{runtime-context → request-context}/index.d.ts +1 -1
  371. package/dist/{runtime-context → request-context}/index.d.ts.map +1 -1
  372. package/dist/request-context/index.js +3 -0
  373. package/dist/server/auth.d.ts.map +1 -1
  374. package/dist/server/index.cjs +9 -25
  375. package/dist/server/index.cjs.map +1 -1
  376. package/dist/server/index.js +4 -21
  377. package/dist/server/index.js.map +1 -1
  378. package/dist/server/types.d.ts +3 -3
  379. package/dist/server/types.d.ts.map +1 -1
  380. package/dist/storage/base.d.ts +75 -143
  381. package/dist/storage/base.d.ts.map +1 -1
  382. package/dist/storage/constants.d.ts +3 -4
  383. package/dist/storage/constants.d.ts.map +1 -1
  384. package/dist/storage/domains/index.d.ts +0 -2
  385. package/dist/storage/domains/index.d.ts.map +1 -1
  386. package/dist/storage/domains/memory/base.d.ts +19 -56
  387. package/dist/storage/domains/memory/base.d.ts.map +1 -1
  388. package/dist/storage/domains/memory/inmemory.d.ts +15 -35
  389. package/dist/storage/domains/memory/inmemory.d.ts.map +1 -1
  390. package/dist/storage/domains/observability/base.d.ts +24 -24
  391. package/dist/storage/domains/observability/base.d.ts.map +1 -1
  392. package/dist/storage/domains/observability/inmemory.d.ts +18 -18
  393. package/dist/storage/domains/observability/inmemory.d.ts.map +1 -1
  394. package/dist/storage/domains/operations/inmemory.d.ts.map +1 -1
  395. package/dist/storage/domains/scores/base.d.ts +5 -5
  396. package/dist/storage/domains/scores/base.d.ts.map +1 -1
  397. package/dist/storage/domains/scores/inmemory.d.ts +5 -5
  398. package/dist/storage/domains/scores/inmemory.d.ts.map +1 -1
  399. package/dist/storage/domains/workflows/base.d.ts +4 -11
  400. package/dist/storage/domains/workflows/base.d.ts.map +1 -1
  401. package/dist/storage/domains/workflows/inmemory.d.ts +4 -11
  402. package/dist/storage/domains/workflows/inmemory.d.ts.map +1 -1
  403. package/dist/storage/index.cjs +74 -1775
  404. package/dist/storage/index.cjs.map +1 -1
  405. package/dist/storage/index.js +1 -1744
  406. package/dist/storage/index.js.map +1 -1
  407. package/dist/storage/mock.d.ts +35 -92
  408. package/dist/storage/mock.d.ts.map +1 -1
  409. package/dist/storage/types.d.ts +77 -75
  410. package/dist/storage/types.d.ts.map +1 -1
  411. package/dist/stream/MastraAgentNetworkStream.d.ts +4 -2
  412. package/dist/stream/MastraAgentNetworkStream.d.ts.map +1 -1
  413. package/dist/stream/MastraWorkflowStream.d.ts +1 -1
  414. package/dist/stream/MastraWorkflowStream.d.ts.map +1 -1
  415. package/dist/stream/RunOutput.d.ts +1 -0
  416. package/dist/stream/RunOutput.d.ts.map +1 -1
  417. package/dist/stream/aisdk/v4/input.d.ts +1 -1
  418. package/dist/stream/aisdk/v4/input.d.ts.map +1 -1
  419. package/dist/stream/aisdk/v5/execute.d.ts +4 -11
  420. package/dist/stream/aisdk/v5/execute.d.ts.map +1 -1
  421. package/dist/stream/aisdk/v5/output.d.ts +1 -1
  422. package/dist/stream/aisdk/v5/output.d.ts.map +1 -1
  423. package/dist/stream/base/output.d.ts +1 -1
  424. package/dist/stream/base/output.d.ts.map +1 -1
  425. package/dist/stream/index.cjs +11 -11
  426. package/dist/stream/index.d.ts +1 -1
  427. package/dist/stream/index.d.ts.map +1 -1
  428. package/dist/stream/index.js +2 -2
  429. package/dist/stream/types.d.ts +2 -6
  430. package/dist/stream/types.d.ts.map +1 -1
  431. package/dist/test-utils/llm-mock.cjs +8 -8
  432. package/dist/test-utils/llm-mock.cjs.map +1 -1
  433. package/dist/test-utils/llm-mock.d.ts +1 -1
  434. package/dist/test-utils/llm-mock.d.ts.map +1 -1
  435. package/dist/test-utils/llm-mock.js +3 -3
  436. package/dist/test-utils/llm-mock.js.map +1 -1
  437. package/dist/tools/index.cjs +4 -4
  438. package/dist/tools/index.js +1 -1
  439. package/dist/tools/is-vercel-tool.cjs +2 -2
  440. package/dist/tools/is-vercel-tool.js +1 -1
  441. package/dist/tools/tool-builder/builder.d.ts +3 -71
  442. package/dist/tools/tool-builder/builder.d.ts.map +1 -1
  443. package/dist/tools/tool.d.ts +25 -25
  444. package/dist/tools/tool.d.ts.map +1 -1
  445. package/dist/tools/types.d.ts +102 -11
  446. package/dist/tools/types.d.ts.map +1 -1
  447. package/dist/tools/validation.d.ts +4 -3
  448. package/dist/tools/validation.d.ts.map +1 -1
  449. package/dist/tts/index.cjs +12 -6
  450. package/dist/tts/index.cjs.map +1 -1
  451. package/dist/tts/index.d.ts +0 -1
  452. package/dist/tts/index.d.ts.map +1 -1
  453. package/dist/tts/index.js +14 -1
  454. package/dist/tts/index.js.map +1 -1
  455. package/dist/types/dynamic-argument.d.ts +3 -3
  456. package/dist/utils/fetchWithRetry.d.ts +9 -0
  457. package/dist/utils/fetchWithRetry.d.ts.map +1 -0
  458. package/dist/utils.cjs +33 -17
  459. package/dist/utils.d.ts +39 -6
  460. package/dist/utils.d.ts.map +1 -1
  461. package/dist/utils.js +1 -1
  462. package/dist/vector/embed.d.ts +1 -1
  463. package/dist/vector/embed.d.ts.map +1 -1
  464. package/dist/vector/index.cjs +80 -8
  465. package/dist/vector/index.cjs.map +1 -1
  466. package/dist/vector/index.js +80 -1
  467. package/dist/vector/index.js.map +1 -1
  468. package/dist/vector/vector.d.ts +5 -2
  469. package/dist/vector/vector.d.ts.map +1 -1
  470. package/dist/voice/composite-voice.d.ts +1 -7
  471. package/dist/voice/composite-voice.d.ts.map +1 -1
  472. package/dist/voice/index.cjs +4 -4
  473. package/dist/voice/index.js +1 -1
  474. package/dist/voice/voice.d.ts +0 -1
  475. package/dist/voice/voice.d.ts.map +1 -1
  476. package/dist/workflows/default.d.ts +35 -43
  477. package/dist/workflows/default.d.ts.map +1 -1
  478. package/dist/workflows/evented/execution-engine.d.ts +5 -3
  479. package/dist/workflows/evented/execution-engine.d.ts.map +1 -1
  480. package/dist/workflows/evented/index.cjs +10 -10
  481. package/dist/workflows/evented/index.js +1 -1
  482. package/dist/workflows/evented/step-executor.d.ts +15 -13
  483. package/dist/workflows/evented/step-executor.d.ts.map +1 -1
  484. package/dist/workflows/evented/workflow-event-processor/index.d.ts +5 -5
  485. package/dist/workflows/evented/workflow-event-processor/index.d.ts.map +1 -1
  486. package/dist/workflows/evented/workflow-event-processor/loop.d.ts +3 -3
  487. package/dist/workflows/evented/workflow-event-processor/loop.d.ts.map +1 -1
  488. package/dist/workflows/evented/workflow-event-processor/parallel.d.ts +2 -2
  489. package/dist/workflows/evented/workflow-event-processor/sleep.d.ts +2 -2
  490. package/dist/workflows/evented/workflow-event-processor/utils.d.ts +2 -7
  491. package/dist/workflows/evented/workflow-event-processor/utils.d.ts.map +1 -1
  492. package/dist/workflows/evented/workflow.d.ts +11 -14
  493. package/dist/workflows/evented/workflow.d.ts.map +1 -1
  494. package/dist/workflows/execution-engine.d.ts +6 -6
  495. package/dist/workflows/execution-engine.d.ts.map +1 -1
  496. package/dist/workflows/index.cjs +22 -14
  497. package/dist/workflows/index.js +1 -1
  498. package/dist/workflows/step.d.ts +5 -5
  499. package/dist/workflows/step.d.ts.map +1 -1
  500. package/dist/workflows/types.d.ts +20 -44
  501. package/dist/workflows/types.d.ts.map +1 -1
  502. package/dist/workflows/utils.d.ts +14 -0
  503. package/dist/workflows/utils.d.ts.map +1 -1
  504. package/dist/workflows/workflow.d.ts +74 -64
  505. package/dist/workflows/workflow.d.ts.map +1 -1
  506. package/evals/scoreTraces.d.ts +1 -0
  507. package/evals.d.ts +1 -0
  508. package/features.d.ts +1 -0
  509. package/observability.d.ts +1 -0
  510. package/package.json +48 -64
  511. package/request-context.d.ts +1 -0
  512. package/src/_types/ai-sdk.types.d.ts +4705 -0
  513. package/src/llm/model/provider-types.generated.d.ts +32 -7
  514. package/agent/input-processor/processors.d.ts +0 -1
  515. package/ai-tracing.d.ts +0 -1
  516. package/dist/agent/index.warning.d.ts +0 -13
  517. package/dist/agent/index.warning.d.ts.map +0 -1
  518. package/dist/agent/input-processor/index.cjs +0 -28
  519. package/dist/agent/input-processor/index.d.ts +0 -10
  520. package/dist/agent/input-processor/index.d.ts.map +0 -1
  521. package/dist/agent/input-processor/index.js +0 -3
  522. package/dist/agent/input-processor/processors/index.d.ts +0 -6
  523. package/dist/agent/input-processor/processors/index.d.ts.map +0 -1
  524. package/dist/agent/input-processor/processors/language-detector.d.ts +0 -18
  525. package/dist/agent/input-processor/processors/language-detector.d.ts.map +0 -1
  526. package/dist/agent/input-processor/processors/moderation.d.ts +0 -18
  527. package/dist/agent/input-processor/processors/moderation.d.ts.map +0 -1
  528. package/dist/agent/input-processor/processors/pii-detector.d.ts +0 -18
  529. package/dist/agent/input-processor/processors/pii-detector.d.ts.map +0 -1
  530. package/dist/agent/input-processor/processors/prompt-injection-detector.d.ts +0 -18
  531. package/dist/agent/input-processor/processors/prompt-injection-detector.d.ts.map +0 -1
  532. package/dist/agent/input-processor/processors/unicode-normalizer.d.ts +0 -18
  533. package/dist/agent/input-processor/processors/unicode-normalizer.d.ts.map +0 -1
  534. package/dist/ai-tracing/context.d.ts.map +0 -1
  535. package/dist/ai-tracing/exporters/base.d.ts +0 -111
  536. package/dist/ai-tracing/exporters/base.d.ts.map +0 -1
  537. package/dist/ai-tracing/exporters/cloud.d.ts +0 -30
  538. package/dist/ai-tracing/exporters/cloud.d.ts.map +0 -1
  539. package/dist/ai-tracing/exporters/console.d.ts +0 -10
  540. package/dist/ai-tracing/exporters/console.d.ts.map +0 -1
  541. package/dist/ai-tracing/exporters/default.d.ts +0 -98
  542. package/dist/ai-tracing/exporters/default.d.ts.map +0 -1
  543. package/dist/ai-tracing/exporters/index.d.ts +0 -9
  544. package/dist/ai-tracing/exporters/index.d.ts.map +0 -1
  545. package/dist/ai-tracing/index.cjs +0 -148
  546. package/dist/ai-tracing/index.d.ts +0 -13
  547. package/dist/ai-tracing/index.d.ts.map +0 -1
  548. package/dist/ai-tracing/index.js +0 -3
  549. package/dist/ai-tracing/model-tracing.d.ts +0 -63
  550. package/dist/ai-tracing/model-tracing.d.ts.map +0 -1
  551. package/dist/ai-tracing/registry.d.ts +0 -51
  552. package/dist/ai-tracing/registry.d.ts.map +0 -1
  553. package/dist/ai-tracing/span_processors/index.d.ts +0 -5
  554. package/dist/ai-tracing/span_processors/index.d.ts.map +0 -1
  555. package/dist/ai-tracing/span_processors/sensitive-data-filter.d.ts +0 -85
  556. package/dist/ai-tracing/span_processors/sensitive-data-filter.d.ts.map +0 -1
  557. package/dist/ai-tracing/spans/base.d.ts +0 -65
  558. package/dist/ai-tracing/spans/base.d.ts.map +0 -1
  559. package/dist/ai-tracing/spans/default.d.ts +0 -13
  560. package/dist/ai-tracing/spans/default.d.ts.map +0 -1
  561. package/dist/ai-tracing/spans/index.d.ts +0 -7
  562. package/dist/ai-tracing/spans/index.d.ts.map +0 -1
  563. package/dist/ai-tracing/spans/no-op.d.ts +0 -15
  564. package/dist/ai-tracing/spans/no-op.d.ts.map +0 -1
  565. package/dist/ai-tracing/tracers/base.d.ts +0 -105
  566. package/dist/ai-tracing/tracers/base.d.ts.map +0 -1
  567. package/dist/ai-tracing/tracers/default.d.ts +0 -7
  568. package/dist/ai-tracing/tracers/default.d.ts.map +0 -1
  569. package/dist/ai-tracing/tracers/index.d.ts +0 -6
  570. package/dist/ai-tracing/tracers/index.d.ts.map +0 -1
  571. package/dist/ai-tracing/types.d.ts.map +0 -1
  572. package/dist/ai-tracing/utils.d.ts +0 -68
  573. package/dist/ai-tracing/utils.d.ts.map +0 -1
  574. package/dist/base.warning.d.ts +0 -9
  575. package/dist/base.warning.d.ts.map +0 -1
  576. package/dist/bundler/index.warning.d.ts +0 -9
  577. package/dist/bundler/index.warning.d.ts.map +0 -1
  578. package/dist/chunk-253FBVD4.cjs +0 -1303
  579. package/dist/chunk-253FBVD4.cjs.map +0 -1
  580. package/dist/chunk-2B3VLGTH.js +0 -87
  581. package/dist/chunk-2B3VLGTH.js.map +0 -1
  582. package/dist/chunk-34ZCWSUA.js.map +0 -1
  583. package/dist/chunk-3HXBPDKN.js +0 -105
  584. package/dist/chunk-3JX2Y3WH.cjs.map +0 -1
  585. package/dist/chunk-3VXXCPKX.js.map +0 -1
  586. package/dist/chunk-4R2TBRS7.cjs +0 -191
  587. package/dist/chunk-4R2TBRS7.cjs.map +0 -1
  588. package/dist/chunk-5NTO7S5I.cjs.map +0 -1
  589. package/dist/chunk-6C7VGVK4.js +0 -267
  590. package/dist/chunk-6C7VGVK4.js.map +0 -1
  591. package/dist/chunk-6KOL2B3A.cjs +0 -75
  592. package/dist/chunk-6KOL2B3A.cjs.map +0 -1
  593. package/dist/chunk-6TEQIYXV.cjs.map +0 -1
  594. package/dist/chunk-6VOPKVYH.cjs +0 -57
  595. package/dist/chunk-6VOPKVYH.cjs.map +0 -1
  596. package/dist/chunk-77JHIM4E.cjs.map +0 -1
  597. package/dist/chunk-7J3XX4AO.cjs.map +0 -1
  598. package/dist/chunk-A5KDVZDL.cjs.map +0 -1
  599. package/dist/chunk-ABZOBBLL.cjs.map +0 -1
  600. package/dist/chunk-AQGLVU53.cjs +0 -603
  601. package/dist/chunk-AQGLVU53.cjs.map +0 -1
  602. package/dist/chunk-BLUDYAPI.js +0 -596
  603. package/dist/chunk-BLUDYAPI.js.map +0 -1
  604. package/dist/chunk-BWGXM3D4.js.map +0 -1
  605. package/dist/chunk-C7OVZMPW.cjs +0 -91
  606. package/dist/chunk-C7OVZMPW.cjs.map +0 -1
  607. package/dist/chunk-DMBN72QF.cjs +0 -39
  608. package/dist/chunk-DMBN72QF.cjs.map +0 -1
  609. package/dist/chunk-DTTOVV72.js +0 -2880
  610. package/dist/chunk-DTTOVV72.js.map +0 -1
  611. package/dist/chunk-E3PG7G6E.js.map +0 -1
  612. package/dist/chunk-EBVYYC2Q.cjs +0 -111
  613. package/dist/chunk-FHVFGVIO.js.map +0 -1
  614. package/dist/chunk-GB5BIA4V.js +0 -167
  615. package/dist/chunk-GB5BIA4V.js.map +0 -1
  616. package/dist/chunk-HEQTUMUA.cjs +0 -271
  617. package/dist/chunk-HEQTUMUA.cjs.map +0 -1
  618. package/dist/chunk-HF3GZRFP.cjs +0 -9
  619. package/dist/chunk-HF3GZRFP.cjs.map +0 -1
  620. package/dist/chunk-JVV5LREI.js +0 -431
  621. package/dist/chunk-JVV5LREI.js.map +0 -1
  622. package/dist/chunk-KAEQISOW.js.map +0 -1
  623. package/dist/chunk-KDX3ZMQ2.js +0 -12
  624. package/dist/chunk-KDX3ZMQ2.js.map +0 -1
  625. package/dist/chunk-LG5B3KIW.js +0 -1215
  626. package/dist/chunk-LG5B3KIW.js.map +0 -1
  627. package/dist/chunk-LZUSZT7R.cjs +0 -170
  628. package/dist/chunk-LZUSZT7R.cjs.map +0 -1
  629. package/dist/chunk-MCASUJWY.cjs.map +0 -1
  630. package/dist/chunk-MJMID7LX.cjs.map +0 -1
  631. package/dist/chunk-MKCC5K77.js +0 -90
  632. package/dist/chunk-MKCC5K77.js.map +0 -1
  633. package/dist/chunk-NPNGPMT2.js +0 -39
  634. package/dist/chunk-NPNGPMT2.js.map +0 -1
  635. package/dist/chunk-NR77P3TK.js.map +0 -1
  636. package/dist/chunk-NUAURT4I.cjs +0 -82
  637. package/dist/chunk-NUAURT4I.cjs.map +0 -1
  638. package/dist/chunk-OIT3PCWA.js +0 -72
  639. package/dist/chunk-OIT3PCWA.js.map +0 -1
  640. package/dist/chunk-P35FNLTQ.cjs +0 -2936
  641. package/dist/chunk-P35FNLTQ.cjs.map +0 -1
  642. package/dist/chunk-PFXXH2RP.js.map +0 -1
  643. package/dist/chunk-PZUZNPFM.js.map +0 -1
  644. package/dist/chunk-QFF5JUKT.cjs.map +0 -1
  645. package/dist/chunk-RKXWLG33.js +0 -7
  646. package/dist/chunk-RKXWLG33.js.map +0 -1
  647. package/dist/chunk-ROS5CMJS.cjs.map +0 -1
  648. package/dist/chunk-SJMKDSRF.js +0 -179
  649. package/dist/chunk-SJMKDSRF.js.map +0 -1
  650. package/dist/chunk-SSULK22X.cjs +0 -14
  651. package/dist/chunk-SSULK22X.cjs.map +0 -1
  652. package/dist/chunk-TSNDVBUU.cjs.map +0 -1
  653. package/dist/chunk-TTELJD4F.js.map +0 -1
  654. package/dist/chunk-TX4TTPYJ.cjs +0 -436
  655. package/dist/chunk-TX4TTPYJ.cjs.map +0 -1
  656. package/dist/chunk-UXG7PYML.js.map +0 -1
  657. package/dist/chunk-UZKIGB7M.cjs.map +0 -1
  658. package/dist/chunk-VF676YCO.cjs +0 -150
  659. package/dist/chunk-VF676YCO.cjs.map +0 -1
  660. package/dist/chunk-VQASQG5D.js +0 -55
  661. package/dist/chunk-VQASQG5D.js.map +0 -1
  662. package/dist/chunk-WBAXXG34.cjs.map +0 -1
  663. package/dist/chunk-WCHE6FJ7.js.map +0 -1
  664. package/dist/chunk-WM4RO23J.js +0 -145
  665. package/dist/chunk-WM4RO23J.js.map +0 -1
  666. package/dist/chunk-Z4RIRDU3.js.map +0 -1
  667. package/dist/chunk-ZABG3SZ2.cjs +0 -93
  668. package/dist/chunk-ZABG3SZ2.cjs.map +0 -1
  669. package/dist/chunk-ZISECZZO.js +0 -72
  670. package/dist/chunk-ZISECZZO.js.map +0 -1
  671. package/dist/chunk-ZMELUU72.js.map +0 -1
  672. package/dist/deployer/index.warning.d.ts +0 -9
  673. package/dist/deployer/index.warning.d.ts.map +0 -1
  674. package/dist/eval/evaluation.d.ts +0 -14
  675. package/dist/eval/evaluation.d.ts.map +0 -1
  676. package/dist/eval/index.cjs +0 -16
  677. package/dist/eval/index.d.ts +0 -4
  678. package/dist/eval/index.d.ts.map +0 -1
  679. package/dist/eval/index.js +0 -3
  680. package/dist/eval/metric.d.ts +0 -8
  681. package/dist/eval/metric.d.ts.map +0 -1
  682. package/dist/eval/types.d.ts +0 -9
  683. package/dist/eval/types.d.ts.map +0 -1
  684. package/dist/integration/index.warning.d.ts +0 -3
  685. package/dist/integration/index.warning.d.ts.map +0 -1
  686. package/dist/integration/integration.warning.d.ts +0 -5
  687. package/dist/integration/integration.warning.d.ts.map +0 -1
  688. package/dist/integration/openapi-toolset.warning.d.ts +0 -5
  689. package/dist/integration/openapi-toolset.warning.d.ts.map +0 -1
  690. package/dist/loop/telemetry/index.d.ts +0 -36
  691. package/dist/loop/telemetry/index.d.ts.map +0 -1
  692. package/dist/loop/telemetry/noop.d.ts +0 -3
  693. package/dist/loop/telemetry/noop.d.ts.map +0 -1
  694. package/dist/loop/test-utils/mockTracer.d.ts +0 -47
  695. package/dist/loop/test-utils/mockTracer.d.ts.map +0 -1
  696. package/dist/loop/test-utils/telemetry.d.ts +0 -6
  697. package/dist/loop/test-utils/telemetry.d.ts.map +0 -1
  698. package/dist/memory/index.warning.d.ts +0 -6
  699. package/dist/memory/index.warning.d.ts.map +0 -1
  700. package/dist/models-dev-4VGIWYS3.js +0 -3
  701. package/dist/models-dev-AXZASLL2.cjs +0 -12
  702. package/dist/netlify-TX6V7SJJ.cjs +0 -12
  703. package/dist/netlify-VJXBII33.js +0 -3
  704. package/dist/relevance/cohere/index.d.ts +0 -9
  705. package/dist/relevance/cohere/index.d.ts.map +0 -1
  706. package/dist/runtime-context/index.cjs +0 -12
  707. package/dist/runtime-context/index.js +0 -3
  708. package/dist/scores/base.d.ts.map +0 -1
  709. package/dist/scores/base.test-utils.d.ts.map +0 -1
  710. package/dist/scores/hooks.d.ts.map +0 -1
  711. package/dist/scores/index.cjs +0 -37
  712. package/dist/scores/index.cjs.map +0 -1
  713. package/dist/scores/index.d.ts +0 -4
  714. package/dist/scores/index.d.ts.map +0 -1
  715. package/dist/scores/index.js +0 -4
  716. package/dist/scores/index.js.map +0 -1
  717. package/dist/scores/run-experiment/index.d.ts.map +0 -1
  718. package/dist/scores/run-experiment/scorerAccumulator.d.ts.map +0 -1
  719. package/dist/scores/scoreTraces/index.cjs.map +0 -1
  720. package/dist/scores/scoreTraces/index.d.ts.map +0 -1
  721. package/dist/scores/scoreTraces/index.js.map +0 -1
  722. package/dist/scores/scoreTraces/scoreTraces.d.ts.map +0 -1
  723. package/dist/scores/scoreTraces/scoreTracesWorkflow.d.ts.map +0 -1
  724. package/dist/scores/scoreTraces/utils.d.ts.map +0 -1
  725. package/dist/scores/types.d.ts.map +0 -1
  726. package/dist/storage/base.warning.d.ts +0 -8
  727. package/dist/storage/base.warning.d.ts.map +0 -1
  728. package/dist/storage/domains/legacy-evals/base.d.ts +0 -13
  729. package/dist/storage/domains/legacy-evals/base.d.ts.map +0 -1
  730. package/dist/storage/domains/legacy-evals/index.d.ts +0 -2
  731. package/dist/storage/domains/legacy-evals/index.d.ts.map +0 -1
  732. package/dist/storage/domains/legacy-evals/inmemory.d.ts +0 -17
  733. package/dist/storage/domains/legacy-evals/inmemory.d.ts.map +0 -1
  734. package/dist/storage/domains/traces/base.d.ts +0 -14
  735. package/dist/storage/domains/traces/base.d.ts.map +0 -1
  736. package/dist/storage/domains/traces/index.d.ts +0 -3
  737. package/dist/storage/domains/traces/index.d.ts.map +0 -1
  738. package/dist/storage/domains/traces/inmemory.d.ts +0 -22
  739. package/dist/storage/domains/traces/inmemory.d.ts.map +0 -1
  740. package/dist/storage/index.warning.d.ts +0 -3
  741. package/dist/storage/index.warning.d.ts.map +0 -1
  742. package/dist/telemetry/composite-exporter.d.ts +0 -10
  743. package/dist/telemetry/composite-exporter.d.ts.map +0 -1
  744. package/dist/telemetry/index.cjs +0 -32
  745. package/dist/telemetry/index.cjs.map +0 -1
  746. package/dist/telemetry/index.d.ts +0 -6
  747. package/dist/telemetry/index.d.ts.map +0 -1
  748. package/dist/telemetry/index.js +0 -3
  749. package/dist/telemetry/index.js.map +0 -1
  750. package/dist/telemetry/otel-vendor.cjs +0 -105
  751. package/dist/telemetry/otel-vendor.cjs.map +0 -1
  752. package/dist/telemetry/otel-vendor.d.ts +0 -11
  753. package/dist/telemetry/otel-vendor.d.ts.map +0 -1
  754. package/dist/telemetry/otel-vendor.js +0 -59
  755. package/dist/telemetry/otel-vendor.js.map +0 -1
  756. package/dist/telemetry/storage-exporter.d.ts +0 -21
  757. package/dist/telemetry/storage-exporter.d.ts.map +0 -1
  758. package/dist/telemetry/telemetry.d.ts +0 -59
  759. package/dist/telemetry/telemetry.d.ts.map +0 -1
  760. package/dist/telemetry/telemetry.decorators.d.ts +0 -15
  761. package/dist/telemetry/telemetry.decorators.d.ts.map +0 -1
  762. package/dist/telemetry/types.d.ts +0 -74
  763. package/dist/telemetry/types.d.ts.map +0 -1
  764. package/dist/telemetry/utility.d.ts +0 -15
  765. package/dist/telemetry/utility.d.ts.map +0 -1
  766. package/dist/tools/index.warning.d.ts +0 -8
  767. package/dist/tools/index.warning.d.ts.map +0 -1
  768. package/dist/tts/index.warning.d.ts +0 -7
  769. package/dist/tts/index.warning.d.ts.map +0 -1
  770. package/dist/vector/index.warning.d.ts +0 -6
  771. package/dist/vector/index.warning.d.ts.map +0 -1
  772. package/dist/workflows/index.warning.d.ts +0 -6
  773. package/dist/workflows/index.warning.d.ts.map +0 -1
  774. package/dist/workflows/legacy/index.cjs +0 -92
  775. package/dist/workflows/legacy/index.cjs.map +0 -1
  776. package/dist/workflows/legacy/index.d.ts +0 -5
  777. package/dist/workflows/legacy/index.d.ts.map +0 -1
  778. package/dist/workflows/legacy/index.js +0 -3
  779. package/dist/workflows/legacy/index.js.map +0 -1
  780. package/dist/workflows/legacy/machine.d.ts +0 -386
  781. package/dist/workflows/legacy/machine.d.ts.map +0 -1
  782. package/dist/workflows/legacy/step.d.ts +0 -15
  783. package/dist/workflows/legacy/step.d.ts.map +0 -1
  784. package/dist/workflows/legacy/types.d.ts +0 -397
  785. package/dist/workflows/legacy/types.d.ts.map +0 -1
  786. package/dist/workflows/legacy/utils.d.ts +0 -68
  787. package/dist/workflows/legacy/utils.d.ts.map +0 -1
  788. package/dist/workflows/legacy/workflow-instance.d.ts +0 -97
  789. package/dist/workflows/legacy/workflow-instance.d.ts.map +0 -1
  790. package/dist/workflows/legacy/workflow.d.ts +0 -109
  791. package/dist/workflows/legacy/workflow.d.ts.map +0 -1
  792. package/dist/workflows/workflow.warning.d.ts +0 -9
  793. package/dist/workflows/workflow.warning.d.ts.map +0 -1
  794. package/eval.d.ts +0 -1
  795. package/runtime-context.d.ts +0 -1
  796. package/scores/scoreTraces.d.ts +0 -1
  797. package/scores.d.ts +0 -1
  798. package/telemetry/otel-vendor.d.ts +0 -1
  799. package/telemetry.d.ts +0 -1
  800. package/workflows/legacy.d.ts +0 -1
  801. /package/dist/agent/{input-processor → message-list}/index.cjs.map +0 -0
  802. /package/dist/agent/{input-processor → message-list}/index.js.map +0 -0
  803. /package/dist/{ai-tracing → evals}/index.cjs.map +0 -0
  804. /package/dist/{ai-tracing → evals}/index.js.map +0 -0
  805. /package/dist/{scores/run-experiment → evals/run}/scorerAccumulator.d.ts +0 -0
  806. /package/dist/{scores → evals}/scoreTraces/index.d.ts +0 -0
  807. /package/dist/{eval → observability}/index.cjs.map +0 -0
  808. /package/dist/{eval → observability}/index.js.map +0 -0
  809. /package/dist/{runtime-context → request-context}/index.cjs.map +0 -0
  810. /package/dist/{runtime-context → request-context}/index.js.map +0 -0
@@ -1,2880 +0,0 @@
1
- import { RuntimeContext } from './chunk-HLRWYUFN.js';
2
- import { MastraError } from './chunk-PZUZNPFM.js';
3
- import { ToolStream } from './chunk-HGNRQ3OG.js';
4
- import { isVercelTool, validateToolInput } from './chunk-WM4RO23J.js';
5
- import { MastraBase } from './chunk-VQASQG5D.js';
6
- import { ConsoleLogger, LogLevel, RegisteredLogger } from './chunk-UXG7PYML.js';
7
- import { createHash } from 'crypto';
8
- import jsonSchemaToZod from 'json-schema-to-zod';
9
- import { z } from 'zod';
10
- import { convertZodSchemaToAISDKSchema, OpenAIReasoningSchemaCompatLayer, OpenAISchemaCompatLayer, GoogleSchemaCompatLayer, AnthropicSchemaCompatLayer, DeepSeekSchemaCompatLayer, MetaSchemaCompatLayer, applyCompatLayer } from '@mastra/schema-compat';
11
- import { TransformStream } from 'stream/web';
12
-
13
- // src/ai-tracing/types.ts
14
- var AISpanType = /* @__PURE__ */ ((AISpanType2) => {
15
- AISpanType2["AGENT_RUN"] = "agent_run";
16
- AISpanType2["GENERIC"] = "generic";
17
- AISpanType2["MODEL_GENERATION"] = "model_generation";
18
- AISpanType2["MODEL_STEP"] = "model_step";
19
- AISpanType2["MODEL_CHUNK"] = "model_chunk";
20
- AISpanType2["MCP_TOOL_CALL"] = "mcp_tool_call";
21
- AISpanType2["PROCESSOR_RUN"] = "processor_run";
22
- AISpanType2["TOOL_CALL"] = "tool_call";
23
- AISpanType2["WORKFLOW_RUN"] = "workflow_run";
24
- AISpanType2["WORKFLOW_STEP"] = "workflow_step";
25
- AISpanType2["WORKFLOW_CONDITIONAL"] = "workflow_conditional";
26
- AISpanType2["WORKFLOW_CONDITIONAL_EVAL"] = "workflow_conditional_eval";
27
- AISpanType2["WORKFLOW_PARALLEL"] = "workflow_parallel";
28
- AISpanType2["WORKFLOW_LOOP"] = "workflow_loop";
29
- AISpanType2["WORKFLOW_SLEEP"] = "workflow_sleep";
30
- AISpanType2["WORKFLOW_WAIT_EVENT"] = "workflow_wait_event";
31
- return AISpanType2;
32
- })(AISpanType || {});
33
- var InternalSpans = /* @__PURE__ */ ((InternalSpans2) => {
34
- InternalSpans2[InternalSpans2["NONE"] = 0] = "NONE";
35
- InternalSpans2[InternalSpans2["WORKFLOW"] = 1] = "WORKFLOW";
36
- InternalSpans2[InternalSpans2["AGENT"] = 2] = "AGENT";
37
- InternalSpans2[InternalSpans2["TOOL"] = 4] = "TOOL";
38
- InternalSpans2[InternalSpans2["MODEL"] = 8] = "MODEL";
39
- InternalSpans2[InternalSpans2["ALL"] = 15] = "ALL";
40
- return InternalSpans2;
41
- })(InternalSpans || {});
42
- var SamplingStrategyType = /* @__PURE__ */ ((SamplingStrategyType2) => {
43
- SamplingStrategyType2["ALWAYS"] = "always";
44
- SamplingStrategyType2["NEVER"] = "never";
45
- SamplingStrategyType2["RATIO"] = "ratio";
46
- SamplingStrategyType2["CUSTOM"] = "custom";
47
- return SamplingStrategyType2;
48
- })(SamplingStrategyType || {});
49
- var AITracingEventType = /* @__PURE__ */ ((AITracingEventType2) => {
50
- AITracingEventType2["SPAN_STARTED"] = "span_started";
51
- AITracingEventType2["SPAN_UPDATED"] = "span_updated";
52
- AITracingEventType2["SPAN_ENDED"] = "span_ended";
53
- return AITracingEventType2;
54
- })(AITracingEventType || {});
55
-
56
- // src/ai-tracing/spans/base.ts
57
- function isSpanInternal(spanType, flags) {
58
- if (flags === void 0 || flags === 0 /* NONE */) {
59
- return false;
60
- }
61
- switch (spanType) {
62
- // Workflow-related spans
63
- case "workflow_run" /* WORKFLOW_RUN */:
64
- case "workflow_step" /* WORKFLOW_STEP */:
65
- case "workflow_conditional" /* WORKFLOW_CONDITIONAL */:
66
- case "workflow_conditional_eval" /* WORKFLOW_CONDITIONAL_EVAL */:
67
- case "workflow_parallel" /* WORKFLOW_PARALLEL */:
68
- case "workflow_loop" /* WORKFLOW_LOOP */:
69
- case "workflow_sleep" /* WORKFLOW_SLEEP */:
70
- case "workflow_wait_event" /* WORKFLOW_WAIT_EVENT */:
71
- return (flags & 1 /* WORKFLOW */) !== 0;
72
- // Agent-related spans
73
- case "agent_run" /* AGENT_RUN */:
74
- return (flags & 2 /* AGENT */) !== 0;
75
- // Tool-related spans
76
- case "tool_call" /* TOOL_CALL */:
77
- case "mcp_tool_call" /* MCP_TOOL_CALL */:
78
- return (flags & 4 /* TOOL */) !== 0;
79
- // Model-related spans
80
- case "model_generation" /* MODEL_GENERATION */:
81
- case "model_step" /* MODEL_STEP */:
82
- case "model_chunk" /* MODEL_CHUNK */:
83
- return (flags & 8 /* MODEL */) !== 0;
84
- // Default: never internal
85
- default:
86
- return false;
87
- }
88
- }
89
- var BaseAISpan = class {
90
- name;
91
- type;
92
- attributes;
93
- parent;
94
- startTime;
95
- endTime;
96
- isEvent;
97
- isInternal;
98
- aiTracing;
99
- input;
100
- output;
101
- errorInfo;
102
- metadata;
103
- traceState;
104
- /** Parent span ID (for root spans that are children of external spans) */
105
- parentSpanId;
106
- constructor(options, aiTracing) {
107
- this.name = options.name;
108
- this.type = options.type;
109
- this.attributes = deepClean(options.attributes) || {};
110
- this.metadata = deepClean(options.metadata);
111
- this.parent = options.parent;
112
- this.startTime = /* @__PURE__ */ new Date();
113
- this.aiTracing = aiTracing;
114
- this.isEvent = options.isEvent ?? false;
115
- this.isInternal = isSpanInternal(this.type, options.tracingPolicy?.internal);
116
- this.traceState = options.traceState;
117
- if (this.isEvent) {
118
- this.output = deepClean(options.output);
119
- } else {
120
- this.input = deepClean(options.input);
121
- }
122
- }
123
- createChildSpan(options) {
124
- return this.aiTracing.startSpan({ ...options, parent: this, isEvent: false });
125
- }
126
- createEventSpan(options) {
127
- return this.aiTracing.startSpan({ ...options, parent: this, isEvent: true });
128
- }
129
- /** Returns `TRUE` if the span is the root span of a trace */
130
- get isRootSpan() {
131
- return !this.parent;
132
- }
133
- /** Get the closest parent spanId that isn't an internal span */
134
- getParentSpanId(includeInternalSpans) {
135
- if (!this.parent) {
136
- return this.parentSpanId;
137
- }
138
- if (includeInternalSpans) return this.parent.id;
139
- if (this.parent.isInternal) return this.parent.getParentSpanId(includeInternalSpans);
140
- return this.parent.id;
141
- }
142
- /** Find the closest parent span of a specific type by walking up the parent chain */
143
- findParent(spanType) {
144
- let current = this.parent;
145
- while (current) {
146
- if (current.type === spanType) {
147
- return current;
148
- }
149
- current = current.parent;
150
- }
151
- return void 0;
152
- }
153
- /** Returns a lightweight span ready for export */
154
- exportSpan(includeInternalSpans) {
155
- return {
156
- id: this.id,
157
- traceId: this.traceId,
158
- name: this.name,
159
- type: this.type,
160
- attributes: this.attributes,
161
- metadata: this.metadata,
162
- startTime: this.startTime,
163
- endTime: this.endTime,
164
- input: this.input,
165
- output: this.output,
166
- errorInfo: this.errorInfo,
167
- isEvent: this.isEvent,
168
- isRootSpan: this.isRootSpan,
169
- parentSpanId: this.getParentSpanId(includeInternalSpans)
170
- };
171
- }
172
- };
173
- var DEFAULT_KEYS_TO_STRIP = /* @__PURE__ */ new Set([
174
- "logger",
175
- "experimental_providerMetadata",
176
- "providerMetadata",
177
- "steps",
178
- "tracingContext"
179
- ]);
180
- function deepClean(value, options = {}, _seen = /* @__PURE__ */ new WeakSet(), _depth = 0) {
181
- const { keysToStrip = DEFAULT_KEYS_TO_STRIP, maxDepth = 10 } = options;
182
- if (_depth > maxDepth) {
183
- return "[MaxDepth]";
184
- }
185
- if (value === null || typeof value !== "object") {
186
- try {
187
- JSON.stringify(value);
188
- return value;
189
- } catch (error) {
190
- return `[${error instanceof Error ? error.message : String(error)}]`;
191
- }
192
- }
193
- if (_seen.has(value)) {
194
- return "[Circular]";
195
- }
196
- _seen.add(value);
197
- if (Array.isArray(value)) {
198
- return value.map((item) => deepClean(item, options, _seen, _depth + 1));
199
- }
200
- const cleaned = {};
201
- for (const [key, val] of Object.entries(value)) {
202
- if (keysToStrip.has(key)) {
203
- continue;
204
- }
205
- try {
206
- cleaned[key] = deepClean(val, options, _seen, _depth + 1);
207
- } catch (error) {
208
- cleaned[key] = `[${error instanceof Error ? error.message : String(error)}]`;
209
- }
210
- }
211
- return cleaned;
212
- }
213
-
214
- // src/ai-tracing/spans/default.ts
215
- var DefaultAISpan = class extends BaseAISpan {
216
- id;
217
- traceId;
218
- constructor(options, aiTracing) {
219
- super(options, aiTracing);
220
- this.id = generateSpanId();
221
- if (options.parent) {
222
- this.traceId = options.parent.traceId;
223
- } else if (options.traceId) {
224
- if (isValidTraceId(options.traceId)) {
225
- this.traceId = options.traceId;
226
- } else {
227
- console.error(
228
- `[Mastra Tracing] Invalid traceId: must be 1-32 hexadecimal characters, got "${options.traceId}". Generating new trace ID.`
229
- );
230
- this.traceId = generateTraceId();
231
- }
232
- } else {
233
- this.traceId = generateTraceId();
234
- }
235
- if (!options.parent && options.parentSpanId) {
236
- if (isValidSpanId(options.parentSpanId)) {
237
- this.parentSpanId = options.parentSpanId;
238
- } else {
239
- console.error(
240
- `[Mastra Tracing] Invalid parentSpanId: must be 1-16 hexadecimal characters, got "${options.parentSpanId}". Ignoring parent span ID.`
241
- );
242
- }
243
- }
244
- }
245
- end(options) {
246
- if (this.isEvent) {
247
- return;
248
- }
249
- this.endTime = /* @__PURE__ */ new Date();
250
- if (options?.output !== void 0) {
251
- this.output = deepClean(options.output);
252
- }
253
- if (options?.attributes) {
254
- this.attributes = { ...this.attributes, ...deepClean(options.attributes) };
255
- }
256
- if (options?.metadata) {
257
- this.metadata = { ...this.metadata, ...deepClean(options.metadata) };
258
- }
259
- }
260
- error(options) {
261
- if (this.isEvent) {
262
- return;
263
- }
264
- const { error, endSpan = true, attributes, metadata } = options;
265
- this.errorInfo = error instanceof MastraError ? {
266
- id: error.id,
267
- details: error.details,
268
- category: error.category,
269
- domain: error.domain,
270
- message: error.message
271
- } : {
272
- message: error.message
273
- };
274
- if (attributes) {
275
- this.attributes = { ...this.attributes, ...deepClean(attributes) };
276
- }
277
- if (metadata) {
278
- this.metadata = { ...this.metadata, ...deepClean(metadata) };
279
- }
280
- if (endSpan) {
281
- this.end();
282
- } else {
283
- this.update({});
284
- }
285
- }
286
- update(options) {
287
- if (this.isEvent) {
288
- return;
289
- }
290
- if (options.input !== void 0) {
291
- this.input = deepClean(options.input);
292
- }
293
- if (options.output !== void 0) {
294
- this.output = deepClean(options.output);
295
- }
296
- if (options.attributes) {
297
- this.attributes = { ...this.attributes, ...deepClean(options.attributes) };
298
- }
299
- if (options.metadata) {
300
- this.metadata = { ...this.metadata, ...deepClean(options.metadata) };
301
- }
302
- }
303
- get isValid() {
304
- return true;
305
- }
306
- async export() {
307
- return JSON.stringify({
308
- spanId: this.id,
309
- traceId: this.traceId,
310
- startTime: this.startTime,
311
- endTime: this.endTime,
312
- attributes: this.attributes,
313
- metadata: this.metadata
314
- });
315
- }
316
- };
317
- function generateSpanId() {
318
- const bytes = new Uint8Array(8);
319
- if (typeof crypto !== "undefined" && crypto.getRandomValues) {
320
- crypto.getRandomValues(bytes);
321
- } else {
322
- for (let i = 0; i < 8; i++) {
323
- bytes[i] = Math.floor(Math.random() * 256);
324
- }
325
- }
326
- return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
327
- }
328
- function generateTraceId() {
329
- const bytes = new Uint8Array(16);
330
- if (typeof crypto !== "undefined" && crypto.getRandomValues) {
331
- crypto.getRandomValues(bytes);
332
- } else {
333
- for (let i = 0; i < 16; i++) {
334
- bytes[i] = Math.floor(Math.random() * 256);
335
- }
336
- }
337
- return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
338
- }
339
- function isValidTraceId(traceId) {
340
- return /^[0-9a-f]{1,32}$/i.test(traceId);
341
- }
342
- function isValidSpanId(spanId) {
343
- return /^[0-9a-f]{1,16}$/i.test(spanId);
344
- }
345
-
346
- // src/ai-tracing/spans/no-op.ts
347
- var NoOpAISpan = class extends BaseAISpan {
348
- id;
349
- traceId;
350
- constructor(options, aiTracing) {
351
- super(options, aiTracing);
352
- this.id = "no-op";
353
- this.traceId = "no-op-trace";
354
- }
355
- end(_options) {
356
- }
357
- error(_options) {
358
- }
359
- update(_options) {
360
- }
361
- get isValid() {
362
- return false;
363
- }
364
- };
365
-
366
- // src/ai-tracing/exporters/base.ts
367
- var BaseExporter = class {
368
- /** Mastra logger instance */
369
- logger;
370
- /** Whether this exporter is disabled */
371
- isDisabled = false;
372
- /**
373
- * Initialize the base exporter with logger
374
- */
375
- constructor(config = {}) {
376
- const logLevel = this.resolveLogLevel(config.logLevel);
377
- this.logger = config.logger ?? new ConsoleLogger({ level: logLevel, name: this.constructor.name });
378
- }
379
- /**
380
- * Set the logger for the exporter (called by Mastra/AITracing during initialization)
381
- */
382
- __setLogger(logger) {
383
- this.logger = logger;
384
- this.logger.debug(`Logger updated for exporter [name=${this.name}]`);
385
- }
386
- /**
387
- * Convert string log level to LogLevel enum
388
- */
389
- resolveLogLevel(logLevel) {
390
- if (!logLevel) {
391
- return LogLevel.INFO;
392
- }
393
- if (typeof logLevel === "number") {
394
- return logLevel;
395
- }
396
- const logLevelMap = {
397
- debug: LogLevel.DEBUG,
398
- info: LogLevel.INFO,
399
- warn: LogLevel.WARN,
400
- error: LogLevel.ERROR
401
- };
402
- return logLevelMap[logLevel] ?? LogLevel.INFO;
403
- }
404
- /**
405
- * Mark the exporter as disabled and log a message
406
- *
407
- * @param reason - Reason why the exporter is disabled
408
- */
409
- setDisabled(reason) {
410
- this.isDisabled = true;
411
- this.logger.warn(`${this.name} disabled: ${reason}`);
412
- }
413
- /**
414
- * Export a tracing event
415
- *
416
- * This method checks if the exporter is disabled before calling _exportEvent.
417
- * Subclasses should implement _exportEvent instead of overriding this method.
418
- */
419
- async exportEvent(event) {
420
- if (this.isDisabled) {
421
- return;
422
- }
423
- await this._exportEvent(event);
424
- }
425
- /**
426
- * Shutdown the exporter and clean up resources
427
- *
428
- * Default implementation just logs. Override to add custom cleanup.
429
- */
430
- async shutdown() {
431
- this.logger.info(`${this.name} shutdown complete`);
432
- }
433
- };
434
- var CoreToolBuilder = class extends MastraBase {
435
- originalTool;
436
- options;
437
- logType;
438
- constructor(input) {
439
- super({ name: "CoreToolBuilder" });
440
- this.originalTool = input.originalTool;
441
- this.options = input.options;
442
- this.logType = input.logType;
443
- }
444
- // Helper to get parameters based on tool type
445
- getParameters = () => {
446
- if (isVercelTool(this.originalTool)) {
447
- let schema2 = this.originalTool.parameters ?? ("inputSchema" in this.originalTool ? this.originalTool.inputSchema : void 0) ?? z.object({});
448
- if (typeof schema2 === "function") {
449
- schema2 = schema2();
450
- }
451
- return schema2;
452
- }
453
- let schema = this.originalTool.inputSchema ?? z.object({});
454
- if (typeof schema === "function") {
455
- schema = schema();
456
- }
457
- return schema;
458
- };
459
- getOutputSchema = () => {
460
- if ("outputSchema" in this.originalTool) {
461
- let schema = this.originalTool.outputSchema;
462
- if (typeof schema === "function") {
463
- schema = schema();
464
- }
465
- return schema;
466
- }
467
- return null;
468
- };
469
- // For provider-defined tools, we need to include all required properties
470
- buildProviderTool(tool) {
471
- if ("type" in tool && tool.type === "provider-defined" && "id" in tool && typeof tool.id === "string" && tool.id.includes(".")) {
472
- const parameters = this.getParameters();
473
- const outputSchema = this.getOutputSchema();
474
- return {
475
- type: "provider-defined",
476
- id: tool.id,
477
- args: "args" in this.originalTool ? this.originalTool.args : {},
478
- description: tool.description,
479
- parameters: parameters.jsonSchema ? parameters : convertZodSchemaToAISDKSchema(parameters),
480
- ...outputSchema ? { outputSchema: outputSchema.jsonSchema ? outputSchema : convertZodSchemaToAISDKSchema(outputSchema) } : {},
481
- execute: this.originalTool.execute ? this.createExecute(
482
- this.originalTool,
483
- { ...this.options, description: this.originalTool.description },
484
- this.logType
485
- ) : void 0
486
- };
487
- }
488
- return void 0;
489
- }
490
- createLogMessageOptions({ agentName, toolName, type }) {
491
- if (!agentName) {
492
- return {
493
- start: `Executing tool ${toolName}`,
494
- error: `Failed tool execution`
495
- };
496
- }
497
- const prefix = `[Agent:${agentName}]`;
498
- const toolType = type === "toolset" ? "toolset" : "tool";
499
- return {
500
- start: `${prefix} - Executing ${toolType} ${toolName}`,
501
- error: `${prefix} - Failed ${toolType} execution`
502
- };
503
- }
504
- createExecute(tool, options, logType, processedSchema) {
505
- const { logger, mastra: _mastra, memory: _memory, runtimeContext, model, ...rest } = options;
506
- const logModelObject = {
507
- modelId: model?.modelId,
508
- provider: model?.provider,
509
- specificationVersion: model?.specificationVersion
510
- };
511
- const { start, error } = this.createLogMessageOptions({
512
- agentName: options.agentName,
513
- toolName: options.name,
514
- type: logType
515
- });
516
- const execFunction = async (args, execOptions) => {
517
- const tracingContext = execOptions.tracingContext || options.tracingContext;
518
- const toolSpan = tracingContext?.currentSpan?.createChildSpan({
519
- type: "tool_call" /* TOOL_CALL */,
520
- name: `tool: '${options.name}'`,
521
- input: args,
522
- attributes: {
523
- toolId: options.name,
524
- toolDescription: options.description,
525
- toolType: logType || "tool"
526
- },
527
- tracingPolicy: options.tracingPolicy
528
- });
529
- try {
530
- let result;
531
- if (isVercelTool(tool)) {
532
- result = await tool?.execute?.(args, execOptions);
533
- } else {
534
- const wrappedMastra = options.mastra ? wrapMastra(options.mastra, { currentSpan: toolSpan }) : options.mastra;
535
- result = await tool?.execute?.(
536
- {
537
- context: args,
538
- threadId: options.threadId,
539
- resourceId: options.resourceId,
540
- mastra: wrappedMastra,
541
- memory: options.memory,
542
- runId: options.runId,
543
- runtimeContext: options.runtimeContext ?? new RuntimeContext(),
544
- writer: new ToolStream(
545
- {
546
- prefix: "tool",
547
- callId: execOptions.toolCallId,
548
- name: options.name,
549
- runId: options.runId
550
- },
551
- options.writableStream || execOptions.writableStream
552
- ),
553
- tracingContext: { currentSpan: toolSpan }
554
- },
555
- execOptions
556
- );
557
- }
558
- toolSpan?.end({ output: result });
559
- return result ?? void 0;
560
- } catch (error2) {
561
- toolSpan?.error({ error: error2 });
562
- throw error2;
563
- }
564
- };
565
- return async (args, execOptions) => {
566
- let logger2 = options.logger || this.logger;
567
- try {
568
- logger2.debug(start, { ...rest, model: logModelObject, args });
569
- const parameters = processedSchema || this.getParameters();
570
- const { data, error: error2 } = validateToolInput(parameters, args, options.name);
571
- if (error2) {
572
- logger2.warn(`Tool input validation failed for '${options.name}'`, {
573
- toolName: options.name,
574
- errors: error2.validationErrors,
575
- args
576
- });
577
- return error2;
578
- }
579
- args = data;
580
- return await new Promise((resolve, reject) => {
581
- setImmediate(async () => {
582
- try {
583
- const result = await execFunction(args, execOptions);
584
- resolve(result);
585
- } catch (err) {
586
- reject(err);
587
- }
588
- });
589
- });
590
- } catch (err) {
591
- const mastraError = new MastraError(
592
- {
593
- id: "TOOL_EXECUTION_FAILED",
594
- domain: "TOOL" /* TOOL */,
595
- category: "USER" /* USER */,
596
- details: {
597
- errorMessage: String(error),
598
- argsJson: JSON.stringify(args),
599
- model: model?.modelId ?? ""
600
- }
601
- },
602
- err
603
- );
604
- logger2.trackException(mastraError);
605
- logger2.error(error, { ...rest, model: logModelObject, error: mastraError, args });
606
- return mastraError;
607
- }
608
- };
609
- }
610
- buildV5() {
611
- const builtTool = this.build();
612
- if (!builtTool.parameters) {
613
- throw new Error("Tool parameters are required");
614
- }
615
- const base = {
616
- ...builtTool,
617
- inputSchema: builtTool.parameters,
618
- onInputStart: "onInputStart" in this.originalTool ? this.originalTool.onInputStart : void 0,
619
- onInputDelta: "onInputDelta" in this.originalTool ? this.originalTool.onInputDelta : void 0,
620
- onInputAvailable: "onInputAvailable" in this.originalTool ? this.originalTool.onInputAvailable : void 0
621
- };
622
- if (builtTool.type === "provider-defined") {
623
- const { execute, parameters, ...rest } = base;
624
- const name = builtTool.id.split(".")[1] || builtTool.id;
625
- return {
626
- ...rest,
627
- type: builtTool.type,
628
- id: builtTool.id,
629
- name,
630
- args: builtTool.args
631
- };
632
- }
633
- return base;
634
- }
635
- build() {
636
- const providerTool = this.buildProviderTool(this.originalTool);
637
- if (providerTool) {
638
- return providerTool;
639
- }
640
- const model = this.options.model;
641
- const schemaCompatLayers = [];
642
- if (model) {
643
- const supportsStructuredOutputs = model.specificationVersion !== "v2" ? model.supportsStructuredOutputs ?? false : false;
644
- const modelInfo = {
645
- modelId: model.modelId,
646
- supportsStructuredOutputs,
647
- provider: model.provider
648
- };
649
- schemaCompatLayers.push(
650
- new OpenAIReasoningSchemaCompatLayer(modelInfo),
651
- new OpenAISchemaCompatLayer(modelInfo),
652
- new GoogleSchemaCompatLayer(modelInfo),
653
- new AnthropicSchemaCompatLayer(modelInfo),
654
- new DeepSeekSchemaCompatLayer(modelInfo),
655
- new MetaSchemaCompatLayer(modelInfo)
656
- );
657
- }
658
- let processedZodSchema;
659
- let processedSchema;
660
- const originalSchema = this.getParameters();
661
- const applicableLayer = schemaCompatLayers.find((layer) => layer.shouldApply());
662
- if (applicableLayer && originalSchema) {
663
- processedZodSchema = applicableLayer.processZodType(originalSchema);
664
- processedSchema = applyCompatLayer({
665
- schema: originalSchema,
666
- compatLayers: schemaCompatLayers,
667
- mode: "aiSdkSchema"
668
- });
669
- } else {
670
- processedZodSchema = originalSchema;
671
- processedSchema = applyCompatLayer({
672
- schema: originalSchema,
673
- compatLayers: schemaCompatLayers,
674
- mode: "aiSdkSchema"
675
- });
676
- }
677
- let processedOutputSchema;
678
- if (this.getOutputSchema()) {
679
- processedOutputSchema = applyCompatLayer({
680
- schema: this.getOutputSchema(),
681
- compatLayers: schemaCompatLayers,
682
- mode: "aiSdkSchema"
683
- });
684
- }
685
- const definition = {
686
- type: "function",
687
- description: this.originalTool.description,
688
- parameters: this.getParameters(),
689
- outputSchema: this.getOutputSchema(),
690
- requireApproval: this.options.requireApproval,
691
- execute: this.originalTool.execute ? this.createExecute(
692
- this.originalTool,
693
- { ...this.options, description: this.originalTool.description },
694
- this.logType,
695
- processedZodSchema
696
- // Pass the processed Zod schema for validation
697
- ) : void 0
698
- };
699
- return {
700
- ...definition,
701
- id: "id" in this.originalTool ? this.originalTool.id : void 0,
702
- parameters: processedSchema,
703
- outputSchema: processedOutputSchema
704
- };
705
- }
706
- };
707
-
708
- // src/utils.ts
709
- var delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
710
- function deepMerge(target, source) {
711
- const output = { ...target };
712
- if (!source) return output;
713
- Object.keys(source).forEach((key) => {
714
- const targetValue = output[key];
715
- const sourceValue = source[key];
716
- if (Array.isArray(targetValue) && Array.isArray(sourceValue)) {
717
- output[key] = sourceValue;
718
- } else if (sourceValue instanceof Object && targetValue instanceof Object && !Array.isArray(sourceValue) && !Array.isArray(targetValue)) {
719
- output[key] = deepMerge(targetValue, sourceValue);
720
- } else if (sourceValue !== void 0) {
721
- output[key] = sourceValue;
722
- }
723
- });
724
- return output;
725
- }
726
- function generateEmptyFromSchema(schema) {
727
- try {
728
- const parsedSchema = JSON.parse(schema);
729
- if (!parsedSchema || parsedSchema.type !== "object" || !parsedSchema.properties) return {};
730
- const obj = {};
731
- const TYPE_DEFAULTS = {
732
- string: "",
733
- array: [],
734
- object: {},
735
- number: 0,
736
- integer: 0,
737
- boolean: false
738
- };
739
- for (const [key, prop] of Object.entries(parsedSchema.properties)) {
740
- obj[key] = TYPE_DEFAULTS[prop.type] ?? null;
741
- }
742
- return obj;
743
- } catch {
744
- return {};
745
- }
746
- }
747
- async function* maskStreamTags(stream, tag, options = {}) {
748
- const { onStart, onEnd, onMask } = options;
749
- const openTag = `<${tag}>`;
750
- const closeTag = `</${tag}>`;
751
- let buffer = "";
752
- let fullContent = "";
753
- let isMasking = false;
754
- let isBuffering = false;
755
- const trimOutsideDelimiter = (text, delimiter, trim) => {
756
- if (!text.includes(delimiter)) {
757
- return text;
758
- }
759
- const parts = text.split(delimiter);
760
- if (trim === `before-start`) {
761
- return `${delimiter}${parts[1]}`;
762
- }
763
- return `${parts[0]}${delimiter}`;
764
- };
765
- const startsWith = (text, pattern) => {
766
- if (pattern.includes(openTag.substring(0, 3))) {
767
- pattern = trimOutsideDelimiter(pattern, `<`, `before-start`);
768
- }
769
- return text.trim().startsWith(pattern.trim());
770
- };
771
- for await (const chunk of stream) {
772
- fullContent += chunk;
773
- if (isBuffering) buffer += chunk;
774
- const chunkHasTag = startsWith(chunk, openTag);
775
- const bufferHasTag = !chunkHasTag && isBuffering && startsWith(openTag, buffer);
776
- let toYieldBeforeMaskedStartTag = ``;
777
- if (!isMasking && (chunkHasTag || bufferHasTag)) {
778
- isMasking = true;
779
- isBuffering = false;
780
- const taggedTextToMask = trimOutsideDelimiter(buffer, `<`, `before-start`);
781
- if (taggedTextToMask !== buffer.trim()) {
782
- toYieldBeforeMaskedStartTag = buffer.replace(taggedTextToMask, ``);
783
- }
784
- buffer = "";
785
- onStart?.();
786
- }
787
- if (!isMasking && !isBuffering && startsWith(openTag, chunk) && chunk.trim() !== "") {
788
- isBuffering = true;
789
- buffer += chunk;
790
- continue;
791
- }
792
- if (isBuffering && buffer && !startsWith(openTag, buffer)) {
793
- yield buffer;
794
- buffer = "";
795
- isBuffering = false;
796
- continue;
797
- }
798
- if (isMasking && fullContent.includes(closeTag)) {
799
- onMask?.(chunk);
800
- onEnd?.();
801
- isMasking = false;
802
- const lastFullContent = fullContent;
803
- fullContent = ``;
804
- const textUntilEndTag = trimOutsideDelimiter(lastFullContent, closeTag, "after-end");
805
- if (textUntilEndTag !== lastFullContent) {
806
- yield lastFullContent.replace(textUntilEndTag, ``);
807
- }
808
- continue;
809
- }
810
- if (isMasking) {
811
- onMask?.(chunk);
812
- if (toYieldBeforeMaskedStartTag) {
813
- yield toYieldBeforeMaskedStartTag;
814
- }
815
- continue;
816
- }
817
- yield chunk;
818
- }
819
- }
820
- function resolveSerializedZodOutput(schema) {
821
- return Function("z", `"use strict";return (${schema});`)(z);
822
- }
823
- function isZodType(value) {
824
- return typeof value === "object" && value !== null && "_def" in value && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
825
- }
826
- function createDeterministicId(input) {
827
- return createHash("sha256").update(input).digest("hex").slice(0, 8);
828
- }
829
- function setVercelToolProperties(tool) {
830
- const inputSchema = "inputSchema" in tool ? tool.inputSchema : convertVercelToolParameters(tool);
831
- const toolId = !("id" in tool) ? tool.description ? `tool-${createDeterministicId(tool.description)}` : `tool-${Math.random().toString(36).substring(2, 9)}` : tool.id;
832
- return {
833
- ...tool,
834
- id: toolId,
835
- inputSchema
836
- };
837
- }
838
- function ensureToolProperties(tools) {
839
- const toolsWithProperties = Object.keys(tools).reduce((acc, key) => {
840
- const tool = tools?.[key];
841
- if (tool) {
842
- if (isVercelTool(tool)) {
843
- acc[key] = setVercelToolProperties(tool);
844
- } else {
845
- acc[key] = tool;
846
- }
847
- }
848
- return acc;
849
- }, {});
850
- return toolsWithProperties;
851
- }
852
- function convertVercelToolParameters(tool) {
853
- let schema = tool.parameters ?? z.object({});
854
- if (typeof schema === "function") {
855
- schema = schema();
856
- }
857
- return isZodType(schema) ? schema : resolveSerializedZodOutput(jsonSchemaToZod(schema));
858
- }
859
- function makeCoreTool(originalTool, options, logType) {
860
- return new CoreToolBuilder({ originalTool, options, logType }).build();
861
- }
862
- function makeCoreToolV5(originalTool, options, logType) {
863
- return new CoreToolBuilder({ originalTool, options, logType }).buildV5();
864
- }
865
- function createMastraProxy({ mastra, logger }) {
866
- return new Proxy(mastra, {
867
- get(target, prop) {
868
- const hasProp = Reflect.has(target, prop);
869
- if (hasProp) {
870
- const value = Reflect.get(target, prop);
871
- const isFunction = typeof value === "function";
872
- if (isFunction) {
873
- return value.bind(target);
874
- }
875
- return value;
876
- }
877
- if (prop === "logger") {
878
- logger.warn(`Please use 'getLogger' instead, logger is deprecated`);
879
- return Reflect.apply(target.getLogger, target, []);
880
- }
881
- if (prop === "telemetry") {
882
- logger.warn(`Please use 'getTelemetry' instead, telemetry is deprecated`);
883
- return Reflect.apply(target.getTelemetry, target, []);
884
- }
885
- if (prop === "storage") {
886
- logger.warn(`Please use 'getStorage' instead, storage is deprecated`);
887
- return Reflect.get(target, "storage");
888
- }
889
- if (prop === "agents") {
890
- logger.warn(`Please use 'getAgents' instead, agents is deprecated`);
891
- return Reflect.apply(target.getAgents, target, []);
892
- }
893
- if (prop === "tts") {
894
- logger.warn(`Please use 'getTTS' instead, tts is deprecated`);
895
- return Reflect.apply(target.getTTS, target, []);
896
- }
897
- if (prop === "vectors") {
898
- logger.warn(`Please use 'getVectors' instead, vectors is deprecated`);
899
- return Reflect.apply(target.getVectors, target, []);
900
- }
901
- if (prop === "memory") {
902
- logger.warn(`Please use 'getMemory' instead, memory is deprecated`);
903
- return Reflect.get(target, "memory");
904
- }
905
- return Reflect.get(target, prop);
906
- }
907
- });
908
- }
909
- function checkEvalStorageFields(traceObject, logger) {
910
- const missingFields = [];
911
- if (!traceObject.input) missingFields.push("input");
912
- if (!traceObject.output) missingFields.push("output");
913
- if (!traceObject.agentName) missingFields.push("agent_name");
914
- if (!traceObject.metricName) missingFields.push("metric_name");
915
- if (!traceObject.instructions) missingFields.push("instructions");
916
- if (!traceObject.globalRunId) missingFields.push("global_run_id");
917
- if (!traceObject.runId) missingFields.push("run_id");
918
- if (missingFields.length > 0) {
919
- if (logger) {
920
- logger.warn("Skipping evaluation storage due to missing required fields", {
921
- missingFields,
922
- runId: traceObject.runId,
923
- agentName: traceObject.agentName
924
- });
925
- } else {
926
- console.warn("Skipping evaluation storage due to missing required fields", {
927
- missingFields,
928
- runId: traceObject.runId,
929
- agentName: traceObject.agentName
930
- });
931
- }
932
- return false;
933
- }
934
- return true;
935
- }
936
- function detectSingleMessageCharacteristics(message) {
937
- if (typeof message === "object" && message !== null && (message.role === "function" || // UI-only role
938
- message.role === "data" || // UI-only role
939
- "toolInvocations" in message || // UI-specific field
940
- "parts" in message || // UI-specific field
941
- "experimental_attachments" in message)) {
942
- return "has-ui-specific-parts";
943
- } else if (typeof message === "object" && message !== null && "content" in message && (Array.isArray(message.content) || // Core messages can have array content
944
- "experimental_providerMetadata" in message || "providerOptions" in message)) {
945
- return "has-core-specific-parts";
946
- } else if (typeof message === "object" && message !== null && "role" in message && "content" in message && typeof message.content === "string" && ["system", "user", "assistant", "tool"].includes(message.role)) {
947
- return "message";
948
- } else {
949
- return "other";
950
- }
951
- }
952
- function isUiMessage(message) {
953
- return detectSingleMessageCharacteristics(message) === `has-ui-specific-parts`;
954
- }
955
- function isCoreMessage(message) {
956
- return [`has-core-specific-parts`, `message`].includes(detectSingleMessageCharacteristics(message));
957
- }
958
- var SQL_IDENTIFIER_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
959
- function parseSqlIdentifier(name, kind = "identifier") {
960
- if (!SQL_IDENTIFIER_PATTERN.test(name) || name.length > 63) {
961
- throw new Error(
962
- `Invalid ${kind}: ${name}. Must start with a letter or underscore, contain only letters, numbers, or underscores, and be at most 63 characters long.`
963
- );
964
- }
965
- return name;
966
- }
967
- function parseFieldKey(key) {
968
- if (!key) throw new Error("Field key cannot be empty");
969
- const segments = key.split(".");
970
- for (const segment of segments) {
971
- if (!SQL_IDENTIFIER_PATTERN.test(segment) || segment.length > 63) {
972
- throw new Error(`Invalid field key segment: ${segment} in ${key}`);
973
- }
974
- }
975
- return key;
976
- }
977
- async function fetchWithRetry(url, options = {}, maxRetries = 3) {
978
- let retryCount = 0;
979
- let lastError = null;
980
- while (retryCount < maxRetries) {
981
- try {
982
- const response = await fetch(url, options);
983
- if (!response.ok) {
984
- throw new Error(`Request failed with status: ${response.status} ${response.statusText}`);
985
- }
986
- return response;
987
- } catch (error) {
988
- lastError = error instanceof Error ? error : new Error(String(error));
989
- retryCount++;
990
- if (retryCount >= maxRetries) {
991
- break;
992
- }
993
- const delay2 = Math.min(1e3 * Math.pow(2, retryCount) * 1e3, 1e4);
994
- await new Promise((resolve) => setTimeout(resolve, delay2));
995
- }
996
- }
997
- throw lastError || new Error("Request failed after multiple retry attempts");
998
- }
999
-
1000
- // src/ai-tracing/exporters/cloud.ts
1001
- var CloudExporter = class extends BaseExporter {
1002
- name = "mastra-cloud-ai-tracing-exporter";
1003
- config;
1004
- buffer;
1005
- flushTimer = null;
1006
- constructor(config = {}) {
1007
- super(config);
1008
- const accessToken = config.accessToken ?? process.env.MASTRA_CLOUD_ACCESS_TOKEN;
1009
- if (!accessToken) {
1010
- this.setDisabled(
1011
- "MASTRA_CLOUD_ACCESS_TOKEN environment variable not set. \u{1F680} Sign up for Mastra Cloud at https://cloud.mastra.ai to see your AI traces online and obtain your access token."
1012
- );
1013
- }
1014
- const endpoint = config.endpoint ?? process.env.MASTRA_CLOUD_AI_TRACES_ENDPOINT ?? "https://api.mastra.ai/ai/spans/publish";
1015
- this.config = {
1016
- logger: this.logger,
1017
- logLevel: config.logLevel ?? LogLevel.INFO,
1018
- maxBatchSize: config.maxBatchSize ?? 1e3,
1019
- maxBatchWaitMs: config.maxBatchWaitMs ?? 5e3,
1020
- maxRetries: config.maxRetries ?? 3,
1021
- accessToken: accessToken || "",
1022
- endpoint
1023
- };
1024
- this.buffer = {
1025
- spans: [],
1026
- totalSize: 0
1027
- };
1028
- }
1029
- async _exportEvent(event) {
1030
- if (event.type !== "span_ended" /* SPAN_ENDED */) {
1031
- return;
1032
- }
1033
- this.addToBuffer(event);
1034
- if (this.shouldFlush()) {
1035
- this.flush().catch((error) => {
1036
- this.logger.error("Batch flush failed", {
1037
- error: error instanceof Error ? error.message : String(error)
1038
- });
1039
- });
1040
- } else if (this.buffer.totalSize === 1) {
1041
- this.scheduleFlush();
1042
- }
1043
- }
1044
- addToBuffer(event) {
1045
- if (this.buffer.totalSize === 0) {
1046
- this.buffer.firstEventTime = /* @__PURE__ */ new Date();
1047
- }
1048
- const spanRecord = this.formatSpan(event.exportedSpan);
1049
- this.buffer.spans.push(spanRecord);
1050
- this.buffer.totalSize++;
1051
- }
1052
- formatSpan(span) {
1053
- const spanRecord = {
1054
- traceId: span.traceId,
1055
- spanId: span.id,
1056
- parentSpanId: span.parentSpanId ?? null,
1057
- name: span.name,
1058
- spanType: span.type,
1059
- attributes: span.attributes ?? null,
1060
- metadata: span.metadata ?? null,
1061
- startedAt: span.startTime,
1062
- endedAt: span.endTime ?? null,
1063
- input: span.input ?? null,
1064
- output: span.output ?? null,
1065
- error: span.errorInfo,
1066
- isEvent: span.isEvent,
1067
- createdAt: /* @__PURE__ */ new Date(),
1068
- updatedAt: null
1069
- };
1070
- return spanRecord;
1071
- }
1072
- shouldFlush() {
1073
- if (this.buffer.totalSize >= this.config.maxBatchSize) {
1074
- return true;
1075
- }
1076
- if (this.buffer.firstEventTime && this.buffer.totalSize > 0) {
1077
- const elapsed = Date.now() - this.buffer.firstEventTime.getTime();
1078
- if (elapsed >= this.config.maxBatchWaitMs) {
1079
- return true;
1080
- }
1081
- }
1082
- return false;
1083
- }
1084
- scheduleFlush() {
1085
- if (this.flushTimer) {
1086
- clearTimeout(this.flushTimer);
1087
- }
1088
- this.flushTimer = setTimeout(() => {
1089
- this.flush().catch((error) => {
1090
- const mastraError = new MastraError(
1091
- {
1092
- id: `CLOUD_AI_TRACING_FAILED_TO_SCHEDULE_FLUSH`,
1093
- domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */,
1094
- category: "USER" /* USER */
1095
- },
1096
- error
1097
- );
1098
- this.logger.trackException(mastraError);
1099
- this.logger.error("Scheduled flush failed", mastraError);
1100
- });
1101
- }, this.config.maxBatchWaitMs);
1102
- }
1103
- async flush() {
1104
- if (this.flushTimer) {
1105
- clearTimeout(this.flushTimer);
1106
- this.flushTimer = null;
1107
- }
1108
- if (this.buffer.totalSize === 0) {
1109
- return;
1110
- }
1111
- const startTime = Date.now();
1112
- const spansCopy = [...this.buffer.spans];
1113
- const flushReason = this.buffer.totalSize >= this.config.maxBatchSize ? "size" : "time";
1114
- this.resetBuffer();
1115
- try {
1116
- await this.batchUpload(spansCopy);
1117
- const elapsed = Date.now() - startTime;
1118
- this.logger.debug("Batch flushed successfully", {
1119
- batchSize: spansCopy.length,
1120
- flushReason,
1121
- durationMs: elapsed
1122
- });
1123
- } catch (error) {
1124
- const mastraError = new MastraError(
1125
- {
1126
- id: `CLOUD_AI_TRACING_FAILED_TO_BATCH_UPLOAD`,
1127
- domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */,
1128
- category: "USER" /* USER */,
1129
- details: {
1130
- droppedBatchSize: spansCopy.length
1131
- }
1132
- },
1133
- error
1134
- );
1135
- this.logger.trackException(mastraError);
1136
- this.logger.error("Batch upload failed after all retries, dropping batch", mastraError);
1137
- }
1138
- }
1139
- /**
1140
- * Uploads spans to cloud API using fetchWithRetry for all retry logic
1141
- */
1142
- async batchUpload(spans) {
1143
- const headers = {
1144
- Authorization: `Bearer ${this.config.accessToken}`,
1145
- "Content-Type": "application/json"
1146
- };
1147
- const options = {
1148
- method: "POST",
1149
- headers,
1150
- body: JSON.stringify({ spans })
1151
- };
1152
- await fetchWithRetry(this.config.endpoint, options, this.config.maxRetries);
1153
- }
1154
- resetBuffer() {
1155
- this.buffer.spans = [];
1156
- this.buffer.firstEventTime = void 0;
1157
- this.buffer.totalSize = 0;
1158
- }
1159
- async shutdown() {
1160
- if (this.isDisabled) {
1161
- return;
1162
- }
1163
- if (this.flushTimer) {
1164
- clearTimeout(this.flushTimer);
1165
- this.flushTimer = null;
1166
- }
1167
- if (this.buffer.totalSize > 0) {
1168
- this.logger.info("Flushing remaining events on shutdown", {
1169
- remainingEvents: this.buffer.totalSize
1170
- });
1171
- try {
1172
- await this.flush();
1173
- } catch (error) {
1174
- const mastraError = new MastraError(
1175
- {
1176
- id: `CLOUD_AI_TRACING_FAILED_TO_FLUSH_REMAINING_EVENTS_DURING_SHUTDOWN`,
1177
- domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */,
1178
- category: "USER" /* USER */,
1179
- details: {
1180
- remainingEvents: this.buffer.totalSize
1181
- }
1182
- },
1183
- error
1184
- );
1185
- this.logger.trackException(mastraError);
1186
- this.logger.error("Failed to flush remaining events during shutdown", mastraError);
1187
- }
1188
- }
1189
- this.logger.info("CloudExporter shutdown complete");
1190
- }
1191
- };
1192
-
1193
- // src/ai-tracing/exporters/console.ts
1194
- var ConsoleExporter = class extends BaseExporter {
1195
- name = "tracing-console-exporter";
1196
- constructor(config = {}) {
1197
- super(config);
1198
- }
1199
- async _exportEvent(event) {
1200
- const span = event.exportedSpan;
1201
- const formatAttributes = (attributes) => {
1202
- try {
1203
- return JSON.stringify(attributes, null, 2);
1204
- } catch (error) {
1205
- const errMsg = error instanceof Error ? error.message : "Unknown formatting error";
1206
- return `[Unable to serialize attributes: ${errMsg}]`;
1207
- }
1208
- };
1209
- const formatDuration = (startTime, endTime) => {
1210
- if (!endTime) return "N/A";
1211
- const duration = endTime.getTime() - startTime.getTime();
1212
- return `${duration}ms`;
1213
- };
1214
- switch (event.type) {
1215
- case "span_started" /* SPAN_STARTED */:
1216
- this.logger.info(`\u{1F680} SPAN_STARTED`);
1217
- this.logger.info(` Type: ${span.type}`);
1218
- this.logger.info(` Name: ${span.name}`);
1219
- this.logger.info(` ID: ${span.id}`);
1220
- this.logger.info(` Trace ID: ${span.traceId}`);
1221
- if (span.input !== void 0) {
1222
- this.logger.info(` Input: ${formatAttributes(span.input)}`);
1223
- }
1224
- this.logger.info(` Attributes: ${formatAttributes(span.attributes)}`);
1225
- this.logger.info("\u2500".repeat(80));
1226
- break;
1227
- case "span_ended" /* SPAN_ENDED */:
1228
- const duration = formatDuration(span.startTime, span.endTime);
1229
- this.logger.info(`\u2705 SPAN_ENDED`);
1230
- this.logger.info(` Type: ${span.type}`);
1231
- this.logger.info(` Name: ${span.name}`);
1232
- this.logger.info(` ID: ${span.id}`);
1233
- this.logger.info(` Duration: ${duration}`);
1234
- this.logger.info(` Trace ID: ${span.traceId}`);
1235
- if (span.input !== void 0) {
1236
- this.logger.info(` Input: ${formatAttributes(span.input)}`);
1237
- }
1238
- if (span.output !== void 0) {
1239
- this.logger.info(` Output: ${formatAttributes(span.output)}`);
1240
- }
1241
- if (span.errorInfo) {
1242
- this.logger.info(` Error: ${formatAttributes(span.errorInfo)}`);
1243
- }
1244
- this.logger.info(` Attributes: ${formatAttributes(span.attributes)}`);
1245
- this.logger.info("\u2500".repeat(80));
1246
- break;
1247
- case "span_updated" /* SPAN_UPDATED */:
1248
- this.logger.info(`\u{1F4DD} SPAN_UPDATED`);
1249
- this.logger.info(` Type: ${span.type}`);
1250
- this.logger.info(` Name: ${span.name}`);
1251
- this.logger.info(` ID: ${span.id}`);
1252
- this.logger.info(` Trace ID: ${span.traceId}`);
1253
- if (span.input !== void 0) {
1254
- this.logger.info(` Input: ${formatAttributes(span.input)}`);
1255
- }
1256
- if (span.output !== void 0) {
1257
- this.logger.info(` Output: ${formatAttributes(span.output)}`);
1258
- }
1259
- if (span.errorInfo) {
1260
- this.logger.info(` Error: ${formatAttributes(span.errorInfo)}`);
1261
- }
1262
- this.logger.info(` Updated Attributes: ${formatAttributes(span.attributes)}`);
1263
- this.logger.info("\u2500".repeat(80));
1264
- break;
1265
- default:
1266
- this.logger.warn(`Tracing event type not implemented: ${event.type}`);
1267
- }
1268
- }
1269
- async shutdown() {
1270
- this.logger.info("ConsoleExporter shutdown");
1271
- }
1272
- };
1273
-
1274
- // src/ai-tracing/exporters/default.ts
1275
- function resolveStrategy(userConfig, storage, logger) {
1276
- if (userConfig.strategy && userConfig.strategy !== "auto") {
1277
- const hints = storage.aiTracingStrategy;
1278
- if (hints.supported.includes(userConfig.strategy)) {
1279
- return userConfig.strategy;
1280
- }
1281
- logger.warn("User-specified AI tracing strategy not supported by storage adapter, falling back to auto-selection", {
1282
- userStrategy: userConfig.strategy,
1283
- storageAdapter: storage.constructor.name,
1284
- supportedStrategies: hints.supported,
1285
- fallbackStrategy: hints.preferred
1286
- });
1287
- }
1288
- return storage.aiTracingStrategy.preferred;
1289
- }
1290
- var DefaultExporter = class {
1291
- name = "tracing-default-exporter";
1292
- logger;
1293
- mastra = null;
1294
- config;
1295
- resolvedStrategy;
1296
- buffer;
1297
- flushTimer = null;
1298
- // Track all spans that have been created, persists across flushes
1299
- allCreatedSpans = /* @__PURE__ */ new Set();
1300
- constructor(config = {}, logger) {
1301
- if (logger) {
1302
- this.logger = logger;
1303
- } else {
1304
- this.logger = new ConsoleLogger({ level: LogLevel.INFO });
1305
- }
1306
- this.config = {
1307
- maxBatchSize: config.maxBatchSize ?? 1e3,
1308
- maxBufferSize: config.maxBufferSize ?? 1e4,
1309
- maxBatchWaitMs: config.maxBatchWaitMs ?? 5e3,
1310
- maxRetries: config.maxRetries ?? 4,
1311
- retryDelayMs: config.retryDelayMs ?? 500,
1312
- strategy: config.strategy ?? "auto"
1313
- };
1314
- this.buffer = {
1315
- creates: [],
1316
- updates: [],
1317
- insertOnly: [],
1318
- seenSpans: /* @__PURE__ */ new Set(),
1319
- spanSequences: /* @__PURE__ */ new Map(),
1320
- completedSpans: /* @__PURE__ */ new Set(),
1321
- outOfOrderCount: 0,
1322
- totalSize: 0
1323
- };
1324
- this.resolvedStrategy = "batch-with-updates";
1325
- }
1326
- strategyInitialized = false;
1327
- /**
1328
- * Register the Mastra instance (called after Mastra construction is complete)
1329
- */
1330
- __registerMastra(mastra) {
1331
- this.mastra = mastra;
1332
- }
1333
- /**
1334
- * Initialize the exporter (called after all dependencies are ready)
1335
- */
1336
- init(_config) {
1337
- if (!this.mastra) {
1338
- throw new Error("DefaultExporter: init() called before __registerMastra()");
1339
- }
1340
- const storage = this.mastra.getStorage();
1341
- if (!storage) {
1342
- this.logger.warn("DefaultExporter disabled: Storage not available. Traces will not be persisted.");
1343
- return;
1344
- }
1345
- this.initializeStrategy(storage);
1346
- }
1347
- /**
1348
- * Initialize the resolved strategy once storage is available
1349
- */
1350
- initializeStrategy(storage) {
1351
- if (this.strategyInitialized) return;
1352
- this.resolvedStrategy = resolveStrategy(this.config, storage, this.logger);
1353
- this.strategyInitialized = true;
1354
- this.logger.debug("AI tracing exporter initialized", {
1355
- strategy: this.resolvedStrategy,
1356
- source: this.config.strategy !== "auto" ? "user" : "auto",
1357
- storageAdapter: storage.constructor.name,
1358
- maxBatchSize: this.config.maxBatchSize,
1359
- maxBatchWaitMs: this.config.maxBatchWaitMs
1360
- });
1361
- }
1362
- /**
1363
- * Builds a unique span key for tracking
1364
- */
1365
- buildSpanKey(traceId, spanId) {
1366
- return `${traceId}:${spanId}`;
1367
- }
1368
- /**
1369
- * Gets the next sequence number for a span
1370
- */
1371
- getNextSequence(spanKey) {
1372
- const current = this.buffer.spanSequences.get(spanKey) || 0;
1373
- const next = current + 1;
1374
- this.buffer.spanSequences.set(spanKey, next);
1375
- return next;
1376
- }
1377
- /**
1378
- * Handles out-of-order span updates by logging and skipping
1379
- */
1380
- handleOutOfOrderUpdate(event) {
1381
- this.logger.warn("Out-of-order span update detected - skipping event", {
1382
- spanId: event.exportedSpan.id,
1383
- traceId: event.exportedSpan.traceId,
1384
- spanName: event.exportedSpan.name,
1385
- eventType: event.type
1386
- });
1387
- }
1388
- /**
1389
- * Adds an event to the appropriate buffer based on strategy
1390
- */
1391
- addToBuffer(event) {
1392
- const spanKey = this.buildSpanKey(event.exportedSpan.traceId, event.exportedSpan.id);
1393
- if (this.buffer.totalSize === 0) {
1394
- this.buffer.firstEventTime = /* @__PURE__ */ new Date();
1395
- }
1396
- switch (event.type) {
1397
- case "span_started" /* SPAN_STARTED */:
1398
- if (this.resolvedStrategy === "batch-with-updates") {
1399
- const createRecord = this.buildCreateRecord(event.exportedSpan);
1400
- this.buffer.creates.push(createRecord);
1401
- this.buffer.seenSpans.add(spanKey);
1402
- this.allCreatedSpans.add(spanKey);
1403
- }
1404
- break;
1405
- case "span_updated" /* SPAN_UPDATED */:
1406
- if (this.resolvedStrategy === "batch-with-updates") {
1407
- if (this.allCreatedSpans.has(spanKey)) {
1408
- this.buffer.updates.push({
1409
- traceId: event.exportedSpan.traceId,
1410
- spanId: event.exportedSpan.id,
1411
- updates: this.buildUpdateRecord(event.exportedSpan),
1412
- sequenceNumber: this.getNextSequence(spanKey)
1413
- });
1414
- } else {
1415
- this.handleOutOfOrderUpdate(event);
1416
- this.buffer.outOfOrderCount++;
1417
- }
1418
- }
1419
- break;
1420
- case "span_ended" /* SPAN_ENDED */:
1421
- if (this.resolvedStrategy === "batch-with-updates") {
1422
- if (this.allCreatedSpans.has(spanKey)) {
1423
- this.buffer.updates.push({
1424
- traceId: event.exportedSpan.traceId,
1425
- spanId: event.exportedSpan.id,
1426
- updates: this.buildUpdateRecord(event.exportedSpan),
1427
- sequenceNumber: this.getNextSequence(spanKey)
1428
- });
1429
- this.buffer.completedSpans.add(spanKey);
1430
- } else if (event.exportedSpan.isEvent) {
1431
- const createRecord = this.buildCreateRecord(event.exportedSpan);
1432
- this.buffer.creates.push(createRecord);
1433
- this.buffer.seenSpans.add(spanKey);
1434
- this.allCreatedSpans.add(spanKey);
1435
- this.buffer.completedSpans.add(spanKey);
1436
- } else {
1437
- this.handleOutOfOrderUpdate(event);
1438
- this.buffer.outOfOrderCount++;
1439
- }
1440
- } else if (this.resolvedStrategy === "insert-only") {
1441
- const createRecord = this.buildCreateRecord(event.exportedSpan);
1442
- this.buffer.insertOnly.push(createRecord);
1443
- this.buffer.completedSpans.add(spanKey);
1444
- this.allCreatedSpans.add(spanKey);
1445
- }
1446
- break;
1447
- }
1448
- this.buffer.totalSize = this.buffer.creates.length + this.buffer.updates.length + this.buffer.insertOnly.length;
1449
- }
1450
- /**
1451
- * Checks if buffer should be flushed based on size or time triggers
1452
- */
1453
- shouldFlush() {
1454
- if (this.buffer.totalSize >= this.config.maxBufferSize) {
1455
- return true;
1456
- }
1457
- if (this.buffer.totalSize >= this.config.maxBatchSize) {
1458
- return true;
1459
- }
1460
- if (this.buffer.firstEventTime && this.buffer.totalSize > 0) {
1461
- const elapsed = Date.now() - this.buffer.firstEventTime.getTime();
1462
- if (elapsed >= this.config.maxBatchWaitMs) {
1463
- return true;
1464
- }
1465
- }
1466
- return false;
1467
- }
1468
- /**
1469
- * Resets the buffer after successful flush
1470
- */
1471
- resetBuffer(completedSpansToCleanup = /* @__PURE__ */ new Set()) {
1472
- this.buffer.creates = [];
1473
- this.buffer.updates = [];
1474
- this.buffer.insertOnly = [];
1475
- this.buffer.seenSpans.clear();
1476
- this.buffer.spanSequences.clear();
1477
- this.buffer.completedSpans.clear();
1478
- this.buffer.outOfOrderCount = 0;
1479
- this.buffer.firstEventTime = void 0;
1480
- this.buffer.totalSize = 0;
1481
- for (const spanKey of completedSpansToCleanup) {
1482
- this.allCreatedSpans.delete(spanKey);
1483
- }
1484
- }
1485
- /**
1486
- * Schedules a flush using setTimeout
1487
- */
1488
- scheduleFlush() {
1489
- if (this.flushTimer) {
1490
- clearTimeout(this.flushTimer);
1491
- }
1492
- this.flushTimer = setTimeout(() => {
1493
- this.flush().catch((error) => {
1494
- this.logger.error("Scheduled flush failed", {
1495
- error: error instanceof Error ? error.message : String(error)
1496
- });
1497
- });
1498
- }, this.config.maxBatchWaitMs);
1499
- }
1500
- /**
1501
- * Serializes span attributes to storage record format
1502
- * Handles all AI span types and their specific attributes
1503
- */
1504
- serializeAttributes(span) {
1505
- if (!span.attributes) {
1506
- return null;
1507
- }
1508
- try {
1509
- return JSON.parse(
1510
- JSON.stringify(span.attributes, (_key, value) => {
1511
- if (value instanceof Date) {
1512
- return value.toISOString();
1513
- }
1514
- if (typeof value === "object" && value !== null) {
1515
- return value;
1516
- }
1517
- return value;
1518
- })
1519
- );
1520
- } catch (error) {
1521
- this.logger.warn("Failed to serialize span attributes, storing as null", {
1522
- spanId: span.id,
1523
- spanType: span.type,
1524
- error: error instanceof Error ? error.message : String(error)
1525
- });
1526
- return null;
1527
- }
1528
- }
1529
- buildCreateRecord(span) {
1530
- return {
1531
- traceId: span.traceId,
1532
- spanId: span.id,
1533
- parentSpanId: span.parentSpanId ?? null,
1534
- name: span.name,
1535
- scope: null,
1536
- spanType: span.type,
1537
- attributes: this.serializeAttributes(span),
1538
- metadata: span.metadata ?? null,
1539
- links: null,
1540
- startedAt: span.startTime,
1541
- endedAt: span.endTime ?? null,
1542
- input: span.input,
1543
- output: span.output,
1544
- error: span.errorInfo,
1545
- isEvent: span.isEvent
1546
- };
1547
- }
1548
- buildUpdateRecord(span) {
1549
- return {
1550
- name: span.name,
1551
- scope: null,
1552
- attributes: this.serializeAttributes(span),
1553
- metadata: span.metadata ?? null,
1554
- links: null,
1555
- endedAt: span.endTime ?? null,
1556
- input: span.input,
1557
- output: span.output,
1558
- error: span.errorInfo
1559
- };
1560
- }
1561
- /**
1562
- * Handles realtime strategy - processes each event immediately
1563
- */
1564
- async handleRealtimeEvent(event, storage) {
1565
- const span = event.exportedSpan;
1566
- const spanKey = this.buildSpanKey(span.traceId, span.id);
1567
- if (span.isEvent) {
1568
- if (event.type === "span_ended" /* SPAN_ENDED */) {
1569
- await storage.createAISpan(this.buildCreateRecord(event.exportedSpan));
1570
- } else {
1571
- this.logger.warn(`Tracing event type not implemented for event spans: ${event.type}`);
1572
- }
1573
- } else {
1574
- switch (event.type) {
1575
- case "span_started" /* SPAN_STARTED */:
1576
- await storage.createAISpan(this.buildCreateRecord(event.exportedSpan));
1577
- this.allCreatedSpans.add(spanKey);
1578
- break;
1579
- case "span_updated" /* SPAN_UPDATED */:
1580
- await storage.updateAISpan({
1581
- traceId: span.traceId,
1582
- spanId: span.id,
1583
- updates: this.buildUpdateRecord(span)
1584
- });
1585
- break;
1586
- case "span_ended" /* SPAN_ENDED */:
1587
- await storage.updateAISpan({
1588
- traceId: span.traceId,
1589
- spanId: span.id,
1590
- updates: this.buildUpdateRecord(span)
1591
- });
1592
- this.allCreatedSpans.delete(spanKey);
1593
- break;
1594
- default:
1595
- this.logger.warn(`Tracing event type not implemented for span spans: ${event.type}`);
1596
- }
1597
- }
1598
- }
1599
- /**
1600
- * Handles batch-with-updates strategy - buffers events and processes in batches
1601
- */
1602
- handleBatchWithUpdatesEvent(event) {
1603
- this.addToBuffer(event);
1604
- if (this.shouldFlush()) {
1605
- this.flush().catch((error) => {
1606
- this.logger.error("Batch flush failed", {
1607
- error: error instanceof Error ? error.message : String(error)
1608
- });
1609
- });
1610
- } else if (this.buffer.totalSize === 1) {
1611
- this.scheduleFlush();
1612
- }
1613
- }
1614
- /**
1615
- * Handles insert-only strategy - only processes SPAN_ENDED events in batches
1616
- */
1617
- handleInsertOnlyEvent(event) {
1618
- if (event.type === "span_ended" /* SPAN_ENDED */) {
1619
- this.addToBuffer(event);
1620
- if (this.shouldFlush()) {
1621
- this.flush().catch((error) => {
1622
- this.logger.error("Batch flush failed", {
1623
- error: error instanceof Error ? error.message : String(error)
1624
- });
1625
- });
1626
- } else if (this.buffer.totalSize === 1) {
1627
- this.scheduleFlush();
1628
- }
1629
- }
1630
- }
1631
- /**
1632
- * Calculates retry delay using exponential backoff
1633
- */
1634
- calculateRetryDelay(attempt) {
1635
- return this.config.retryDelayMs * Math.pow(2, attempt);
1636
- }
1637
- /**
1638
- * Flushes the current buffer to storage with retry logic
1639
- */
1640
- async flush() {
1641
- if (!this.mastra) {
1642
- this.logger.debug("Cannot flush traces. Mastra instance not registered yet.");
1643
- return;
1644
- }
1645
- const storage = this.mastra.getStorage();
1646
- if (!storage) {
1647
- this.logger.debug("Cannot flush traces. Mastra storage is not initialized");
1648
- return;
1649
- }
1650
- if (this.flushTimer) {
1651
- clearTimeout(this.flushTimer);
1652
- this.flushTimer = null;
1653
- }
1654
- if (this.buffer.totalSize === 0) {
1655
- return;
1656
- }
1657
- const startTime = Date.now();
1658
- const flushReason = this.buffer.totalSize >= this.config.maxBufferSize ? "overflow" : this.buffer.totalSize >= this.config.maxBatchSize ? "size" : "time";
1659
- const bufferCopy = {
1660
- creates: [...this.buffer.creates],
1661
- updates: [...this.buffer.updates],
1662
- insertOnly: [...this.buffer.insertOnly],
1663
- seenSpans: new Set(this.buffer.seenSpans),
1664
- spanSequences: new Map(this.buffer.spanSequences),
1665
- completedSpans: new Set(this.buffer.completedSpans),
1666
- outOfOrderCount: this.buffer.outOfOrderCount,
1667
- firstEventTime: this.buffer.firstEventTime,
1668
- totalSize: this.buffer.totalSize
1669
- };
1670
- this.resetBuffer();
1671
- await this.flushWithRetries(storage, bufferCopy, 0);
1672
- const elapsed = Date.now() - startTime;
1673
- this.logger.debug("Batch flushed", {
1674
- strategy: this.resolvedStrategy,
1675
- batchSize: bufferCopy.totalSize,
1676
- flushReason,
1677
- durationMs: elapsed,
1678
- outOfOrderCount: bufferCopy.outOfOrderCount > 0 ? bufferCopy.outOfOrderCount : void 0
1679
- });
1680
- }
1681
- /**
1682
- * Attempts to flush with exponential backoff retry logic
1683
- */
1684
- async flushWithRetries(storage, buffer, attempt) {
1685
- try {
1686
- if (this.resolvedStrategy === "batch-with-updates") {
1687
- if (buffer.creates.length > 0) {
1688
- await storage.batchCreateAISpans({ records: buffer.creates });
1689
- }
1690
- if (buffer.updates.length > 0) {
1691
- const sortedUpdates = buffer.updates.sort((a, b) => {
1692
- const spanCompare = this.buildSpanKey(a.traceId, a.spanId).localeCompare(
1693
- this.buildSpanKey(b.traceId, b.spanId)
1694
- );
1695
- if (spanCompare !== 0) return spanCompare;
1696
- return a.sequenceNumber - b.sequenceNumber;
1697
- });
1698
- await storage.batchUpdateAISpans({ records: sortedUpdates });
1699
- }
1700
- } else if (this.resolvedStrategy === "insert-only") {
1701
- if (buffer.insertOnly.length > 0) {
1702
- await storage.batchCreateAISpans({ records: buffer.insertOnly });
1703
- }
1704
- }
1705
- for (const spanKey of buffer.completedSpans) {
1706
- this.allCreatedSpans.delete(spanKey);
1707
- }
1708
- } catch (error) {
1709
- if (attempt < this.config.maxRetries) {
1710
- const retryDelay = this.calculateRetryDelay(attempt);
1711
- this.logger.warn("Batch flush failed, retrying", {
1712
- attempt: attempt + 1,
1713
- maxRetries: this.config.maxRetries,
1714
- nextRetryInMs: retryDelay,
1715
- error: error instanceof Error ? error.message : String(error)
1716
- });
1717
- await new Promise((resolve) => setTimeout(resolve, retryDelay));
1718
- return this.flushWithRetries(storage, buffer, attempt + 1);
1719
- } else {
1720
- this.logger.error("Batch flush failed after all retries, dropping batch", {
1721
- finalAttempt: attempt + 1,
1722
- maxRetries: this.config.maxRetries,
1723
- droppedBatchSize: buffer.totalSize,
1724
- error: error instanceof Error ? error.message : String(error)
1725
- });
1726
- for (const spanKey of buffer.completedSpans) {
1727
- this.allCreatedSpans.delete(spanKey);
1728
- }
1729
- }
1730
- }
1731
- }
1732
- async exportEvent(event) {
1733
- if (!this.mastra) {
1734
- this.logger.debug("Cannot export AI tracing event. Mastra instance not registered yet.");
1735
- return;
1736
- }
1737
- const storage = this.mastra.getStorage();
1738
- if (!storage) {
1739
- this.logger.debug("Cannot store traces. Mastra storage is not initialized");
1740
- return;
1741
- }
1742
- if (!this.strategyInitialized) {
1743
- this.initializeStrategy(storage);
1744
- }
1745
- switch (this.resolvedStrategy) {
1746
- case "realtime":
1747
- await this.handleRealtimeEvent(event, storage);
1748
- break;
1749
- case "batch-with-updates":
1750
- this.handleBatchWithUpdatesEvent(event);
1751
- break;
1752
- case "insert-only":
1753
- this.handleInsertOnlyEvent(event);
1754
- break;
1755
- }
1756
- }
1757
- async shutdown() {
1758
- if (this.flushTimer) {
1759
- clearTimeout(this.flushTimer);
1760
- this.flushTimer = null;
1761
- }
1762
- if (this.buffer.totalSize > 0) {
1763
- this.logger.info("Flushing remaining events on shutdown", {
1764
- remainingEvents: this.buffer.totalSize
1765
- });
1766
- try {
1767
- await this.flush();
1768
- } catch (error) {
1769
- this.logger.error("Failed to flush remaining events during shutdown", {
1770
- error: error instanceof Error ? error.message : String(error)
1771
- });
1772
- }
1773
- }
1774
- this.logger.info("DefaultExporter shutdown complete");
1775
- }
1776
- };
1777
-
1778
- // src/ai-tracing/span_processors/sensitive-data-filter.ts
1779
- var SensitiveDataFilter = class {
1780
- name = "sensitive-data-filter";
1781
- sensitiveFields;
1782
- redactionToken;
1783
- redactionStyle;
1784
- constructor(options = {}) {
1785
- this.sensitiveFields = (options.sensitiveFields || [
1786
- "password",
1787
- "token",
1788
- "secret",
1789
- "key",
1790
- "apikey",
1791
- "auth",
1792
- "authorization",
1793
- "bearer",
1794
- "bearertoken",
1795
- "jwt",
1796
- "credential",
1797
- "clientsecret",
1798
- "privatekey",
1799
- "refresh",
1800
- "ssn"
1801
- ]).map((f) => this.normalizeKey(f));
1802
- this.redactionToken = options.redactionToken ?? "[REDACTED]";
1803
- this.redactionStyle = options.redactionStyle ?? "full";
1804
- }
1805
- /**
1806
- * Process a span by filtering sensitive data across its key fields.
1807
- * Fields processed: attributes, metadata, input, output, errorInfo.
1808
- *
1809
- * @param span - The input span to filter
1810
- * @returns A new span with sensitive values redacted
1811
- */
1812
- process(span) {
1813
- span.attributes = this.tryFilter(span.attributes);
1814
- span.metadata = this.tryFilter(span.metadata);
1815
- span.input = this.tryFilter(span.input);
1816
- span.output = this.tryFilter(span.output);
1817
- span.errorInfo = this.tryFilter(span.errorInfo);
1818
- return span;
1819
- }
1820
- /**
1821
- * Recursively filter objects/arrays for sensitive keys.
1822
- * Handles circular references by replacing with a marker.
1823
- */
1824
- deepFilter(obj, seen = /* @__PURE__ */ new WeakSet()) {
1825
- if (obj === null || typeof obj !== "object") {
1826
- return obj;
1827
- }
1828
- if (seen.has(obj)) {
1829
- return "[Circular Reference]";
1830
- }
1831
- seen.add(obj);
1832
- if (Array.isArray(obj)) {
1833
- return obj.map((item) => this.deepFilter(item, seen));
1834
- }
1835
- const filtered = {};
1836
- for (const key of Object.keys(obj)) {
1837
- const normKey = this.normalizeKey(key);
1838
- if (this.isSensitive(normKey)) {
1839
- if (obj[key] && typeof obj[key] === "object") {
1840
- filtered[key] = this.deepFilter(obj[key], seen);
1841
- } else {
1842
- filtered[key] = this.redactValue(obj[key]);
1843
- }
1844
- } else {
1845
- filtered[key] = this.deepFilter(obj[key], seen);
1846
- }
1847
- }
1848
- return filtered;
1849
- }
1850
- tryFilter(value) {
1851
- try {
1852
- return this.deepFilter(value);
1853
- } catch {
1854
- return { error: { processor: this.name } };
1855
- }
1856
- }
1857
- /**
1858
- * Normalize keys by lowercasing and stripping non-alphanumeric characters.
1859
- * Ensures consistent matching for variants like "api-key", "api_key", "Api Key".
1860
- */
1861
- normalizeKey(key) {
1862
- return key.toLowerCase().replace(/[^a-z0-9]/g, "");
1863
- }
1864
- /**
1865
- * Check whether a normalized key exactly matches any sensitive field.
1866
- * Both key and sensitive fields are normalized by removing all non-alphanumeric
1867
- * characters and converting to lowercase before comparison.
1868
- *
1869
- * Examples:
1870
- * - "api_key", "api-key", "ApiKey" all normalize to "apikey" → MATCHES "apikey"
1871
- * - "promptTokens", "prompt_tokens" normalize to "prompttokens" → DOES NOT MATCH "token"
1872
- */
1873
- isSensitive(normalizedKey) {
1874
- return this.sensitiveFields.some((sensitiveField) => {
1875
- return normalizedKey === sensitiveField;
1876
- });
1877
- }
1878
- /**
1879
- * Redact a sensitive value.
1880
- * - Full style: replaces with a fixed token.
1881
- * - Partial style: shows 3 chars at start and end, hides the middle.
1882
- *
1883
- * Non-string values are converted to strings before partial redaction.
1884
- */
1885
- redactValue(value) {
1886
- if (this.redactionStyle === "full") {
1887
- return this.redactionToken;
1888
- }
1889
- const str = String(value);
1890
- const len = str.length;
1891
- if (len <= 6) {
1892
- return this.redactionToken;
1893
- }
1894
- return str.slice(0, 3) + "\u2026" + str.slice(len - 3);
1895
- }
1896
- async shutdown() {
1897
- }
1898
- };
1899
-
1900
- // src/ai-tracing/registry.ts
1901
- var AITracingRegistry = class {
1902
- instances = /* @__PURE__ */ new Map();
1903
- defaultInstance;
1904
- configSelector;
1905
- /**
1906
- * Register a tracing instance
1907
- */
1908
- register(name, instance, isDefault = false) {
1909
- if (this.instances.has(name)) {
1910
- throw new Error(`AI Tracing instance '${name}' already registered`);
1911
- }
1912
- this.instances.set(name, instance);
1913
- if (isDefault || !this.defaultInstance) {
1914
- this.defaultInstance = instance;
1915
- }
1916
- }
1917
- /**
1918
- * Get a tracing instance by name
1919
- */
1920
- get(name) {
1921
- return this.instances.get(name);
1922
- }
1923
- /**
1924
- * Get the default tracing instance
1925
- */
1926
- getDefault() {
1927
- return this.defaultInstance;
1928
- }
1929
- /**
1930
- * Set the tracing selector function
1931
- */
1932
- setSelector(selector) {
1933
- this.configSelector = selector;
1934
- }
1935
- /**
1936
- * Get the selected tracing instance based on context
1937
- */
1938
- getSelected(options) {
1939
- if (this.configSelector) {
1940
- const selected = this.configSelector(options, this.instances);
1941
- if (selected && this.instances.has(selected)) {
1942
- return this.instances.get(selected);
1943
- }
1944
- }
1945
- return this.defaultInstance;
1946
- }
1947
- /**
1948
- * Unregister a tracing instance
1949
- */
1950
- unregister(name) {
1951
- return this.instances.delete(name);
1952
- }
1953
- /**
1954
- * Shutdown all instances and clear the registry
1955
- */
1956
- async shutdown() {
1957
- const shutdownPromises = Array.from(this.instances.values()).map((instance) => instance.shutdown());
1958
- await Promise.allSettled(shutdownPromises);
1959
- this.instances.clear();
1960
- }
1961
- /**
1962
- * Clear all instances without shutdown
1963
- */
1964
- clear() {
1965
- this.instances.clear();
1966
- this.defaultInstance = void 0;
1967
- this.configSelector = void 0;
1968
- }
1969
- /**
1970
- * Get all registered instances
1971
- */
1972
- getAll() {
1973
- return new Map(this.instances);
1974
- }
1975
- };
1976
- var aiTracingRegistry = new AITracingRegistry();
1977
- function registerAITracing(name, instance, isDefault = false) {
1978
- aiTracingRegistry.register(name, instance, isDefault);
1979
- }
1980
- function getAITracing(name) {
1981
- return aiTracingRegistry.get(name);
1982
- }
1983
- function getDefaultAITracing() {
1984
- return aiTracingRegistry.getDefault();
1985
- }
1986
- function setSelector(selector) {
1987
- aiTracingRegistry.setSelector(selector);
1988
- }
1989
- function getSelectedAITracing(options) {
1990
- return aiTracingRegistry.getSelected(options);
1991
- }
1992
- function unregisterAITracing(name) {
1993
- return aiTracingRegistry.unregister(name);
1994
- }
1995
- async function shutdownAITracingRegistry() {
1996
- await aiTracingRegistry.shutdown();
1997
- }
1998
- function clearAITracingRegistry() {
1999
- aiTracingRegistry.clear();
2000
- }
2001
- function getAllAITracing() {
2002
- return aiTracingRegistry.getAll();
2003
- }
2004
- function hasAITracing(name) {
2005
- const tracing = getAITracing(name);
2006
- if (!tracing) return false;
2007
- const config = tracing.getConfig();
2008
- const sampling = config.sampling;
2009
- return sampling.type !== "never" /* NEVER */;
2010
- }
2011
- function isAITracingInstance(obj) {
2012
- return obj instanceof BaseAITracing;
2013
- }
2014
- function setupAITracing(config) {
2015
- if (!config) {
2016
- return;
2017
- }
2018
- if (config.default?.enabled && config.configs?.["default"]) {
2019
- throw new Error(
2020
- "Cannot use 'default' as a custom config name when default tracing is enabled. Please rename your custom config to avoid conflicts."
2021
- );
2022
- }
2023
- if (config.default?.enabled) {
2024
- const defaultInstance = new DefaultAITracing({
2025
- serviceName: "mastra",
2026
- name: "default",
2027
- sampling: { type: "always" /* ALWAYS */ },
2028
- exporters: [new DefaultExporter(), new CloudExporter()],
2029
- processors: [new SensitiveDataFilter()]
2030
- });
2031
- registerAITracing("default", defaultInstance, true);
2032
- }
2033
- if (config.configs) {
2034
- const instances = Object.entries(config.configs);
2035
- instances.forEach(([name, tracingDef], index) => {
2036
- const instance = isAITracingInstance(tracingDef) ? tracingDef : new DefaultAITracing({ ...tracingDef, name });
2037
- const isDefault = !config.default?.enabled && index === 0;
2038
- registerAITracing(name, instance, isDefault);
2039
- });
2040
- }
2041
- if (config.configSelector) {
2042
- setSelector(config.configSelector);
2043
- }
2044
- }
2045
-
2046
- // src/ai-tracing/utils.ts
2047
- function omitKeys(obj, keysToOmit) {
2048
- return Object.fromEntries(Object.entries(obj).filter(([key]) => !keysToOmit.includes(key)));
2049
- }
2050
- function selectFields(obj, fields) {
2051
- if (!obj || typeof obj !== "object") {
2052
- return obj;
2053
- }
2054
- const result = {};
2055
- for (const field of fields) {
2056
- const value = getNestedValue(obj, field);
2057
- if (value !== void 0) {
2058
- setNestedValue(result, field, value);
2059
- }
2060
- }
2061
- return result;
2062
- }
2063
- function getNestedValue(obj, path) {
2064
- return path.split(".").reduce((current, key) => {
2065
- return current && typeof current === "object" ? current[key] : void 0;
2066
- }, obj);
2067
- }
2068
- function setNestedValue(obj, path, value) {
2069
- const keys = path.split(".");
2070
- const lastKey = keys.pop();
2071
- if (!lastKey) {
2072
- return;
2073
- }
2074
- const target = keys.reduce((current, key) => {
2075
- if (!current[key] || typeof current[key] !== "object") {
2076
- current[key] = {};
2077
- }
2078
- return current[key];
2079
- }, obj);
2080
- target[lastKey] = value;
2081
- }
2082
- function getValidTraceId(span) {
2083
- return span?.isValid ? span.traceId : void 0;
2084
- }
2085
- function getOrCreateSpan(options) {
2086
- const { type, attributes, tracingContext, runtimeContext, tracingOptions, ...rest } = options;
2087
- const metadata = {
2088
- ...rest.metadata ?? {},
2089
- ...tracingOptions?.metadata ?? {}
2090
- };
2091
- if (tracingContext?.currentSpan) {
2092
- return tracingContext.currentSpan.createChildSpan({
2093
- type,
2094
- attributes,
2095
- ...rest,
2096
- metadata
2097
- });
2098
- }
2099
- const aiTracing = getSelectedAITracing({
2100
- runtimeContext
2101
- });
2102
- return aiTracing?.startSpan({
2103
- type,
2104
- attributes,
2105
- ...rest,
2106
- metadata,
2107
- runtimeContext,
2108
- tracingOptions,
2109
- traceId: tracingOptions?.traceId,
2110
- parentSpanId: tracingOptions?.parentSpanId,
2111
- customSamplerOptions: {
2112
- runtimeContext,
2113
- metadata
2114
- }
2115
- });
2116
- }
2117
-
2118
- // src/ai-tracing/tracers/base.ts
2119
- var BaseAITracing = class extends MastraBase {
2120
- config;
2121
- constructor(config) {
2122
- super({ component: RegisteredLogger.AI_TRACING, name: config.serviceName });
2123
- this.config = {
2124
- serviceName: config.serviceName,
2125
- name: config.name,
2126
- sampling: config.sampling ?? { type: "always" /* ALWAYS */ },
2127
- exporters: config.exporters ?? [],
2128
- processors: config.processors ?? [],
2129
- includeInternalSpans: config.includeInternalSpans ?? false,
2130
- runtimeContextKeys: config.runtimeContextKeys ?? []
2131
- };
2132
- }
2133
- /**
2134
- * Override setLogger to add AI tracing specific initialization log
2135
- * and propagate logger to exporters
2136
- */
2137
- __setLogger(logger) {
2138
- super.__setLogger(logger);
2139
- this.exporters.forEach((exporter) => {
2140
- if (typeof exporter.__setLogger === "function") {
2141
- exporter.__setLogger(logger);
2142
- }
2143
- });
2144
- this.logger.debug(
2145
- `[AI Tracing] Initialized [service=${this.config.serviceName}] [instance=${this.config.name}] [sampling=${this.config.sampling.type}]`
2146
- );
2147
- }
2148
- // ============================================================================
2149
- // Protected getters for clean config access
2150
- // ============================================================================
2151
- get exporters() {
2152
- return this.config.exporters || [];
2153
- }
2154
- get processors() {
2155
- return this.config.processors || [];
2156
- }
2157
- // ============================================================================
2158
- // Public API - Single type-safe span creation method
2159
- // ============================================================================
2160
- /**
2161
- * Start a new span of a specific AISpanType
2162
- */
2163
- startSpan(options) {
2164
- const { customSamplerOptions, runtimeContext, metadata, tracingOptions, ...rest } = options;
2165
- if (!this.shouldSample(customSamplerOptions)) {
2166
- return new NoOpAISpan({ ...rest, metadata }, this);
2167
- }
2168
- let traceState;
2169
- if (options.parent) {
2170
- traceState = options.parent.traceState;
2171
- } else {
2172
- traceState = this.computeTraceState(tracingOptions);
2173
- }
2174
- const enrichedMetadata = this.extractMetadataFromRuntimeContext(runtimeContext, metadata, traceState);
2175
- const span = this.createSpan({
2176
- ...rest,
2177
- metadata: enrichedMetadata,
2178
- traceState
2179
- });
2180
- if (span.isEvent) {
2181
- this.emitSpanEnded(span);
2182
- } else {
2183
- this.wireSpanLifecycle(span);
2184
- this.emitSpanStarted(span);
2185
- }
2186
- return span;
2187
- }
2188
- // ============================================================================
2189
- // Configuration Management
2190
- // ============================================================================
2191
- /**
2192
- * Get current configuration
2193
- */
2194
- getConfig() {
2195
- return { ...this.config };
2196
- }
2197
- // ============================================================================
2198
- // Plugin Access
2199
- // ============================================================================
2200
- /**
2201
- * Get all exporters
2202
- */
2203
- getExporters() {
2204
- return [...this.exporters];
2205
- }
2206
- /**
2207
- * Get all processors
2208
- */
2209
- getProcessors() {
2210
- return [...this.processors];
2211
- }
2212
- /**
2213
- * Get the logger instance (for exporters and other components)
2214
- */
2215
- getLogger() {
2216
- return this.logger;
2217
- }
2218
- // ============================================================================
2219
- // Span Lifecycle Management
2220
- // ============================================================================
2221
- /**
2222
- * Automatically wires up AI tracing lifecycle events for any span
2223
- * This ensures all spans emit events regardless of implementation
2224
- */
2225
- wireSpanLifecycle(span) {
2226
- if (!this.config.includeInternalSpans && span.isInternal) {
2227
- return;
2228
- }
2229
- const originalEnd = span.end.bind(span);
2230
- const originalUpdate = span.update.bind(span);
2231
- span.end = (options) => {
2232
- if (span.isEvent) {
2233
- this.logger.warn(`End event is not available on event spans`);
2234
- return;
2235
- }
2236
- originalEnd(options);
2237
- this.emitSpanEnded(span);
2238
- };
2239
- span.update = (options) => {
2240
- if (span.isEvent) {
2241
- this.logger.warn(`Update() is not available on event spans`);
2242
- return;
2243
- }
2244
- originalUpdate(options);
2245
- this.emitSpanUpdated(span);
2246
- };
2247
- }
2248
- // ============================================================================
2249
- // Utility Methods
2250
- // ============================================================================
2251
- /**
2252
- * Check if an AI trace should be sampled
2253
- */
2254
- shouldSample(options) {
2255
- const { sampling } = this.config;
2256
- switch (sampling.type) {
2257
- case "always" /* ALWAYS */:
2258
- return true;
2259
- case "never" /* NEVER */:
2260
- return false;
2261
- case "ratio" /* RATIO */:
2262
- if (sampling.probability === void 0 || sampling.probability < 0 || sampling.probability > 1) {
2263
- this.logger.warn(
2264
- `Invalid sampling probability: ${sampling.probability}. Expected value between 0 and 1. Defaulting to no sampling.`
2265
- );
2266
- return false;
2267
- }
2268
- return Math.random() < sampling.probability;
2269
- case "custom" /* CUSTOM */:
2270
- return sampling.sampler(options);
2271
- default:
2272
- throw new Error(`Sampling strategy type not implemented: ${sampling.type}`);
2273
- }
2274
- }
2275
- /**
2276
- * Compute TraceState for a new trace based on configured and per-request keys
2277
- */
2278
- computeTraceState(tracingOptions) {
2279
- const configuredKeys = this.config.runtimeContextKeys ?? [];
2280
- const additionalKeys = tracingOptions?.runtimeContextKeys ?? [];
2281
- const allKeys = [...configuredKeys, ...additionalKeys];
2282
- if (allKeys.length === 0) {
2283
- return void 0;
2284
- }
2285
- return {
2286
- runtimeContextKeys: allKeys
2287
- };
2288
- }
2289
- /**
2290
- * Extract metadata from RuntimeContext using TraceState
2291
- */
2292
- extractMetadataFromRuntimeContext(runtimeContext, explicitMetadata, traceState) {
2293
- if (!runtimeContext || !traceState || traceState.runtimeContextKeys.length === 0) {
2294
- return explicitMetadata;
2295
- }
2296
- const extracted = this.extractKeys(runtimeContext, traceState.runtimeContextKeys);
2297
- if (Object.keys(extracted).length === 0 && !explicitMetadata) {
2298
- return void 0;
2299
- }
2300
- return {
2301
- ...extracted,
2302
- ...explicitMetadata
2303
- // Explicit metadata always wins
2304
- };
2305
- }
2306
- /**
2307
- * Extract specific keys from RuntimeContext
2308
- */
2309
- extractKeys(runtimeContext, keys) {
2310
- const result = {};
2311
- for (const key of keys) {
2312
- const parts = key.split(".");
2313
- const rootKey = parts[0];
2314
- const value = runtimeContext.get(rootKey);
2315
- if (value !== void 0) {
2316
- if (parts.length > 1) {
2317
- const nestedPath = parts.slice(1).join(".");
2318
- const nestedValue = getNestedValue(value, nestedPath);
2319
- if (nestedValue !== void 0) {
2320
- setNestedValue(result, key, nestedValue);
2321
- }
2322
- } else {
2323
- setNestedValue(result, key, value);
2324
- }
2325
- }
2326
- }
2327
- return result;
2328
- }
2329
- /**
2330
- * Process a span through all processors
2331
- */
2332
- processSpan(span) {
2333
- for (const processor of this.processors) {
2334
- if (!span) {
2335
- break;
2336
- }
2337
- try {
2338
- span = processor.process(span);
2339
- } catch (error) {
2340
- this.logger.error(`[AI Tracing] Processor error [name=${processor.name}]`, error);
2341
- }
2342
- }
2343
- return span;
2344
- }
2345
- // ============================================================================
2346
- // Event-driven Export Methods
2347
- // ============================================================================
2348
- getSpanForExport(span) {
2349
- if (!span.isValid) return void 0;
2350
- if (span.isInternal && !this.config.includeInternalSpans) return void 0;
2351
- const processedSpan = this.processSpan(span);
2352
- return processedSpan?.exportSpan(this.config.includeInternalSpans);
2353
- }
2354
- /**
2355
- * Emit a span started event
2356
- */
2357
- emitSpanStarted(span) {
2358
- const exportedSpan = this.getSpanForExport(span);
2359
- if (exportedSpan) {
2360
- this.exportEvent({ type: "span_started" /* SPAN_STARTED */, exportedSpan }).catch((error) => {
2361
- this.logger.error("[AI Tracing] Failed to export span_started event", error);
2362
- });
2363
- }
2364
- }
2365
- /**
2366
- * Emit a span ended event (called automatically when spans end)
2367
- */
2368
- emitSpanEnded(span) {
2369
- const exportedSpan = this.getSpanForExport(span);
2370
- if (exportedSpan) {
2371
- this.exportEvent({ type: "span_ended" /* SPAN_ENDED */, exportedSpan }).catch((error) => {
2372
- this.logger.error("[AI Tracing] Failed to export span_ended event", error);
2373
- });
2374
- }
2375
- }
2376
- /**
2377
- * Emit a span updated event
2378
- */
2379
- emitSpanUpdated(span) {
2380
- const exportedSpan = this.getSpanForExport(span);
2381
- if (exportedSpan) {
2382
- this.exportEvent({ type: "span_updated" /* SPAN_UPDATED */, exportedSpan }).catch((error) => {
2383
- this.logger.error("[AI Tracing] Failed to export span_updated event", error);
2384
- });
2385
- }
2386
- }
2387
- /**
2388
- * Export tracing event through all exporters (realtime mode)
2389
- */
2390
- async exportEvent(event) {
2391
- const exportPromises = this.exporters.map(async (exporter) => {
2392
- try {
2393
- if (exporter.exportEvent) {
2394
- await exporter.exportEvent(event);
2395
- this.logger.debug(`[AI Tracing] Event exported [exporter=${exporter.name}] [type=${event.type}]`);
2396
- }
2397
- } catch (error) {
2398
- this.logger.error(`[AI Tracing] Export error [exporter=${exporter.name}]`, error);
2399
- }
2400
- });
2401
- await Promise.allSettled(exportPromises);
2402
- }
2403
- // ============================================================================
2404
- // Lifecycle Management
2405
- // ============================================================================
2406
- /**
2407
- * Initialize AI tracing (called by Mastra during component registration)
2408
- */
2409
- init() {
2410
- this.logger.debug(`[AI Tracing] Initialization started [name=${this.name}]`);
2411
- this.logger.info(`[AI Tracing] Initialized successfully [name=${this.name}]`);
2412
- }
2413
- /**
2414
- * Shutdown AI tracing and clean up resources
2415
- */
2416
- async shutdown() {
2417
- this.logger.debug(`[AI Tracing] Shutdown started [name=${this.name}]`);
2418
- const shutdownPromises = [...this.exporters.map((e) => e.shutdown()), ...this.processors.map((p) => p.shutdown())];
2419
- await Promise.allSettled(shutdownPromises);
2420
- this.logger.info(`[AI Tracing] Shutdown completed [name=${this.name}]`);
2421
- }
2422
- };
2423
-
2424
- // src/ai-tracing/tracers/default.ts
2425
- var DefaultAITracing = class extends BaseAITracing {
2426
- constructor(config) {
2427
- super(config);
2428
- }
2429
- createSpan(options) {
2430
- return new DefaultAISpan(options, this);
2431
- }
2432
- };
2433
-
2434
- // src/ai-tracing/context.ts
2435
- var AGENT_GETTERS = ["getAgent", "getAgentById"];
2436
- var AGENT_METHODS_TO_WRAP = ["generate", "stream", "generateLegacy", "streamLegacy"];
2437
- var WORKFLOW_GETTERS = ["getWorkflow", "getWorkflowById"];
2438
- var WORKFLOW_METHODS_TO_WRAP = ["execute", "createRun", "createRunAsync"];
2439
- function isNoOpSpan(span) {
2440
- return span.constructor.name === "NoOpAISpan" || span.__isNoOp === true;
2441
- }
2442
- function isMastra(mastra) {
2443
- const hasAgentGetters = AGENT_GETTERS.every((method) => typeof mastra?.[method] === "function");
2444
- const hasWorkflowGetters = WORKFLOW_GETTERS.every((method) => typeof mastra?.[method] === "function");
2445
- return hasAgentGetters && hasWorkflowGetters;
2446
- }
2447
- function wrapMastra(mastra, tracingContext) {
2448
- if (!tracingContext.currentSpan || isNoOpSpan(tracingContext.currentSpan)) {
2449
- return mastra;
2450
- }
2451
- if (!isMastra(mastra)) {
2452
- return mastra;
2453
- }
2454
- try {
2455
- return new Proxy(mastra, {
2456
- get(target, prop) {
2457
- try {
2458
- if (AGENT_GETTERS.includes(prop)) {
2459
- return (...args) => {
2460
- const agent = target[prop](...args);
2461
- return wrapAgent(agent, tracingContext);
2462
- };
2463
- }
2464
- if (WORKFLOW_GETTERS.includes(prop)) {
2465
- return (...args) => {
2466
- const workflow = target[prop](...args);
2467
- return wrapWorkflow(workflow, tracingContext);
2468
- };
2469
- }
2470
- const value = target[prop];
2471
- return typeof value === "function" ? value.bind(target) : value;
2472
- } catch (error) {
2473
- console.warn("AI Tracing: Failed to wrap method, falling back to original", error);
2474
- const value = target[prop];
2475
- return typeof value === "function" ? value.bind(target) : value;
2476
- }
2477
- }
2478
- });
2479
- } catch (error) {
2480
- console.warn("AI Tracing: Failed to create proxy, using original Mastra instance", error);
2481
- return mastra;
2482
- }
2483
- }
2484
- function wrapAgent(agent, tracingContext) {
2485
- if (!tracingContext.currentSpan || isNoOpSpan(tracingContext.currentSpan)) {
2486
- return agent;
2487
- }
2488
- try {
2489
- return new Proxy(agent, {
2490
- get(target, prop) {
2491
- try {
2492
- if (AGENT_METHODS_TO_WRAP.includes(prop)) {
2493
- return (input, options = {}) => {
2494
- return target[prop](input, {
2495
- ...options,
2496
- tracingContext
2497
- });
2498
- };
2499
- }
2500
- const value = target[prop];
2501
- return typeof value === "function" ? value.bind(target) : value;
2502
- } catch (error) {
2503
- console.warn("AI Tracing: Failed to wrap agent method, falling back to original", error);
2504
- const value = target[prop];
2505
- return typeof value === "function" ? value.bind(target) : value;
2506
- }
2507
- }
2508
- });
2509
- } catch (error) {
2510
- console.warn("AI Tracing: Failed to create agent proxy, using original instance", error);
2511
- return agent;
2512
- }
2513
- }
2514
- function wrapWorkflow(workflow, tracingContext) {
2515
- if (!tracingContext.currentSpan || isNoOpSpan(tracingContext.currentSpan)) {
2516
- return workflow;
2517
- }
2518
- try {
2519
- return new Proxy(workflow, {
2520
- get(target, prop) {
2521
- try {
2522
- if (WORKFLOW_METHODS_TO_WRAP.includes(prop)) {
2523
- if (prop === "createRun" || prop === "createRunAsync") {
2524
- return async (options = {}) => {
2525
- const run = await target[prop](options);
2526
- return run ? wrapRun(run, tracingContext) : run;
2527
- };
2528
- }
2529
- return (input, options = {}) => {
2530
- return target[prop](input, {
2531
- ...options,
2532
- tracingContext
2533
- });
2534
- };
2535
- }
2536
- const value = target[prop];
2537
- return typeof value === "function" ? value.bind(target) : value;
2538
- } catch (error) {
2539
- console.warn("AI Tracing: Failed to wrap workflow method, falling back to original", error);
2540
- const value = target[prop];
2541
- return typeof value === "function" ? value.bind(target) : value;
2542
- }
2543
- }
2544
- });
2545
- } catch (error) {
2546
- console.warn("AI Tracing: Failed to create workflow proxy, using original instance", error);
2547
- return workflow;
2548
- }
2549
- }
2550
- function wrapRun(run, tracingContext) {
2551
- if (!tracingContext.currentSpan || isNoOpSpan(tracingContext.currentSpan)) {
2552
- return run;
2553
- }
2554
- try {
2555
- return new Proxy(run, {
2556
- get(target, prop) {
2557
- try {
2558
- if (prop === "start") {
2559
- return (startOptions = {}) => {
2560
- return target.start({
2561
- ...startOptions,
2562
- tracingContext: startOptions.tracingContext ?? tracingContext
2563
- });
2564
- };
2565
- }
2566
- const value = target[prop];
2567
- return typeof value === "function" ? value.bind(target) : value;
2568
- } catch (error) {
2569
- console.warn("AI Tracing: Failed to wrap run method, falling back to original", error);
2570
- const value = target[prop];
2571
- return typeof value === "function" ? value.bind(target) : value;
2572
- }
2573
- }
2574
- });
2575
- } catch (error) {
2576
- console.warn("AI Tracing: Failed to create run proxy, using original instance", error);
2577
- return run;
2578
- }
2579
- }
2580
- var ModelSpanTracker = class {
2581
- #modelSpan;
2582
- #currentStepSpan;
2583
- #currentChunkSpan;
2584
- #accumulator = {};
2585
- #stepIndex = 0;
2586
- #chunkSequence = 0;
2587
- constructor(modelSpan) {
2588
- this.#modelSpan = modelSpan;
2589
- }
2590
- /**
2591
- * Get the tracing context for creating child spans.
2592
- * Returns the current step span if active, otherwise the model span.
2593
- */
2594
- getTracingContext() {
2595
- return {
2596
- currentSpan: this.#currentStepSpan ?? this.#modelSpan
2597
- };
2598
- }
2599
- /**
2600
- * Report an error on the generation span
2601
- */
2602
- reportGenerationError(options) {
2603
- this.#modelSpan?.error(options);
2604
- }
2605
- /**
2606
- * End the generation span
2607
- */
2608
- endGeneration(options) {
2609
- this.#modelSpan?.end(options);
2610
- }
2611
- /**
2612
- * Update the generation span
2613
- */
2614
- updateGeneration(options) {
2615
- this.#modelSpan?.update(options);
2616
- }
2617
- /**
2618
- * Start a new Model execution step
2619
- */
2620
- #startStepSpan(payload) {
2621
- this.#currentStepSpan = this.#modelSpan?.createChildSpan({
2622
- name: `step: ${this.#stepIndex}`,
2623
- type: "model_step" /* MODEL_STEP */,
2624
- attributes: {
2625
- stepIndex: this.#stepIndex,
2626
- ...payload?.messageId ? { messageId: payload.messageId } : {},
2627
- ...payload?.warnings?.length ? { warnings: payload.warnings } : {}
2628
- },
2629
- input: payload?.request
2630
- });
2631
- this.#chunkSequence = 0;
2632
- }
2633
- /**
2634
- * End the current Model execution step with token usage, finish reason, output, and metadata
2635
- */
2636
- #endStepSpan(payload) {
2637
- if (!this.#currentStepSpan) return;
2638
- const output = payload.output;
2639
- const { usage, ...otherOutput } = output;
2640
- const stepResult = payload.stepResult;
2641
- const metadata = payload.metadata;
2642
- const cleanMetadata = metadata ? { ...metadata } : void 0;
2643
- if (cleanMetadata?.request) {
2644
- delete cleanMetadata.request;
2645
- }
2646
- this.#currentStepSpan.end({
2647
- output: otherOutput,
2648
- attributes: {
2649
- usage,
2650
- isContinued: stepResult.isContinued,
2651
- finishReason: stepResult.reason,
2652
- warnings: stepResult.warnings
2653
- },
2654
- metadata: {
2655
- ...cleanMetadata
2656
- }
2657
- });
2658
- this.#currentStepSpan = void 0;
2659
- this.#stepIndex++;
2660
- }
2661
- /**
2662
- * Create a new chunk span (for multi-part chunks like text-start/delta/end)
2663
- */
2664
- #startChunkSpan(chunkType, initialData) {
2665
- if (!this.#currentStepSpan) {
2666
- this.#startStepSpan();
2667
- }
2668
- this.#currentChunkSpan = this.#currentStepSpan?.createChildSpan({
2669
- name: `chunk: '${chunkType}'`,
2670
- type: "model_chunk" /* MODEL_CHUNK */,
2671
- attributes: {
2672
- chunkType,
2673
- sequenceNumber: this.#chunkSequence
2674
- }
2675
- });
2676
- this.#accumulator = initialData || {};
2677
- }
2678
- /**
2679
- * Append string content to a specific field in the accumulator
2680
- */
2681
- #appendToAccumulator(field, text) {
2682
- if (this.#accumulator[field] === void 0) {
2683
- this.#accumulator[field] = text;
2684
- } else {
2685
- this.#accumulator[field] += text;
2686
- }
2687
- }
2688
- /**
2689
- * End the current chunk span.
2690
- * Safe to call multiple times - will no-op if span already ended.
2691
- */
2692
- #endChunkSpan(output) {
2693
- if (!this.#currentChunkSpan) return;
2694
- this.#currentChunkSpan.end({
2695
- output: output !== void 0 ? output : this.#accumulator
2696
- });
2697
- this.#currentChunkSpan = void 0;
2698
- this.#accumulator = {};
2699
- this.#chunkSequence++;
2700
- }
2701
- /**
2702
- * Create an event span (for single chunks like tool-call)
2703
- */
2704
- #createEventSpan(chunkType, output) {
2705
- if (!this.#currentStepSpan) {
2706
- this.#startStepSpan();
2707
- }
2708
- const span = this.#currentStepSpan?.createEventSpan({
2709
- name: `chunk: '${chunkType}'`,
2710
- type: "model_chunk" /* MODEL_CHUNK */,
2711
- attributes: {
2712
- chunkType,
2713
- sequenceNumber: this.#chunkSequence
2714
- },
2715
- output
2716
- });
2717
- if (span) {
2718
- this.#chunkSequence++;
2719
- }
2720
- }
2721
- /**
2722
- * Check if there is currently an active chunk span
2723
- */
2724
- #hasActiveChunkSpan() {
2725
- return !!this.#currentChunkSpan;
2726
- }
2727
- /**
2728
- * Get the current accumulator value
2729
- */
2730
- #getAccumulator() {
2731
- return this.#accumulator;
2732
- }
2733
- /**
2734
- * Handle text chunk spans (text-start/delta/end)
2735
- */
2736
- #handleTextChunk(chunk) {
2737
- switch (chunk.type) {
2738
- case "text-start":
2739
- this.#startChunkSpan("text");
2740
- break;
2741
- case "text-delta":
2742
- this.#appendToAccumulator("text", chunk.payload.text);
2743
- break;
2744
- case "text-end": {
2745
- this.#endChunkSpan();
2746
- break;
2747
- }
2748
- }
2749
- }
2750
- /**
2751
- * Handle reasoning chunk spans (reasoning-start/delta/end)
2752
- */
2753
- #handleReasoningChunk(chunk) {
2754
- switch (chunk.type) {
2755
- case "reasoning-start":
2756
- this.#startChunkSpan("reasoning");
2757
- break;
2758
- case "reasoning-delta":
2759
- this.#appendToAccumulator("text", chunk.payload.text);
2760
- break;
2761
- case "reasoning-end": {
2762
- this.#endChunkSpan();
2763
- break;
2764
- }
2765
- }
2766
- }
2767
- /**
2768
- * Handle tool call chunk spans (tool-call-input-streaming-start/delta/end, tool-call)
2769
- */
2770
- #handleToolCallChunk(chunk) {
2771
- switch (chunk.type) {
2772
- case "tool-call-input-streaming-start":
2773
- this.#startChunkSpan("tool-call", {
2774
- toolName: chunk.payload.toolName,
2775
- toolCallId: chunk.payload.toolCallId
2776
- });
2777
- break;
2778
- case "tool-call-delta":
2779
- this.#appendToAccumulator("toolInput", chunk.payload.argsTextDelta);
2780
- break;
2781
- case "tool-call-input-streaming-end":
2782
- case "tool-call": {
2783
- const acc = this.#getAccumulator();
2784
- let toolInput;
2785
- try {
2786
- toolInput = acc.toolInput ? JSON.parse(acc.toolInput) : {};
2787
- } catch {
2788
- toolInput = acc.toolInput;
2789
- }
2790
- this.#endChunkSpan({
2791
- toolName: acc.toolName,
2792
- toolCallId: acc.toolCallId,
2793
- toolInput
2794
- });
2795
- break;
2796
- }
2797
- }
2798
- }
2799
- /**
2800
- * Handle object chunk spans (object, object-result)
2801
- */
2802
- #handleObjectChunk(chunk) {
2803
- switch (chunk.type) {
2804
- case "object":
2805
- if (!this.#hasActiveChunkSpan()) {
2806
- this.#startChunkSpan("object");
2807
- }
2808
- break;
2809
- case "object-result":
2810
- this.#endChunkSpan(chunk.object);
2811
- break;
2812
- }
2813
- }
2814
- /**
2815
- * Wraps a stream with model tracing transform to track MODEL_STEP and MODEL_CHUNK spans.
2816
- *
2817
- * This should be added to the stream pipeline to automatically
2818
- * create MODEL_STEP and MODEL_CHUNK spans for each semantic unit in the stream.
2819
- */
2820
- wrapStream(stream) {
2821
- return stream.pipeThrough(
2822
- new TransformStream({
2823
- transform: (chunk, controller) => {
2824
- controller.enqueue(chunk);
2825
- switch (chunk.type) {
2826
- case "text-start":
2827
- case "text-delta":
2828
- case "text-end":
2829
- this.#handleTextChunk(chunk);
2830
- break;
2831
- case "tool-call-input-streaming-start":
2832
- case "tool-call-delta":
2833
- case "tool-call-input-streaming-end":
2834
- case "tool-call":
2835
- this.#handleToolCallChunk(chunk);
2836
- break;
2837
- case "reasoning-start":
2838
- case "reasoning-delta":
2839
- case "reasoning-end":
2840
- this.#handleReasoningChunk(chunk);
2841
- break;
2842
- case "object":
2843
- case "object-result":
2844
- this.#handleObjectChunk(chunk);
2845
- break;
2846
- case "step-start":
2847
- this.#startStepSpan(chunk.payload);
2848
- break;
2849
- case "step-finish":
2850
- this.#endStepSpan(chunk.payload);
2851
- break;
2852
- case "raw":
2853
- // Skip raw chunks as they're redundant
2854
- case "start":
2855
- case "finish":
2856
- break;
2857
- // Default: auto-create event span for all other chunk types
2858
- default: {
2859
- let outputPayload = chunk.payload;
2860
- if (outputPayload && typeof outputPayload === "object" && "data" in outputPayload) {
2861
- const typedPayload = outputPayload;
2862
- outputPayload = { ...typedPayload };
2863
- if (typedPayload.data) {
2864
- outputPayload.size = typeof typedPayload.data === "string" ? typedPayload.data.length : typedPayload.data instanceof Uint8Array ? typedPayload.data.length : void 0;
2865
- delete outputPayload.data;
2866
- }
2867
- }
2868
- this.#createEventSpan(chunk.type, outputPayload);
2869
- break;
2870
- }
2871
- }
2872
- }
2873
- })
2874
- );
2875
- }
2876
- };
2877
-
2878
- export { AISpanType, AITracingEventType, BaseAISpan, BaseAITracing, BaseExporter, CloudExporter, ConsoleExporter, DefaultAISpan, DefaultAITracing, DefaultExporter, InternalSpans, ModelSpanTracker, NoOpAISpan, SamplingStrategyType, SensitiveDataFilter, checkEvalStorageFields, clearAITracingRegistry, createMastraProxy, deepClean, deepMerge, delay, ensureToolProperties, fetchWithRetry, generateEmptyFromSchema, getAITracing, getAllAITracing, getDefaultAITracing, getNestedValue, getOrCreateSpan, getSelectedAITracing, getValidTraceId, hasAITracing, isCoreMessage, isMastra, isUiMessage, isZodType, makeCoreTool, makeCoreToolV5, maskStreamTags, omitKeys, parseFieldKey, parseSqlIdentifier, registerAITracing, resolveSerializedZodOutput, selectFields, setNestedValue, setSelector, setupAITracing, shutdownAITracingRegistry, unregisterAITracing, wrapMastra };
2879
- //# sourceMappingURL=chunk-DTTOVV72.js.map
2880
- //# sourceMappingURL=chunk-DTTOVV72.js.map