@mastra/core 1.6.0 → 1.7.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 (453) hide show
  1. package/CHANGELOG.md +236 -0
  2. package/dist/agent/agent.d.ts +6 -0
  3. package/dist/agent/agent.d.ts.map +1 -1
  4. package/dist/agent/index.cjs +8 -8
  5. package/dist/agent/index.js +1 -1
  6. package/dist/{chunk-VJWRJWSC.cjs → chunk-2X66GWF5.cjs} +94 -16
  7. package/dist/chunk-2X66GWF5.cjs.map +1 -0
  8. package/dist/{chunk-YM6245EM.js → chunk-6OXW5E2O.js} +3 -3
  9. package/dist/{chunk-YM6245EM.js.map → chunk-6OXW5E2O.js.map} +1 -1
  10. package/dist/{chunk-XWZAKKFT.cjs → chunk-6QBN6MZY.cjs} +14 -14
  11. package/dist/{chunk-XWZAKKFT.cjs.map → chunk-6QBN6MZY.cjs.map} +1 -1
  12. package/dist/{chunk-AYHSPIT6.cjs → chunk-7UAJ6LMR.cjs} +820 -259
  13. package/dist/chunk-7UAJ6LMR.cjs.map +1 -0
  14. package/dist/{chunk-RZNHRIM7.cjs → chunk-A72NTLFT.cjs} +5 -5
  15. package/dist/{chunk-RZNHRIM7.cjs.map → chunk-A72NTLFT.cjs.map} +1 -1
  16. package/dist/{chunk-EEU5NHHU.js → chunk-DFCRXDVK.js} +3 -3
  17. package/dist/{chunk-EEU5NHHU.js.map → chunk-DFCRXDVK.js.map} +1 -1
  18. package/dist/{chunk-5K45E5VE.js → chunk-GPJGPARM.js} +3 -2
  19. package/dist/chunk-GPJGPARM.js.map +1 -0
  20. package/dist/{chunk-LNKS4TJ6.cjs → chunk-HB6T4554.cjs} +8 -7
  21. package/dist/chunk-HB6T4554.cjs.map +1 -0
  22. package/dist/{chunk-DGS2KGDI.js → chunk-KUXNBWN7.js} +6 -5
  23. package/dist/chunk-KUXNBWN7.js.map +1 -0
  24. package/dist/{chunk-IHDE4CJV.js → chunk-QSHV7GPT.js} +89 -12
  25. package/dist/chunk-QSHV7GPT.js.map +1 -0
  26. package/dist/{chunk-3U3XFMGJ.cjs → chunk-QTAS3HND.cjs} +13 -8
  27. package/dist/chunk-QTAS3HND.cjs.map +1 -0
  28. package/dist/{chunk-RHKNKJNM.js → chunk-QWTB53GS.js} +4 -4
  29. package/dist/{chunk-RHKNKJNM.js.map → chunk-QWTB53GS.js.map} +1 -1
  30. package/dist/{chunk-4WG5K4CK.js → chunk-R4N65TLG.js} +7 -7
  31. package/dist/{chunk-4WG5K4CK.js.map → chunk-R4N65TLG.js.map} +1 -1
  32. package/dist/{chunk-5VQPSWPG.cjs → chunk-RABITNTG.cjs} +48 -48
  33. package/dist/{chunk-5VQPSWPG.cjs.map → chunk-RABITNTG.cjs.map} +1 -1
  34. package/dist/{chunk-TVPANHLE.cjs → chunk-SBOHDNIZ.cjs} +3 -2
  35. package/dist/chunk-SBOHDNIZ.cjs.map +1 -0
  36. package/dist/{chunk-MWGGSA5Q.js → chunk-T6GAM3SQ.js} +10 -5
  37. package/dist/chunk-T6GAM3SQ.js.map +1 -0
  38. package/dist/{chunk-TL2TTA4X.cjs → chunk-YQG7NBPR.cjs} +9 -9
  39. package/dist/{chunk-TL2TTA4X.cjs.map → chunk-YQG7NBPR.cjs.map} +1 -1
  40. package/dist/{chunk-XB3DA67Q.js → chunk-ZSBM2SVU.js} +818 -259
  41. package/dist/chunk-ZSBM2SVU.js.map +1 -0
  42. package/dist/datasets/experiment/scorer.d.ts.map +1 -1
  43. package/dist/datasets/index.cjs +17 -17
  44. package/dist/datasets/index.js +2 -2
  45. package/dist/evals/index.cjs +20 -20
  46. package/dist/evals/index.js +3 -3
  47. package/dist/evals/scoreTraces/index.cjs +7 -6
  48. package/dist/evals/scoreTraces/index.cjs.map +1 -1
  49. package/dist/evals/scoreTraces/index.js +4 -3
  50. package/dist/evals/scoreTraces/index.js.map +1 -1
  51. package/dist/evals/scoreTraces/scoreTracesWorkflow.d.ts.map +1 -1
  52. package/dist/harness/harness.d.ts +21 -1
  53. package/dist/harness/harness.d.ts.map +1 -1
  54. package/dist/harness/index.cjs +422 -5
  55. package/dist/harness/index.cjs.map +1 -1
  56. package/dist/harness/index.d.ts +2 -1
  57. package/dist/harness/index.d.ts.map +1 -1
  58. package/dist/harness/index.js +418 -3
  59. package/dist/harness/index.js.map +1 -1
  60. package/dist/harness/types.d.ts +151 -0
  61. package/dist/harness/types.d.ts.map +1 -1
  62. package/dist/index.cjs +2 -2
  63. package/dist/index.js +1 -1
  64. package/dist/loop/index.cjs +12 -12
  65. package/dist/loop/index.js +1 -1
  66. package/dist/loop/test-utils/tools.d.ts.map +1 -1
  67. package/dist/loop/workflows/agentic-loop/index.d.ts.map +1 -1
  68. package/dist/mastra/hooks.d.ts.map +1 -1
  69. package/dist/mastra/index.cjs +2 -2
  70. package/dist/mastra/index.js +1 -1
  71. package/dist/memory/index.cjs +14 -14
  72. package/dist/memory/index.js +1 -1
  73. package/dist/processor-provider/index.cjs +10 -10
  74. package/dist/processor-provider/index.js +1 -1
  75. package/dist/processors/index.cjs +45 -41
  76. package/dist/processors/index.js +1 -1
  77. package/dist/processors/processors/index.d.ts +1 -0
  78. package/dist/processors/processors/index.d.ts.map +1 -1
  79. package/dist/processors/processors/workspace-instructions.d.ts +50 -0
  80. package/dist/processors/processors/workspace-instructions.d.ts.map +1 -0
  81. package/dist/relevance/index.cjs +3 -3
  82. package/dist/relevance/index.js +1 -1
  83. package/dist/storage/constants.cjs +56 -56
  84. package/dist/storage/constants.d.ts.map +1 -1
  85. package/dist/storage/constants.js +1 -1
  86. package/dist/storage/index.cjs +160 -160
  87. package/dist/storage/index.js +2 -2
  88. package/dist/storage/types.d.ts +2 -0
  89. package/dist/storage/types.d.ts.map +1 -1
  90. package/dist/stream/aisdk/v5/compat/prepare-tools.d.ts.map +1 -1
  91. package/dist/stream/base/output.d.ts.map +1 -1
  92. package/dist/stream/index.cjs +8 -8
  93. package/dist/stream/index.js +1 -1
  94. package/dist/tool-loop-agent/index.cjs +4 -4
  95. package/dist/tool-loop-agent/index.js +1 -1
  96. package/dist/vector/index.cjs +7 -7
  97. package/dist/vector/index.js +1 -1
  98. package/dist/workflows/evented/index.cjs +10 -10
  99. package/dist/workflows/evented/index.js +1 -1
  100. package/dist/workflows/index.cjs +25 -25
  101. package/dist/workflows/index.js +1 -1
  102. package/dist/workspace/constants/index.d.ts +2 -0
  103. package/dist/workspace/constants/index.d.ts.map +1 -1
  104. package/dist/workspace/errors.d.ts +1 -1
  105. package/dist/workspace/errors.d.ts.map +1 -1
  106. package/dist/workspace/filesystem/composite-filesystem.d.ts +4 -1
  107. package/dist/workspace/filesystem/composite-filesystem.d.ts.map +1 -1
  108. package/dist/workspace/filesystem/file-write-lock.d.ts +35 -0
  109. package/dist/workspace/filesystem/file-write-lock.d.ts.map +1 -0
  110. package/dist/workspace/filesystem/filesystem.d.ts +5 -1
  111. package/dist/workspace/filesystem/filesystem.d.ts.map +1 -1
  112. package/dist/workspace/filesystem/index.d.ts +1 -0
  113. package/dist/workspace/filesystem/index.d.ts.map +1 -1
  114. package/dist/workspace/filesystem/local-filesystem.d.ts +17 -1
  115. package/dist/workspace/filesystem/local-filesystem.d.ts.map +1 -1
  116. package/dist/workspace/index.cjs +72 -64
  117. package/dist/workspace/index.d.ts +3 -2
  118. package/dist/workspace/index.d.ts.map +1 -1
  119. package/dist/workspace/index.js +1 -1
  120. package/dist/workspace/lifecycle.d.ts +1 -9
  121. package/dist/workspace/lifecycle.d.ts.map +1 -1
  122. package/dist/workspace/sandbox/index.d.ts +2 -0
  123. package/dist/workspace/sandbox/index.d.ts.map +1 -1
  124. package/dist/workspace/sandbox/local-process-manager.d.ts +18 -0
  125. package/dist/workspace/sandbox/local-process-manager.d.ts.map +1 -0
  126. package/dist/workspace/sandbox/local-sandbox.d.ts +49 -35
  127. package/dist/workspace/sandbox/local-sandbox.d.ts.map +1 -1
  128. package/dist/workspace/sandbox/mastra-sandbox.d.ts +45 -11
  129. package/dist/workspace/sandbox/mastra-sandbox.d.ts.map +1 -1
  130. package/dist/workspace/sandbox/native-sandbox/bubblewrap.d.ts +2 -3
  131. package/dist/workspace/sandbox/native-sandbox/bubblewrap.d.ts.map +1 -1
  132. package/dist/workspace/sandbox/native-sandbox/seatbelt.d.ts +2 -3
  133. package/dist/workspace/sandbox/native-sandbox/seatbelt.d.ts.map +1 -1
  134. package/dist/workspace/sandbox/native-sandbox/wrapper.d.ts +4 -5
  135. package/dist/workspace/sandbox/native-sandbox/wrapper.d.ts.map +1 -1
  136. package/dist/workspace/sandbox/process-manager/index.d.ts +4 -0
  137. package/dist/workspace/sandbox/process-manager/index.d.ts.map +1 -0
  138. package/dist/workspace/sandbox/process-manager/process-handle.d.ts +107 -0
  139. package/dist/workspace/sandbox/process-manager/process-handle.d.ts.map +1 -0
  140. package/dist/workspace/sandbox/process-manager/process-manager.d.ts +59 -0
  141. package/dist/workspace/sandbox/process-manager/process-manager.d.ts.map +1 -0
  142. package/dist/workspace/sandbox/process-manager/types.d.ts +24 -0
  143. package/dist/workspace/sandbox/process-manager/types.d.ts.map +1 -0
  144. package/dist/workspace/sandbox/sandbox.d.ts +38 -2
  145. package/dist/workspace/sandbox/sandbox.d.ts.map +1 -1
  146. package/dist/workspace/sandbox/types.d.ts +9 -2
  147. package/dist/workspace/sandbox/types.d.ts.map +1 -1
  148. package/dist/workspace/sandbox/utils.d.ts +7 -0
  149. package/dist/workspace/sandbox/utils.d.ts.map +1 -0
  150. package/dist/workspace/tools/execute-command.d.ts +53 -2
  151. package/dist/workspace/tools/execute-command.d.ts.map +1 -1
  152. package/dist/workspace/tools/get-process-output.d.ts +6 -0
  153. package/dist/workspace/tools/get-process-output.d.ts.map +1 -0
  154. package/dist/workspace/tools/index.d.ts +4 -1
  155. package/dist/workspace/tools/index.d.ts.map +1 -1
  156. package/dist/workspace/tools/kill-process.d.ts +4 -0
  157. package/dist/workspace/tools/kill-process.d.ts.map +1 -0
  158. package/dist/workspace/tools/output-helpers.d.ts +21 -0
  159. package/dist/workspace/tools/output-helpers.d.ts.map +1 -0
  160. package/dist/workspace/tools/tools.d.ts.map +1 -1
  161. package/dist/workspace/types.d.ts +31 -0
  162. package/dist/workspace/types.d.ts.map +1 -1
  163. package/dist/workspace/utils.d.ts +11 -0
  164. package/dist/workspace/utils.d.ts.map +1 -0
  165. package/dist/workspace/workspace.d.ts +36 -0
  166. package/dist/workspace/workspace.d.ts.map +1 -1
  167. package/package.json +7 -7
  168. package/dist/chunk-3U3XFMGJ.cjs.map +0 -1
  169. package/dist/chunk-5K45E5VE.js.map +0 -1
  170. package/dist/chunk-AYHSPIT6.cjs.map +0 -1
  171. package/dist/chunk-DGS2KGDI.js.map +0 -1
  172. package/dist/chunk-IHDE4CJV.js.map +0 -1
  173. package/dist/chunk-LNKS4TJ6.cjs.map +0 -1
  174. package/dist/chunk-MWGGSA5Q.js.map +0 -1
  175. package/dist/chunk-TVPANHLE.cjs.map +0 -1
  176. package/dist/chunk-VJWRJWSC.cjs.map +0 -1
  177. package/dist/chunk-XB3DA67Q.js.map +0 -1
  178. package/dist/docs/SKILL.md +0 -301
  179. package/dist/docs/assets/SOURCE_MAP.json +0 -1413
  180. package/dist/docs/references/docs-agents-adding-voice.md +0 -353
  181. package/dist/docs/references/docs-agents-agent-approval.md +0 -377
  182. package/dist/docs/references/docs-agents-agent-memory.md +0 -212
  183. package/dist/docs/references/docs-agents-guardrails.md +0 -382
  184. package/dist/docs/references/docs-agents-network-approval.md +0 -275
  185. package/dist/docs/references/docs-agents-networks.md +0 -290
  186. package/dist/docs/references/docs-agents-overview.md +0 -309
  187. package/dist/docs/references/docs-agents-processors.md +0 -632
  188. package/dist/docs/references/docs-agents-structured-output.md +0 -271
  189. package/dist/docs/references/docs-agents-using-tools.md +0 -214
  190. package/dist/docs/references/docs-evals-custom-scorers.md +0 -519
  191. package/dist/docs/references/docs-evals-overview.md +0 -146
  192. package/dist/docs/references/docs-evals-running-in-ci.md +0 -106
  193. package/dist/docs/references/docs-mcp-overview.md +0 -370
  194. package/dist/docs/references/docs-mcp-publishing-mcp-server.md +0 -95
  195. package/dist/docs/references/docs-memory-memory-processors.md +0 -316
  196. package/dist/docs/references/docs-memory-observational-memory.md +0 -246
  197. package/dist/docs/references/docs-memory-overview.md +0 -45
  198. package/dist/docs/references/docs-memory-semantic-recall.md +0 -272
  199. package/dist/docs/references/docs-memory-storage.md +0 -261
  200. package/dist/docs/references/docs-memory-working-memory.md +0 -400
  201. package/dist/docs/references/docs-observability-datasets-overview.md +0 -188
  202. package/dist/docs/references/docs-observability-datasets-running-experiments.md +0 -266
  203. package/dist/docs/references/docs-observability-logging.md +0 -99
  204. package/dist/docs/references/docs-observability-overview.md +0 -70
  205. package/dist/docs/references/docs-observability-tracing-bridges-otel.md +0 -209
  206. package/dist/docs/references/docs-observability-tracing-exporters-arize.md +0 -274
  207. package/dist/docs/references/docs-observability-tracing-exporters-braintrust.md +0 -111
  208. package/dist/docs/references/docs-observability-tracing-exporters-cloud.md +0 -129
  209. package/dist/docs/references/docs-observability-tracing-exporters-datadog.md +0 -187
  210. package/dist/docs/references/docs-observability-tracing-exporters-default.md +0 -211
  211. package/dist/docs/references/docs-observability-tracing-exporters-laminar.md +0 -100
  212. package/dist/docs/references/docs-observability-tracing-exporters-langfuse.md +0 -217
  213. package/dist/docs/references/docs-observability-tracing-exporters-langsmith.md +0 -202
  214. package/dist/docs/references/docs-observability-tracing-exporters-otel.md +0 -479
  215. package/dist/docs/references/docs-observability-tracing-exporters-posthog.md +0 -148
  216. package/dist/docs/references/docs-observability-tracing-overview.md +0 -1114
  217. package/dist/docs/references/docs-rag-chunking-and-embedding.md +0 -183
  218. package/dist/docs/references/docs-rag-graph-rag.md +0 -215
  219. package/dist/docs/references/docs-rag-overview.md +0 -72
  220. package/dist/docs/references/docs-rag-retrieval.md +0 -521
  221. package/dist/docs/references/docs-rag-vector-databases.md +0 -648
  222. package/dist/docs/references/docs-server-auth-auth0.md +0 -222
  223. package/dist/docs/references/docs-server-auth-clerk.md +0 -132
  224. package/dist/docs/references/docs-server-auth-composite-auth.md +0 -234
  225. package/dist/docs/references/docs-server-auth-custom-auth-provider.md +0 -513
  226. package/dist/docs/references/docs-server-auth-firebase.md +0 -272
  227. package/dist/docs/references/docs-server-auth-jwt.md +0 -110
  228. package/dist/docs/references/docs-server-auth-simple-auth.md +0 -178
  229. package/dist/docs/references/docs-server-auth-supabase.md +0 -117
  230. package/dist/docs/references/docs-server-auth-workos.md +0 -190
  231. package/dist/docs/references/docs-server-custom-adapters.md +0 -374
  232. package/dist/docs/references/docs-server-custom-api-routes.md +0 -267
  233. package/dist/docs/references/docs-server-mastra-client.md +0 -243
  234. package/dist/docs/references/docs-server-mastra-server.md +0 -71
  235. package/dist/docs/references/docs-server-middleware.md +0 -228
  236. package/dist/docs/references/docs-server-request-context.md +0 -478
  237. package/dist/docs/references/docs-streaming-events.md +0 -247
  238. package/dist/docs/references/docs-streaming-tool-streaming.md +0 -178
  239. package/dist/docs/references/docs-streaming-workflow-streaming.md +0 -109
  240. package/dist/docs/references/docs-voice-overview.md +0 -979
  241. package/dist/docs/references/docs-voice-speech-to-speech.md +0 -103
  242. package/dist/docs/references/docs-voice-speech-to-text.md +0 -80
  243. package/dist/docs/references/docs-voice-text-to-speech.md +0 -84
  244. package/dist/docs/references/docs-workflows-agents-and-tools.md +0 -170
  245. package/dist/docs/references/docs-workflows-control-flow.md +0 -823
  246. package/dist/docs/references/docs-workflows-error-handling.md +0 -360
  247. package/dist/docs/references/docs-workflows-human-in-the-loop.md +0 -213
  248. package/dist/docs/references/docs-workflows-overview.md +0 -372
  249. package/dist/docs/references/docs-workflows-snapshots.md +0 -238
  250. package/dist/docs/references/docs-workflows-suspend-and-resume.md +0 -205
  251. package/dist/docs/references/docs-workflows-time-travel.md +0 -309
  252. package/dist/docs/references/docs-workflows-workflow-state.md +0 -181
  253. package/dist/docs/references/docs-workspace-filesystem.md +0 -162
  254. package/dist/docs/references/docs-workspace-overview.md +0 -239
  255. package/dist/docs/references/docs-workspace-sandbox.md +0 -63
  256. package/dist/docs/references/docs-workspace-search.md +0 -219
  257. package/dist/docs/references/docs-workspace-skills.md +0 -126
  258. package/dist/docs/references/guides-agent-frameworks-ai-sdk.md +0 -140
  259. package/dist/docs/references/reference-agents-agent.md +0 -142
  260. package/dist/docs/references/reference-agents-generate.md +0 -174
  261. package/dist/docs/references/reference-agents-generateLegacy.md +0 -176
  262. package/dist/docs/references/reference-agents-getDefaultGenerateOptions.md +0 -36
  263. package/dist/docs/references/reference-agents-getDefaultOptions.md +0 -34
  264. package/dist/docs/references/reference-agents-getDefaultStreamOptions.md +0 -36
  265. package/dist/docs/references/reference-agents-getDescription.md +0 -21
  266. package/dist/docs/references/reference-agents-getInstructions.md +0 -34
  267. package/dist/docs/references/reference-agents-getLLM.md +0 -37
  268. package/dist/docs/references/reference-agents-getMemory.md +0 -34
  269. package/dist/docs/references/reference-agents-getModel.md +0 -34
  270. package/dist/docs/references/reference-agents-getTools.md +0 -29
  271. package/dist/docs/references/reference-agents-getVoice.md +0 -34
  272. package/dist/docs/references/reference-agents-listAgents.md +0 -35
  273. package/dist/docs/references/reference-agents-listScorers.md +0 -34
  274. package/dist/docs/references/reference-agents-listTools.md +0 -34
  275. package/dist/docs/references/reference-agents-listWorkflows.md +0 -34
  276. package/dist/docs/references/reference-agents-network.md +0 -134
  277. package/dist/docs/references/reference-ai-sdk-chat-route.md +0 -82
  278. package/dist/docs/references/reference-ai-sdk-network-route.md +0 -74
  279. package/dist/docs/references/reference-ai-sdk-to-ai-sdk-stream.md +0 -232
  280. package/dist/docs/references/reference-ai-sdk-with-mastra.md +0 -59
  281. package/dist/docs/references/reference-ai-sdk-workflow-route.md +0 -79
  282. package/dist/docs/references/reference-auth-auth0.md +0 -73
  283. package/dist/docs/references/reference-auth-clerk.md +0 -36
  284. package/dist/docs/references/reference-auth-firebase.md +0 -80
  285. package/dist/docs/references/reference-auth-jwt.md +0 -26
  286. package/dist/docs/references/reference-auth-supabase.md +0 -33
  287. package/dist/docs/references/reference-auth-workos.md +0 -84
  288. package/dist/docs/references/reference-client-js-agents.md +0 -438
  289. package/dist/docs/references/reference-configuration.md +0 -749
  290. package/dist/docs/references/reference-core-addGateway.md +0 -42
  291. package/dist/docs/references/reference-core-getAgent.md +0 -21
  292. package/dist/docs/references/reference-core-getAgentById.md +0 -21
  293. package/dist/docs/references/reference-core-getDeployer.md +0 -22
  294. package/dist/docs/references/reference-core-getGateway.md +0 -38
  295. package/dist/docs/references/reference-core-getGatewayById.md +0 -41
  296. package/dist/docs/references/reference-core-getLogger.md +0 -22
  297. package/dist/docs/references/reference-core-getMCPServer.md +0 -45
  298. package/dist/docs/references/reference-core-getMCPServerById.md +0 -53
  299. package/dist/docs/references/reference-core-getMemory.md +0 -50
  300. package/dist/docs/references/reference-core-getScorer.md +0 -54
  301. package/dist/docs/references/reference-core-getScorerById.md +0 -54
  302. package/dist/docs/references/reference-core-getServer.md +0 -22
  303. package/dist/docs/references/reference-core-getStorage.md +0 -22
  304. package/dist/docs/references/reference-core-getStoredAgentById.md +0 -89
  305. package/dist/docs/references/reference-core-getTelemetry.md +0 -22
  306. package/dist/docs/references/reference-core-getVector.md +0 -22
  307. package/dist/docs/references/reference-core-getWorkflow.md +0 -40
  308. package/dist/docs/references/reference-core-listAgents.md +0 -21
  309. package/dist/docs/references/reference-core-listGateways.md +0 -40
  310. package/dist/docs/references/reference-core-listLogs.md +0 -38
  311. package/dist/docs/references/reference-core-listLogsByRunId.md +0 -36
  312. package/dist/docs/references/reference-core-listMCPServers.md +0 -51
  313. package/dist/docs/references/reference-core-listMemory.md +0 -56
  314. package/dist/docs/references/reference-core-listScorers.md +0 -29
  315. package/dist/docs/references/reference-core-listStoredAgents.md +0 -93
  316. package/dist/docs/references/reference-core-listVectors.md +0 -22
  317. package/dist/docs/references/reference-core-listWorkflows.md +0 -21
  318. package/dist/docs/references/reference-core-mastra-class.md +0 -66
  319. package/dist/docs/references/reference-core-mastra-model-gateway.md +0 -153
  320. package/dist/docs/references/reference-core-setLogger.md +0 -26
  321. package/dist/docs/references/reference-core-setStorage.md +0 -27
  322. package/dist/docs/references/reference-datasets-addItem.md +0 -35
  323. package/dist/docs/references/reference-datasets-addItems.md +0 -33
  324. package/dist/docs/references/reference-datasets-compareExperiments.md +0 -48
  325. package/dist/docs/references/reference-datasets-create.md +0 -49
  326. package/dist/docs/references/reference-datasets-dataset.md +0 -78
  327. package/dist/docs/references/reference-datasets-datasets-manager.md +0 -84
  328. package/dist/docs/references/reference-datasets-delete.md +0 -23
  329. package/dist/docs/references/reference-datasets-deleteExperiment.md +0 -25
  330. package/dist/docs/references/reference-datasets-deleteItem.md +0 -25
  331. package/dist/docs/references/reference-datasets-deleteItems.md +0 -27
  332. package/dist/docs/references/reference-datasets-get.md +0 -29
  333. package/dist/docs/references/reference-datasets-getDetails.md +0 -45
  334. package/dist/docs/references/reference-datasets-getExperiment.md +0 -28
  335. package/dist/docs/references/reference-datasets-getItem.md +0 -31
  336. package/dist/docs/references/reference-datasets-getItemHistory.md +0 -29
  337. package/dist/docs/references/reference-datasets-list.md +0 -29
  338. package/dist/docs/references/reference-datasets-listExperimentResults.md +0 -37
  339. package/dist/docs/references/reference-datasets-listExperiments.md +0 -31
  340. package/dist/docs/references/reference-datasets-listItems.md +0 -44
  341. package/dist/docs/references/reference-datasets-listVersions.md +0 -31
  342. package/dist/docs/references/reference-datasets-startExperiment.md +0 -60
  343. package/dist/docs/references/reference-datasets-startExperimentAsync.md +0 -41
  344. package/dist/docs/references/reference-datasets-update.md +0 -46
  345. package/dist/docs/references/reference-datasets-updateItem.md +0 -36
  346. package/dist/docs/references/reference-evals-answer-relevancy.md +0 -105
  347. package/dist/docs/references/reference-evals-answer-similarity.md +0 -99
  348. package/dist/docs/references/reference-evals-bias.md +0 -120
  349. package/dist/docs/references/reference-evals-completeness.md +0 -137
  350. package/dist/docs/references/reference-evals-content-similarity.md +0 -101
  351. package/dist/docs/references/reference-evals-context-precision.md +0 -196
  352. package/dist/docs/references/reference-evals-create-scorer.md +0 -270
  353. package/dist/docs/references/reference-evals-faithfulness.md +0 -114
  354. package/dist/docs/references/reference-evals-hallucination.md +0 -220
  355. package/dist/docs/references/reference-evals-keyword-coverage.md +0 -128
  356. package/dist/docs/references/reference-evals-mastra-scorer.md +0 -123
  357. package/dist/docs/references/reference-evals-run-evals.md +0 -138
  358. package/dist/docs/references/reference-evals-scorer-utils.md +0 -330
  359. package/dist/docs/references/reference-evals-textual-difference.md +0 -113
  360. package/dist/docs/references/reference-evals-tone-consistency.md +0 -119
  361. package/dist/docs/references/reference-evals-toxicity.md +0 -123
  362. package/dist/docs/references/reference-harness-harness-class.md +0 -645
  363. package/dist/docs/references/reference-logging-pino-logger.md +0 -117
  364. package/dist/docs/references/reference-memory-deleteMessages.md +0 -40
  365. package/dist/docs/references/reference-memory-memory-class.md +0 -147
  366. package/dist/docs/references/reference-memory-observational-memory.md +0 -565
  367. package/dist/docs/references/reference-observability-tracing-bridges-otel.md +0 -131
  368. package/dist/docs/references/reference-observability-tracing-configuration.md +0 -178
  369. package/dist/docs/references/reference-observability-tracing-exporters-console-exporter.md +0 -138
  370. package/dist/docs/references/reference-observability-tracing-exporters-datadog.md +0 -116
  371. package/dist/docs/references/reference-observability-tracing-instances.md +0 -109
  372. package/dist/docs/references/reference-observability-tracing-interfaces.md +0 -749
  373. package/dist/docs/references/reference-observability-tracing-processors-sensitive-data-filter.md +0 -144
  374. package/dist/docs/references/reference-observability-tracing-spans.md +0 -224
  375. package/dist/docs/references/reference-processors-batch-parts-processor.md +0 -61
  376. package/dist/docs/references/reference-processors-language-detector.md +0 -81
  377. package/dist/docs/references/reference-processors-message-history-processor.md +0 -85
  378. package/dist/docs/references/reference-processors-moderation-processor.md +0 -104
  379. package/dist/docs/references/reference-processors-pii-detector.md +0 -107
  380. package/dist/docs/references/reference-processors-processor-interface.md +0 -525
  381. package/dist/docs/references/reference-processors-prompt-injection-detector.md +0 -71
  382. package/dist/docs/references/reference-processors-semantic-recall-processor.md +0 -123
  383. package/dist/docs/references/reference-processors-system-prompt-scrubber.md +0 -80
  384. package/dist/docs/references/reference-processors-token-limiter-processor.md +0 -113
  385. package/dist/docs/references/reference-processors-tool-call-filter.md +0 -85
  386. package/dist/docs/references/reference-processors-tool-search-processor.md +0 -113
  387. package/dist/docs/references/reference-processors-unicode-normalizer.md +0 -62
  388. package/dist/docs/references/reference-processors-working-memory-processor.md +0 -154
  389. package/dist/docs/references/reference-rag-database-config.md +0 -264
  390. package/dist/docs/references/reference-rag-embeddings.md +0 -92
  391. package/dist/docs/references/reference-server-mastra-server.md +0 -298
  392. package/dist/docs/references/reference-server-register-api-route.md +0 -249
  393. package/dist/docs/references/reference-storage-cloudflare-d1.md +0 -218
  394. package/dist/docs/references/reference-storage-composite.md +0 -235
  395. package/dist/docs/references/reference-storage-lance.md +0 -131
  396. package/dist/docs/references/reference-storage-libsql.md +0 -135
  397. package/dist/docs/references/reference-storage-mongodb.md +0 -262
  398. package/dist/docs/references/reference-storage-mssql.md +0 -155
  399. package/dist/docs/references/reference-storage-overview.md +0 -121
  400. package/dist/docs/references/reference-storage-postgresql.md +0 -529
  401. package/dist/docs/references/reference-storage-upstash.md +0 -160
  402. package/dist/docs/references/reference-streaming-ChunkType.md +0 -292
  403. package/dist/docs/references/reference-streaming-agents-MastraModelOutput.md +0 -182
  404. package/dist/docs/references/reference-streaming-agents-streamLegacy.md +0 -142
  405. package/dist/docs/references/reference-streaming-workflows-observeStream.md +0 -42
  406. package/dist/docs/references/reference-streaming-workflows-resumeStream.md +0 -61
  407. package/dist/docs/references/reference-streaming-workflows-stream.md +0 -88
  408. package/dist/docs/references/reference-streaming-workflows-timeTravelStream.md +0 -142
  409. package/dist/docs/references/reference-templates-overview.md +0 -194
  410. package/dist/docs/references/reference-tools-create-tool.md +0 -237
  411. package/dist/docs/references/reference-tools-graph-rag-tool.md +0 -185
  412. package/dist/docs/references/reference-tools-mcp-client.md +0 -962
  413. package/dist/docs/references/reference-tools-mcp-server.md +0 -1275
  414. package/dist/docs/references/reference-tools-vector-query-tool.md +0 -459
  415. package/dist/docs/references/reference-vectors-libsql.md +0 -305
  416. package/dist/docs/references/reference-vectors-mongodb.md +0 -295
  417. package/dist/docs/references/reference-vectors-pg.md +0 -408
  418. package/dist/docs/references/reference-vectors-upstash.md +0 -294
  419. package/dist/docs/references/reference-voice-composite-voice.md +0 -121
  420. package/dist/docs/references/reference-voice-mastra-voice.md +0 -313
  421. package/dist/docs/references/reference-voice-voice.addInstructions.md +0 -56
  422. package/dist/docs/references/reference-voice-voice.addTools.md +0 -67
  423. package/dist/docs/references/reference-voice-voice.connect.md +0 -94
  424. package/dist/docs/references/reference-voice-voice.events.md +0 -37
  425. package/dist/docs/references/reference-voice-voice.listen.md +0 -164
  426. package/dist/docs/references/reference-voice-voice.on.md +0 -111
  427. package/dist/docs/references/reference-voice-voice.speak.md +0 -157
  428. package/dist/docs/references/reference-workflows-run-methods-cancel.md +0 -86
  429. package/dist/docs/references/reference-workflows-run-methods-restart.md +0 -33
  430. package/dist/docs/references/reference-workflows-run-methods-resume.md +0 -59
  431. package/dist/docs/references/reference-workflows-run-methods-start.md +0 -58
  432. package/dist/docs/references/reference-workflows-run-methods-startAsync.md +0 -67
  433. package/dist/docs/references/reference-workflows-run-methods-timeTravel.md +0 -142
  434. package/dist/docs/references/reference-workflows-run.md +0 -59
  435. package/dist/docs/references/reference-workflows-step.md +0 -119
  436. package/dist/docs/references/reference-workflows-workflow-methods-branch.md +0 -25
  437. package/dist/docs/references/reference-workflows-workflow-methods-commit.md +0 -17
  438. package/dist/docs/references/reference-workflows-workflow-methods-create-run.md +0 -63
  439. package/dist/docs/references/reference-workflows-workflow-methods-dountil.md +0 -25
  440. package/dist/docs/references/reference-workflows-workflow-methods-dowhile.md +0 -25
  441. package/dist/docs/references/reference-workflows-workflow-methods-foreach.md +0 -118
  442. package/dist/docs/references/reference-workflows-workflow-methods-map.md +0 -93
  443. package/dist/docs/references/reference-workflows-workflow-methods-parallel.md +0 -21
  444. package/dist/docs/references/reference-workflows-workflow-methods-sleep.md +0 -35
  445. package/dist/docs/references/reference-workflows-workflow-methods-sleepUntil.md +0 -35
  446. package/dist/docs/references/reference-workflows-workflow-methods-then.md +0 -21
  447. package/dist/docs/references/reference-workflows-workflow.md +0 -157
  448. package/dist/docs/references/reference-workspace-filesystem.md +0 -202
  449. package/dist/docs/references/reference-workspace-local-filesystem.md +0 -327
  450. package/dist/docs/references/reference-workspace-local-sandbox.md +0 -285
  451. package/dist/docs/references/reference-workspace-sandbox.md +0 -81
  452. package/dist/docs/references/reference-workspace-workspace-class.md +0 -226
  453. package/dist/docs/references/reference.md +0 -276
@@ -1 +1 @@
1
- {"version":3,"file":"scorer.d.ts","sourceRoot":"","sources":["../../../src/datasets/experiment/scorer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,KAAK,EAAE,sBAAsB,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AACzF,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAE3C,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAC/D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAE5C;;;GAGG;AACH,wBAAgB,cAAc,CAC5B,MAAM,EAAE,MAAM,EACd,OAAO,CAAC,EAAE,CAAC,YAAY,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,GAAG,MAAM,CAAC,EAAE,GACtD,YAAY,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,EAAE,CAgBpC;AAED;;;GAGG;AACH,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,YAAY,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,EAAE,EAC3C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EAC3C,IAAI,EAAE;IAAE,KAAK,EAAE,OAAO,CAAC;IAAC,WAAW,CAAC,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAAE,EACnF,MAAM,EAAE,OAAO,EACf,OAAO,EAAE,oBAAoB,GAAG,IAAI,EACpC,KAAK,EAAE,MAAM,EACb,UAAU,EAAE,UAAU,EACtB,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,EACd,WAAW,CAAC,EAAE,sBAAsB,EACpC,YAAY,CAAC,EAAE,uBAAuB,GACrC,OAAO,CAAC,YAAY,EAAE,CAAC,CA+CzB"}
@@ -1,69 +1,69 @@
1
1
  'use strict';
2
2
 
3
- var chunkLNKS4TJ6_cjs = require('../chunk-LNKS4TJ6.cjs');
4
- var chunkTL2TTA4X_cjs = require('../chunk-TL2TTA4X.cjs');
3
+ var chunkHB6T4554_cjs = require('../chunk-HB6T4554.cjs');
4
+ var chunkYQG7NBPR_cjs = require('../chunk-YQG7NBPR.cjs');
5
5
 
6
6
 
7
7
 
8
8
  Object.defineProperty(exports, "Dataset", {
9
9
  enumerable: true,
10
- get: function () { return chunkLNKS4TJ6_cjs.Dataset; }
10
+ get: function () { return chunkHB6T4554_cjs.Dataset; }
11
11
  });
12
12
  Object.defineProperty(exports, "DatasetsManager", {
13
13
  enumerable: true,
14
- get: function () { return chunkLNKS4TJ6_cjs.DatasetsManager; }
14
+ get: function () { return chunkHB6T4554_cjs.DatasetsManager; }
15
15
  });
16
16
  Object.defineProperty(exports, "compareExperiments", {
17
17
  enumerable: true,
18
- get: function () { return chunkLNKS4TJ6_cjs.compareExperiments; }
18
+ get: function () { return chunkHB6T4554_cjs.compareExperiments; }
19
19
  });
20
20
  Object.defineProperty(exports, "computeMean", {
21
21
  enumerable: true,
22
- get: function () { return chunkLNKS4TJ6_cjs.computeMean; }
22
+ get: function () { return chunkHB6T4554_cjs.computeMean; }
23
23
  });
24
24
  Object.defineProperty(exports, "computeScorerStats", {
25
25
  enumerable: true,
26
- get: function () { return chunkLNKS4TJ6_cjs.computeScorerStats; }
26
+ get: function () { return chunkHB6T4554_cjs.computeScorerStats; }
27
27
  });
28
28
  Object.defineProperty(exports, "executeTarget", {
29
29
  enumerable: true,
30
- get: function () { return chunkLNKS4TJ6_cjs.executeTarget; }
30
+ get: function () { return chunkHB6T4554_cjs.executeTarget; }
31
31
  });
32
32
  Object.defineProperty(exports, "isRegression", {
33
33
  enumerable: true,
34
- get: function () { return chunkLNKS4TJ6_cjs.isRegression; }
34
+ get: function () { return chunkHB6T4554_cjs.isRegression; }
35
35
  });
36
36
  Object.defineProperty(exports, "resolveScorers", {
37
37
  enumerable: true,
38
- get: function () { return chunkLNKS4TJ6_cjs.resolveScorers; }
38
+ get: function () { return chunkHB6T4554_cjs.resolveScorers; }
39
39
  });
40
40
  Object.defineProperty(exports, "runExperiment", {
41
41
  enumerable: true,
42
- get: function () { return chunkLNKS4TJ6_cjs.runExperiment; }
42
+ get: function () { return chunkHB6T4554_cjs.runExperiment; }
43
43
  });
44
44
  Object.defineProperty(exports, "runScorersForItem", {
45
45
  enumerable: true,
46
- get: function () { return chunkLNKS4TJ6_cjs.runScorersForItem; }
46
+ get: function () { return chunkHB6T4554_cjs.runScorersForItem; }
47
47
  });
48
48
  Object.defineProperty(exports, "SchemaUpdateValidationError", {
49
49
  enumerable: true,
50
- get: function () { return chunkTL2TTA4X_cjs.SchemaUpdateValidationError; }
50
+ get: function () { return chunkYQG7NBPR_cjs.SchemaUpdateValidationError; }
51
51
  });
52
52
  Object.defineProperty(exports, "SchemaValidationError", {
53
53
  enumerable: true,
54
- get: function () { return chunkTL2TTA4X_cjs.SchemaValidationError; }
54
+ get: function () { return chunkYQG7NBPR_cjs.SchemaValidationError; }
55
55
  });
56
56
  Object.defineProperty(exports, "SchemaValidator", {
57
57
  enumerable: true,
58
- get: function () { return chunkTL2TTA4X_cjs.SchemaValidator; }
58
+ get: function () { return chunkYQG7NBPR_cjs.SchemaValidator; }
59
59
  });
60
60
  Object.defineProperty(exports, "createValidator", {
61
61
  enumerable: true,
62
- get: function () { return chunkTL2TTA4X_cjs.createValidator; }
62
+ get: function () { return chunkYQG7NBPR_cjs.createValidator; }
63
63
  });
64
64
  Object.defineProperty(exports, "getSchemaValidator", {
65
65
  enumerable: true,
66
- get: function () { return chunkTL2TTA4X_cjs.getSchemaValidator; }
66
+ get: function () { return chunkYQG7NBPR_cjs.getSchemaValidator; }
67
67
  });
68
68
  //# sourceMappingURL=index.cjs.map
69
69
  //# sourceMappingURL=index.cjs.map
@@ -1,4 +1,4 @@
1
- export { Dataset, DatasetsManager, compareExperiments, computeMean, computeScorerStats, executeTarget, isRegression, resolveScorers, runExperiment, runScorersForItem } from '../chunk-DGS2KGDI.js';
2
- export { SchemaUpdateValidationError, SchemaValidationError, SchemaValidator, createValidator, getSchemaValidator } from '../chunk-EEU5NHHU.js';
1
+ export { Dataset, DatasetsManager, compareExperiments, computeMean, computeScorerStats, executeTarget, isRegression, resolveScorers, runExperiment, runScorersForItem } from '../chunk-KUXNBWN7.js';
2
+ export { SchemaUpdateValidationError, SchemaValidationError, SchemaValidator, createValidator, getSchemaValidator } from '../chunk-DFCRXDVK.js';
3
3
  //# sourceMappingURL=index.js.map
4
4
  //# sourceMappingURL=index.js.map
@@ -1,78 +1,78 @@
1
1
  'use strict';
2
2
 
3
- var chunk3U3XFMGJ_cjs = require('../chunk-3U3XFMGJ.cjs');
4
- var chunkVJWRJWSC_cjs = require('../chunk-VJWRJWSC.cjs');
5
- var chunkTVPANHLE_cjs = require('../chunk-TVPANHLE.cjs');
3
+ var chunkQTAS3HND_cjs = require('../chunk-QTAS3HND.cjs');
4
+ var chunk2X66GWF5_cjs = require('../chunk-2X66GWF5.cjs');
5
+ var chunkSBOHDNIZ_cjs = require('../chunk-SBOHDNIZ.cjs');
6
6
 
7
7
 
8
8
 
9
9
  Object.defineProperty(exports, "runEvals", {
10
10
  enumerable: true,
11
- get: function () { return chunk3U3XFMGJ_cjs.runEvals; }
11
+ get: function () { return chunkQTAS3HND_cjs.runEvals; }
12
12
  });
13
13
  Object.defineProperty(exports, "MastraScorer", {
14
14
  enumerable: true,
15
- get: function () { return chunkVJWRJWSC_cjs.MastraScorer; }
15
+ get: function () { return chunk2X66GWF5_cjs.MastraScorer; }
16
16
  });
17
17
  Object.defineProperty(exports, "createScorer", {
18
18
  enumerable: true,
19
- get: function () { return chunkVJWRJWSC_cjs.createScorer; }
19
+ get: function () { return chunk2X66GWF5_cjs.createScorer; }
20
20
  });
21
21
  Object.defineProperty(exports, "listScoresResponseSchema", {
22
22
  enumerable: true,
23
- get: function () { return chunkTVPANHLE_cjs.listScoresResponseSchema; }
23
+ get: function () { return chunkSBOHDNIZ_cjs.listScoresResponseSchema; }
24
24
  });
25
25
  Object.defineProperty(exports, "saveScorePayloadSchema", {
26
26
  enumerable: true,
27
- get: function () { return chunkTVPANHLE_cjs.saveScorePayloadSchema; }
27
+ get: function () { return chunkSBOHDNIZ_cjs.saveScorePayloadSchema; }
28
28
  });
29
29
  Object.defineProperty(exports, "scoreResultSchema", {
30
30
  enumerable: true,
31
- get: function () { return chunkTVPANHLE_cjs.scoreResultSchema; }
31
+ get: function () { return chunkSBOHDNIZ_cjs.scoreResultSchema; }
32
32
  });
33
33
  Object.defineProperty(exports, "scoreRowDataSchema", {
34
34
  enumerable: true,
35
- get: function () { return chunkTVPANHLE_cjs.scoreRowDataSchema; }
35
+ get: function () { return chunkSBOHDNIZ_cjs.scoreRowDataSchema; }
36
36
  });
37
37
  Object.defineProperty(exports, "scoringEntityTypeSchema", {
38
38
  enumerable: true,
39
- get: function () { return chunkTVPANHLE_cjs.scoringEntityTypeSchema; }
39
+ get: function () { return chunkSBOHDNIZ_cjs.scoringEntityTypeSchema; }
40
40
  });
41
41
  Object.defineProperty(exports, "scoringExtractStepResultSchema", {
42
42
  enumerable: true,
43
- get: function () { return chunkTVPANHLE_cjs.scoringExtractStepResultSchema; }
43
+ get: function () { return chunkSBOHDNIZ_cjs.scoringExtractStepResultSchema; }
44
44
  });
45
45
  Object.defineProperty(exports, "scoringHookInputSchema", {
46
46
  enumerable: true,
47
- get: function () { return chunkTVPANHLE_cjs.scoringHookInputSchema; }
47
+ get: function () { return chunkSBOHDNIZ_cjs.scoringHookInputSchema; }
48
48
  });
49
49
  Object.defineProperty(exports, "scoringInputSchema", {
50
50
  enumerable: true,
51
- get: function () { return chunkTVPANHLE_cjs.scoringInputSchema; }
51
+ get: function () { return chunkSBOHDNIZ_cjs.scoringInputSchema; }
52
52
  });
53
53
  Object.defineProperty(exports, "scoringInputWithExtractStepResultAndAnalyzeStepResultSchema", {
54
54
  enumerable: true,
55
- get: function () { return chunkTVPANHLE_cjs.scoringInputWithExtractStepResultAndAnalyzeStepResultSchema; }
55
+ get: function () { return chunkSBOHDNIZ_cjs.scoringInputWithExtractStepResultAndAnalyzeStepResultSchema; }
56
56
  });
57
57
  Object.defineProperty(exports, "scoringInputWithExtractStepResultAndScoreAndReasonSchema", {
58
58
  enumerable: true,
59
- get: function () { return chunkTVPANHLE_cjs.scoringInputWithExtractStepResultAndScoreAndReasonSchema; }
59
+ get: function () { return chunkSBOHDNIZ_cjs.scoringInputWithExtractStepResultAndScoreAndReasonSchema; }
60
60
  });
61
61
  Object.defineProperty(exports, "scoringInputWithExtractStepResultSchema", {
62
62
  enumerable: true,
63
- get: function () { return chunkTVPANHLE_cjs.scoringInputWithExtractStepResultSchema; }
63
+ get: function () { return chunkSBOHDNIZ_cjs.scoringInputWithExtractStepResultSchema; }
64
64
  });
65
65
  Object.defineProperty(exports, "scoringPromptsSchema", {
66
66
  enumerable: true,
67
- get: function () { return chunkTVPANHLE_cjs.scoringPromptsSchema; }
67
+ get: function () { return chunkSBOHDNIZ_cjs.scoringPromptsSchema; }
68
68
  });
69
69
  Object.defineProperty(exports, "scoringSourceSchema", {
70
70
  enumerable: true,
71
- get: function () { return chunkTVPANHLE_cjs.scoringSourceSchema; }
71
+ get: function () { return chunkSBOHDNIZ_cjs.scoringSourceSchema; }
72
72
  });
73
73
  Object.defineProperty(exports, "scoringValueSchema", {
74
74
  enumerable: true,
75
- get: function () { return chunkTVPANHLE_cjs.scoringValueSchema; }
75
+ get: function () { return chunkSBOHDNIZ_cjs.scoringValueSchema; }
76
76
  });
77
77
  //# sourceMappingURL=index.cjs.map
78
78
  //# sourceMappingURL=index.cjs.map
@@ -1,5 +1,5 @@
1
- export { runEvals } from '../chunk-MWGGSA5Q.js';
2
- export { MastraScorer, createScorer } from '../chunk-IHDE4CJV.js';
3
- export { listScoresResponseSchema, saveScorePayloadSchema, scoreResultSchema, scoreRowDataSchema, scoringEntityTypeSchema, scoringExtractStepResultSchema, scoringHookInputSchema, scoringInputSchema, scoringInputWithExtractStepResultAndAnalyzeStepResultSchema, scoringInputWithExtractStepResultAndScoreAndReasonSchema, scoringInputWithExtractStepResultSchema, scoringPromptsSchema, scoringSourceSchema, scoringValueSchema } from '../chunk-5K45E5VE.js';
1
+ export { runEvals } from '../chunk-T6GAM3SQ.js';
2
+ export { MastraScorer, createScorer } from '../chunk-QSHV7GPT.js';
3
+ export { listScoresResponseSchema, saveScorePayloadSchema, scoreResultSchema, scoreRowDataSchema, scoringEntityTypeSchema, scoringExtractStepResultSchema, scoringHookInputSchema, scoringInputSchema, scoringInputWithExtractStepResultAndAnalyzeStepResultSchema, scoringInputWithExtractStepResultAndScoreAndReasonSchema, scoringInputWithExtractStepResultSchema, scoringPromptsSchema, scoringSourceSchema, scoringValueSchema } from '../chunk-GPJGPARM.js';
4
4
  //# sourceMappingURL=index.js.map
5
5
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- var chunk5VQPSWPG_cjs = require('../../chunk-5VQPSWPG.cjs');
4
- var chunkTVPANHLE_cjs = require('../../chunk-TVPANHLE.cjs');
3
+ var chunkRABITNTG_cjs = require('../../chunk-RABITNTG.cjs');
4
+ var chunkSBOHDNIZ_cjs = require('../../chunk-SBOHDNIZ.cjs');
5
5
  var chunk4U7ZLI36_cjs = require('../../chunk-4U7ZLI36.cjs');
6
6
  var pMap = require('p-map');
7
7
  var z = require('zod');
@@ -235,7 +235,7 @@ function transformTraceToScorerInputAndOutput(trace) {
235
235
  }
236
236
 
237
237
  // src/evals/scoreTraces/scoreTracesWorkflow.ts
238
- var getTraceStep = chunk5VQPSWPG_cjs.createStep({
238
+ var getTraceStep = chunkRABITNTG_cjs.createStep({
239
239
  id: "__process-trace-scoring",
240
240
  inputSchema: z__default.default.object({
241
241
  targets: z__default.default.array(
@@ -358,7 +358,8 @@ async function runScorerOnTarget({
358
358
  scorer: {
359
359
  id: scorer.id,
360
360
  name: scorer.name || scorer.id,
361
- description: scorer.description
361
+ description: scorer.description,
362
+ hasJudge: !!scorer.judge
362
363
  },
363
364
  traceId: target.traceId,
364
365
  spanId: target.spanId,
@@ -381,7 +382,7 @@ async function validateAndSaveScore({ storage, scorerResult }) {
381
382
  text: "Scores storage domain is not available"
382
383
  });
383
384
  }
384
- const payloadToSave = chunkTVPANHLE_cjs.saveScorePayloadSchema.parse(scorerResult);
385
+ const payloadToSave = chunkSBOHDNIZ_cjs.saveScorePayloadSchema.parse(scorerResult);
385
386
  const result = await scoresStore.saveScore(payloadToSave);
386
387
  return result.score;
387
388
  }
@@ -432,7 +433,7 @@ async function attachScoreToSpan({
432
433
  updates: { links: [...existingLinks, link] }
433
434
  });
434
435
  }
435
- var scoreTracesWorkflow = chunk5VQPSWPG_cjs.createWorkflow({
436
+ var scoreTracesWorkflow = chunkRABITNTG_cjs.createWorkflow({
436
437
  id: "__batch-scoring-traces",
437
438
  inputSchema: z__default.default.object({
438
439
  targets: z__default.default.array(
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/evals/scoreTraces/scoreTraces.ts","../../../src/evals/scoreTraces/utils.ts","../../../src/evals/scoreTraces/scoreTracesWorkflow.ts"],"names":["MastraError","createStep","z","pMap","span","saveScorePayloadSchema","createWorkflow"],"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Y,CAAA,CAAE,MAAA,EAAO","file":"index.cjs","sourcesContent":["import { MastraError } from '../../error';\nimport type { Mastra } from '../../mastra';\n\nexport async function scoreTraces({\n scorerId,\n targets,\n mastra,\n}: {\n scorerId: string;\n targets: { traceId: string; spanId?: string }[];\n mastra: Mastra;\n}) {\n const workflow = mastra.__getInternalWorkflow('__batch-scoring-traces');\n try {\n const run = await workflow.createRun();\n\n await run.start({ inputData: { targets, scorerId } });\n } catch (error) {\n const mastraError = new MastraError(\n {\n category: 'SYSTEM',\n domain: 'SCORER',\n id: 'MASTRA_SCORER_FAILED_TO_RUN_TRACE_SCORING',\n details: {\n scorerId,\n targets: JSON.stringify(targets),\n },\n },\n error,\n );\n mastra.getLogger()?.trackException(mastraError);\n mastra.getLogger()?.error(mastraError.toString());\n }\n}\n","import type { MastraDBMessage } from '../../agent';\nimport { SpanType } from '../../observability';\nimport type { SpanRecord, TraceRecord } from '../../storage';\nimport type { ScorerRunInputForAgent, ScorerRunOutputForAgent } from '../types';\n\n// Types for span input/output structures\ninterface SpanMessage {\n role: string;\n content: string | Array<{ type: string; text: string }>;\n}\n\ninterface SpanInputWithMessages {\n messages: SpanMessage[];\n}\n\ninterface SpanOutputWithText {\n text?: string;\n}\n\n// Type guards for span data\nfunction isSpanMessage(value: unknown): value is SpanMessage {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'role' in value &&\n typeof (value as SpanMessage).role === 'string' &&\n 'content' in value\n );\n}\n\nfunction hasMessagesArray(value: unknown): value is SpanInputWithMessages {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'messages' in value &&\n Array.isArray((value as SpanInputWithMessages).messages)\n );\n}\n\nfunction hasTextProperty(value: unknown): value is SpanOutputWithText {\n return typeof value === 'object' && value !== null && 'text' in value;\n}\n\n// // Span tree structure for efficient lookups\ninterface SpanTree {\n spanMap: Map<string, SpanRecord>;\n childrenMap: Map<string, SpanRecord[]>;\n rootSpans: SpanRecord[];\n}\n\n/**\n * Build a hierarchical span tree with efficient lookup maps\n */\nexport function buildSpanTree(spans: SpanRecord[]): SpanTree {\n const spanMap = new Map<string, SpanRecord>();\n const childrenMap = new Map<string, SpanRecord[]>();\n const rootSpans: SpanRecord[] = [];\n\n // First pass: build span map\n for (const span of spans) {\n spanMap.set(span.spanId, span);\n }\n\n // Second pass: build parent-child relationships\n for (const span of spans) {\n if (span.parentSpanId == null) {\n // Root span (parentSpanId is null or undefined)\n rootSpans.push(span);\n } else {\n const siblings = childrenMap.get(span.parentSpanId) || [];\n siblings.push(span);\n childrenMap.set(span.parentSpanId, siblings);\n }\n }\n\n // Sort children by startedAt timestamp for temporal ordering\n for (const children of childrenMap.values()) {\n children.sort((a, b) => new Date(a.startedAt).getTime() - new Date(b.startedAt).getTime());\n }\n\n // Sort root spans by startedAt\n rootSpans.sort((a, b) => new Date(a.startedAt).getTime() - new Date(b.startedAt).getTime());\n\n return { spanMap, childrenMap, rootSpans };\n}\n\n/**\n * Extract children spans of a specific type\n */\nfunction getChildrenOfType<T extends SpanRecord>(spanTree: SpanTree, parentSpanId: string, spanType: SpanType): T[] {\n const children = spanTree.childrenMap.get(parentSpanId) || [];\n return children.filter(span => span.spanType === spanType) as T[];\n}\n\n/**\n * Normalize message content to string format\n * For arrays with multiple text parts, returns only the last text part (AI SDK convention)\n */\nfunction normalizeMessageContent(content: string | Array<{ type: string; text: string }>): string {\n if (typeof content === 'string') {\n return content;\n }\n\n // Extract text parts and return only the last one (AI SDK convention)\n const textParts = content.filter(part => part.type === 'text');\n return textParts.length > 0 ? textParts[textParts.length - 1]?.text || '' : '';\n}\n\n/**\n * Create MastraDBMessage directly from span message data\n */\nfunction createMastraDBMessage(\n message: { role: string; content: string | Array<{ type: string; text: string }> },\n createdAt: Date,\n id: string = '',\n): MastraDBMessage {\n const contentText = normalizeMessageContent(message.content);\n const role = message.role as 'user' | 'assistant' | 'system';\n\n return {\n id,\n role,\n content: {\n format: 2,\n parts: [{ type: 'text', text: contentText }],\n content: contentText,\n },\n createdAt: new Date(createdAt),\n };\n}\n\n/**\n * Extract input messages from agent run span\n */\nfunction extractInputMessages(agentSpan: SpanRecord): MastraDBMessage[] {\n const input = agentSpan.input;\n\n // Handle different input formats\n if (typeof input === 'string') {\n return [\n createMastraDBMessage(\n {\n role: 'user',\n content: input,\n },\n agentSpan.startedAt,\n ),\n ];\n }\n\n if (Array.isArray(input)) {\n const messages = input.filter(isSpanMessage) as SpanMessage[];\n return messages.map(msg => createMastraDBMessage(msg, agentSpan.startedAt));\n }\n\n if (hasMessagesArray(input)) {\n const messages = input.messages.filter(isSpanMessage) as SpanMessage[];\n return messages.map(msg => createMastraDBMessage(msg, agentSpan.startedAt));\n }\n return [];\n}\n\n/**\n * Extract system messages from LLM span\n */\nfunction extractSystemMessages(llmSpan: SpanRecord): Array<{ role: 'system'; content: string }> {\n const input = llmSpan.input;\n if (!hasMessagesArray(input)) {\n return [];\n }\n return input.messages\n .filter((msg): msg is SpanMessage & { role: 'system' } => isSpanMessage(msg) && msg.role === 'system')\n .map(msg => ({\n role: 'system' as const,\n content: normalizeMessageContent(msg.content),\n }));\n}\n\n/**\n * Extract conversation history (remembered messages) from LLM span\n * Excludes system messages and the current input message\n */\nfunction extractRememberedMessages(llmSpan: SpanRecord, currentInputContent: string): MastraDBMessage[] {\n const input = llmSpan.input;\n if (!hasMessagesArray(input)) {\n return [];\n }\n const filtered = input.messages.filter(isSpanMessage) as unknown as SpanMessage[];\n const messages = filtered\n .filter(msg => msg.role !== 'system')\n .filter(msg => normalizeMessageContent(msg.content) !== currentInputContent);\n\n return messages.map(msg => createMastraDBMessage(msg, llmSpan.startedAt));\n}\n\n/**\n * Reconstruct tool invocations from tool call spans\n */\nfunction reconstructToolInvocations(spanTree: SpanTree, parentSpanId: string) {\n const toolSpans = getChildrenOfType<SpanRecord>(spanTree, parentSpanId, SpanType.TOOL_CALL);\n\n return toolSpans.map(toolSpan => ({\n toolCallId: toolSpan.spanId,\n toolName: toolSpan.entityName ?? toolSpan.entityId ?? 'unknown',\n toolId: toolSpan.entityId,\n args: toolSpan.input || {},\n result: toolSpan.output || {},\n state: 'result' as const,\n }));\n}\n\n/**\n * Validate trace structure and throw descriptive errors\n */\nexport function validateTrace(trace: TraceRecord): void {\n if (!trace) {\n throw new Error('Trace is null or undefined');\n }\n\n if (!trace.spans || !Array.isArray(trace.spans)) {\n throw new Error('Trace must have a spans array');\n }\n\n if (trace.spans.length === 0) {\n throw new Error('Trace has no spans');\n }\n\n // Check for circular references in parent-child relationships\n const spanIds = new Set(trace.spans.map(span => span.spanId));\n for (const span of trace.spans) {\n if (span.parentSpanId && !spanIds.has(span.parentSpanId)) {\n throw new Error(`Span ${span.spanId} references non-existent parent ${span.parentSpanId}`);\n }\n }\n}\n\n/**\n * Find the most recent model span that contains conversation history\n */\nfunction findPrimaryLLMSpan(spanTree: SpanTree, rootAgentSpan: SpanRecord): SpanRecord {\n const directLLMSpans = getChildrenOfType<SpanRecord>(spanTree, rootAgentSpan.spanId, SpanType.MODEL_GENERATION);\n if (directLLMSpans.length > 0) {\n // There should only be one model generation span per agent run which is a direct child of the root agent span\n return directLLMSpans[0]!;\n }\n\n throw new Error('No model generation span found in trace');\n}\n\n/**\n * Extract common trace validation and span tree building logic\n */\nfunction prepareTraceForTransformation(trace: TraceRecord) {\n validateTrace(trace);\n const spanTree = buildSpanTree(trace.spans);\n\n // Find the root agent run span\n const rootAgentSpan = spanTree.rootSpans.find(span => span.spanType === 'agent_run') as SpanRecord | undefined;\n\n if (!rootAgentSpan) {\n throw new Error('No root agent_run span found in trace');\n }\n\n return { spanTree, rootAgentSpan };\n}\n\nexport function transformTraceToScorerInputAndOutput(trace: TraceRecord): {\n input: ScorerRunInputForAgent;\n output: ScorerRunOutputForAgent;\n} {\n const { spanTree, rootAgentSpan } = prepareTraceForTransformation(trace);\n\n if (!rootAgentSpan.output) {\n throw new Error('Root agent span has no output');\n }\n\n // Build input\n const primaryLLMSpan = findPrimaryLLMSpan(spanTree, rootAgentSpan);\n const inputMessages = extractInputMessages(rootAgentSpan);\n const systemMessages = extractSystemMessages(primaryLLMSpan);\n\n // Extract remembered messages from LLM span (excluding current input)\n const currentInputContent = inputMessages[0]?.content.content || '';\n const rememberedMessages = extractRememberedMessages(primaryLLMSpan, currentInputContent);\n\n const input = {\n inputMessages,\n rememberedMessages,\n systemMessages,\n taggedSystemMessages: {}, // Todo: Support tagged system messages\n };\n\n // Build output\n const toolInvocations = reconstructToolInvocations(spanTree, rootAgentSpan.spanId);\n const responseText = hasTextProperty(rootAgentSpan.output) ? (rootAgentSpan.output.text ?? '') : '';\n\n // Build parts array: tool invocations first, then text\n const parts: Array<{ type: 'tool-invocation'; toolInvocation: any } | { type: 'text'; text: string }> = [];\n\n // Add tool invocation parts\n for (const toolInvocation of toolInvocations) {\n parts.push({\n type: 'tool-invocation',\n toolInvocation,\n });\n }\n\n // Add text part if present\n if (responseText.trim()) {\n parts.push({\n type: 'text',\n text: responseText,\n });\n }\n\n const responseMessage: MastraDBMessage = {\n id: '',\n role: 'assistant',\n content: {\n format: 2,\n parts: parts as any, // Type assertion needed due to providerMetadata optional field\n content: responseText,\n toolInvocations, // Always include, even if empty array\n },\n createdAt: new Date(rootAgentSpan.endedAt || rootAgentSpan.startedAt),\n };\n\n const output: MastraDBMessage[] = [responseMessage];\n\n return {\n input,\n output,\n };\n}\n","import pMap from 'p-map';\nimport z from 'zod';\nimport { ErrorCategory, ErrorDomain, MastraError } from '../../error';\nimport { InternalSpans } from '../../observability';\nimport type { TracingContext } from '../../observability';\nimport type { SpanRecord, TraceRecord, MastraStorage } from '../../storage';\nimport { createStep, createWorkflow } from '../../workflows/evented';\nimport type { MastraScorer, ScorerRun } from '../base';\nimport type { ScoreRowData } from '../types';\nimport { saveScorePayloadSchema } from '../types';\nimport { transformTraceToScorerInputAndOutput } from './utils';\n\nconst getTraceStep = createStep({\n id: '__process-trace-scoring',\n inputSchema: z.object({\n targets: z.array(\n z.object({\n traceId: z.string(),\n spanId: z.string().optional(),\n }),\n ),\n scorerId: z.string(),\n }),\n outputSchema: z.any(),\n execute: async ({ inputData, tracingContext, mastra }) => {\n const logger = mastra.getLogger();\n if (!logger) {\n console.warn(\n '[scoreTracesWorkflow] Logger not initialized: no debug or error logs will be recorded for scoring traces.',\n );\n }\n\n const storage = mastra.getStorage();\n if (!storage) {\n const mastraError = new MastraError({\n id: 'MASTRA_STORAGE_NOT_FOUND_FOR_TRACE_SCORING',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n text: 'Storage not found for trace scoring',\n details: {\n scorerId: inputData.scorerId,\n },\n });\n logger?.error(mastraError.toString());\n logger?.trackException(mastraError);\n return;\n }\n\n let scorer: MastraScorer | undefined;\n try {\n scorer = mastra.getScorerById(inputData.scorerId);\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MASTRA_SCORER_NOT_FOUND_FOR_TRACE_SCORING',\n domain: ErrorDomain.SCORER,\n category: ErrorCategory.SYSTEM,\n text: `Scorer not found for trace scoring`,\n details: {\n scorerId: inputData.scorerId,\n },\n },\n error,\n );\n logger?.error(mastraError.toString());\n logger?.trackException(mastraError);\n return;\n }\n\n await pMap(\n inputData.targets,\n async target => {\n try {\n await runScorerOnTarget({ storage, scorer, target, tracingContext });\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MASTRA_SCORER_FAILED_TO_RUN_SCORER_ON_TRACE',\n domain: ErrorDomain.SCORER,\n category: ErrorCategory.SYSTEM,\n details: {\n scorerId: scorer.id,\n spanId: target.spanId || '',\n traceId: target.traceId,\n },\n },\n error,\n );\n logger?.error(mastraError.toString());\n logger?.trackException(mastraError);\n }\n },\n { concurrency: 3 },\n );\n },\n});\n\nexport async function runScorerOnTarget({\n storage,\n scorer,\n target,\n tracingContext,\n}: {\n storage: MastraStorage;\n scorer: MastraScorer;\n target: { traceId: string; spanId?: string };\n tracingContext: TracingContext;\n}) {\n // TODO: add storage api to get a single span\n const observabilityStore = await storage.getStore('observability');\n if (!observabilityStore) {\n throw new MastraError({\n id: 'MASTRA_OBSERVABILITY_STORAGE_NOT_AVAILABLE',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n text: 'Observability storage domain is not available',\n });\n }\n const trace = await observabilityStore.getTrace({ traceId: target.traceId });\n if (!trace) {\n throw new Error(`Trace not found for scoring, traceId: ${target.traceId}`);\n }\n\n let span: SpanRecord | undefined;\n if (target.spanId) {\n span = trace.spans.find(span => span.spanId === target.spanId);\n } else {\n span = trace.spans.find(span => span.parentSpanId === null);\n }\n\n if (!span) {\n throw new Error(\n `Span not found for scoring, traceId: ${target.traceId}, spanId: ${target.spanId ?? 'Not provided'}`,\n );\n }\n\n const scorerRun = buildScorerRun({\n scorerType: scorer.type === 'agent' ? 'agent' : undefined,\n tracingContext,\n trace,\n targetSpan: span,\n });\n\n const result = await scorer.run(scorerRun);\n const scorerResult = {\n ...result,\n scorer: {\n id: scorer.id,\n name: scorer.name || scorer.id,\n description: scorer.description,\n },\n traceId: target.traceId,\n spanId: target.spanId,\n entityId: span.entityId || span.entityName || 'unknown',\n entityType: span.spanType,\n entity: { traceId: span.traceId, spanId: span.spanId },\n source: 'TEST',\n scorerId: scorer.id,\n };\n\n const savedScoreRecord = await validateAndSaveScore({ storage, scorerResult });\n await attachScoreToSpan({ storage, span, scoreRecord: savedScoreRecord });\n}\n\nasync function validateAndSaveScore({ storage, scorerResult }: { storage: MastraStorage; scorerResult: ScorerRun }) {\n const scoresStore = await storage.getStore('scores');\n if (!scoresStore) {\n throw new MastraError({\n id: 'MASTRA_SCORES_STORAGE_NOT_AVAILABLE',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n text: 'Scores storage domain is not available',\n });\n }\n const payloadToSave = saveScorePayloadSchema.parse(scorerResult);\n const result = await scoresStore.saveScore(payloadToSave);\n return result.score;\n}\n\nfunction buildScorerRun({\n scorerType,\n tracingContext,\n trace,\n targetSpan,\n}: {\n scorerType?: string;\n tracingContext: TracingContext;\n trace: TraceRecord;\n targetSpan: SpanRecord;\n}) {\n let runPayload: ScorerRun;\n if (scorerType === 'agent') {\n const { input, output } = transformTraceToScorerInputAndOutput(trace);\n runPayload = {\n input,\n output,\n };\n } else {\n runPayload = { input: targetSpan.input, output: targetSpan.output };\n }\n\n runPayload.tracingContext = tracingContext;\n return runPayload;\n}\n\nasync function attachScoreToSpan({\n storage,\n span,\n scoreRecord,\n}: {\n storage: MastraStorage;\n span: SpanRecord;\n scoreRecord: ScoreRowData;\n}) {\n const observabilityStore = await storage.getStore('observability');\n if (!observabilityStore) {\n throw new MastraError({\n id: 'MASTRA_OBSERVABILITY_STORAGE_NOT_AVAILABLE',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n text: 'Observability storage domain is not available',\n });\n }\n const existingLinks = span.links || [];\n const link = {\n type: 'score',\n scoreId: scoreRecord.id,\n scorerName: scoreRecord.scorer.id,\n score: scoreRecord.score,\n createdAt: scoreRecord.createdAt,\n };\n await observabilityStore.updateSpan({\n spanId: span.spanId,\n traceId: span.traceId,\n updates: { links: [...existingLinks, link] },\n });\n}\n\nexport const scoreTracesWorkflow = createWorkflow({\n id: '__batch-scoring-traces',\n inputSchema: z.object({\n targets: z.array(\n z.object({\n traceId: z.string(),\n spanId: z.string().optional(),\n }),\n ),\n scorerId: z.string(),\n }),\n outputSchema: z.any(),\n steps: [getTraceStep],\n options: {\n tracingPolicy: {\n internal: InternalSpans.ALL,\n },\n validateInputs: false,\n },\n});\n\nscoreTracesWorkflow.then(getTraceStep).commit();\n"]}
1
+ {"version":3,"sources":["../../../src/evals/scoreTraces/scoreTraces.ts","../../../src/evals/scoreTraces/utils.ts","../../../src/evals/scoreTraces/scoreTracesWorkflow.ts"],"names":["MastraError","createStep","z","pMap","span","saveScorePayloadSchema","createWorkflow"],"mappings":";;;;;;;;;;;;;;AAGA,eAAsB,WAAA,CAAY;AAAA,EAChC,QAAA;AAAA,EACA,OAAA;AAAA,EACA;AACF,CAAA,EAIG;AACD,EAAA,MAAM,QAAA,GA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AAAA,MACA,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,EACH;AACA,EAAA,MAAM,aAAA,GAAgB,IAAA,CAAK,KAAA,IAAS,EAAC;AACrC,EAAA,MAAM,IAAA,GAAO;AAAA,IACX,IAAA,EAAM,OAAA;AAAA,IACN,SAAS,WAAA,CAAY,EAAA;AAAA,IACrB,UAAA,EAAY,YAAY,MAAA,CAAO,EAAA;AAAA,IAC/B,OAAO,WAAA,CAAY,KAAA;AAAA,IACnB,WAAW,WAAA,CAAY;AAAA,GACzB;AACA,EAAA,MAAM,mBAAmB,UAAA,CAAW;AAAA,IAClC,QAAQ,IAAA,CAAK,MAAA;AAAA,IACb,SAAS,IAAA,CAAK,OAAA;AAAA,IACd,SAAS,EAAE,KAAA,EAAO,CAAC,GAAG,aAAA,EAAe,IAAI,CAAA;AAAE,GAC5C,CAAA;AACH;AAEO,IAAM,sBAAsBM,gCAAA,CAAe;AAAA,EAChD,EAAA,EAAI,wBAAA;AAAA,EACJ,WAAA,EAAaJ,mBAAE,MAAA,CAAO;AAAA,IACpB,SAASA,kBAAA,CAAE,KAAA;AAAA,MACTA,mBAAE,MAAA,CAAO;AAAA,QACP,OAAA,EAASA,mBAAE,MAAA,EAAO;AAAA,QAClB,MAAA,EAAQA,kBAAA,CAAE,MAAA,EAAO,CAAE,QAAA;AAAS,OAC7B;AAAA,KACH;AAAA,IACA,QAAA,EAAUA,mBAAE,MAAA;AAAO,GACpB,CAAA;AAAA,EACD,YAAA,EAAcA,mBAAE,GAAA,EAAI;AAAA,EACpB,KAAA,EAAO,CAAC,YAAY,CAAA;AAAA,EACpB,OAAA,EAAS;AAAA,IACP,aAAA,EAAe;AAAA,MACb,QAAA,EAAA,EAAA;AAAA,KACF;AAAA,IACA,cAAA,EAAgB;AAAA;AAEpB,CAAC;AAED,mBAAA,CAAoB,IAAA,CAAK,YAAY,CAAA,CAAE,MAAA,EAAO","file":"index.cjs","sourcesContent":["import { MastraError } from '../../error';\nimport type { Mastra } from '../../mastra';\n\nexport async function scoreTraces({\n scorerId,\n targets,\n mastra,\n}: {\n scorerId: string;\n targets: { traceId: string; spanId?: string }[];\n mastra: Mastra;\n}) {\n const workflow = mastra.__getInternalWorkflow('__batch-scoring-traces');\n try {\n const run = await workflow.createRun();\n\n await run.start({ inputData: { targets, scorerId } });\n } catch (error) {\n const mastraError = new MastraError(\n {\n category: 'SYSTEM',\n domain: 'SCORER',\n id: 'MASTRA_SCORER_FAILED_TO_RUN_TRACE_SCORING',\n details: {\n scorerId,\n targets: JSON.stringify(targets),\n },\n },\n error,\n );\n mastra.getLogger()?.trackException(mastraError);\n mastra.getLogger()?.error(mastraError.toString());\n }\n}\n","import type { MastraDBMessage } from '../../agent';\nimport { SpanType } from '../../observability';\nimport type { SpanRecord, TraceRecord } from '../../storage';\nimport type { ScorerRunInputForAgent, ScorerRunOutputForAgent } from '../types';\n\n// Types for span input/output structures\ninterface SpanMessage {\n role: string;\n content: string | Array<{ type: string; text: string }>;\n}\n\ninterface SpanInputWithMessages {\n messages: SpanMessage[];\n}\n\ninterface SpanOutputWithText {\n text?: string;\n}\n\n// Type guards for span data\nfunction isSpanMessage(value: unknown): value is SpanMessage {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'role' in value &&\n typeof (value as SpanMessage).role === 'string' &&\n 'content' in value\n );\n}\n\nfunction hasMessagesArray(value: unknown): value is SpanInputWithMessages {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'messages' in value &&\n Array.isArray((value as SpanInputWithMessages).messages)\n );\n}\n\nfunction hasTextProperty(value: unknown): value is SpanOutputWithText {\n return typeof value === 'object' && value !== null && 'text' in value;\n}\n\n// // Span tree structure for efficient lookups\ninterface SpanTree {\n spanMap: Map<string, SpanRecord>;\n childrenMap: Map<string, SpanRecord[]>;\n rootSpans: SpanRecord[];\n}\n\n/**\n * Build a hierarchical span tree with efficient lookup maps\n */\nexport function buildSpanTree(spans: SpanRecord[]): SpanTree {\n const spanMap = new Map<string, SpanRecord>();\n const childrenMap = new Map<string, SpanRecord[]>();\n const rootSpans: SpanRecord[] = [];\n\n // First pass: build span map\n for (const span of spans) {\n spanMap.set(span.spanId, span);\n }\n\n // Second pass: build parent-child relationships\n for (const span of spans) {\n if (span.parentSpanId == null) {\n // Root span (parentSpanId is null or undefined)\n rootSpans.push(span);\n } else {\n const siblings = childrenMap.get(span.parentSpanId) || [];\n siblings.push(span);\n childrenMap.set(span.parentSpanId, siblings);\n }\n }\n\n // Sort children by startedAt timestamp for temporal ordering\n for (const children of childrenMap.values()) {\n children.sort((a, b) => new Date(a.startedAt).getTime() - new Date(b.startedAt).getTime());\n }\n\n // Sort root spans by startedAt\n rootSpans.sort((a, b) => new Date(a.startedAt).getTime() - new Date(b.startedAt).getTime());\n\n return { spanMap, childrenMap, rootSpans };\n}\n\n/**\n * Extract children spans of a specific type\n */\nfunction getChildrenOfType<T extends SpanRecord>(spanTree: SpanTree, parentSpanId: string, spanType: SpanType): T[] {\n const children = spanTree.childrenMap.get(parentSpanId) || [];\n return children.filter(span => span.spanType === spanType) as T[];\n}\n\n/**\n * Normalize message content to string format\n * For arrays with multiple text parts, returns only the last text part (AI SDK convention)\n */\nfunction normalizeMessageContent(content: string | Array<{ type: string; text: string }>): string {\n if (typeof content === 'string') {\n return content;\n }\n\n // Extract text parts and return only the last one (AI SDK convention)\n const textParts = content.filter(part => part.type === 'text');\n return textParts.length > 0 ? textParts[textParts.length - 1]?.text || '' : '';\n}\n\n/**\n * Create MastraDBMessage directly from span message data\n */\nfunction createMastraDBMessage(\n message: { role: string; content: string | Array<{ type: string; text: string }> },\n createdAt: Date,\n id: string = '',\n): MastraDBMessage {\n const contentText = normalizeMessageContent(message.content);\n const role = message.role as 'user' | 'assistant' | 'system';\n\n return {\n id,\n role,\n content: {\n format: 2,\n parts: [{ type: 'text', text: contentText }],\n content: contentText,\n },\n createdAt: new Date(createdAt),\n };\n}\n\n/**\n * Extract input messages from agent run span\n */\nfunction extractInputMessages(agentSpan: SpanRecord): MastraDBMessage[] {\n const input = agentSpan.input;\n\n // Handle different input formats\n if (typeof input === 'string') {\n return [\n createMastraDBMessage(\n {\n role: 'user',\n content: input,\n },\n agentSpan.startedAt,\n ),\n ];\n }\n\n if (Array.isArray(input)) {\n const messages = input.filter(isSpanMessage) as SpanMessage[];\n return messages.map(msg => createMastraDBMessage(msg, agentSpan.startedAt));\n }\n\n if (hasMessagesArray(input)) {\n const messages = input.messages.filter(isSpanMessage) as SpanMessage[];\n return messages.map(msg => createMastraDBMessage(msg, agentSpan.startedAt));\n }\n return [];\n}\n\n/**\n * Extract system messages from LLM span\n */\nfunction extractSystemMessages(llmSpan: SpanRecord): Array<{ role: 'system'; content: string }> {\n const input = llmSpan.input;\n if (!hasMessagesArray(input)) {\n return [];\n }\n return input.messages\n .filter((msg): msg is SpanMessage & { role: 'system' } => isSpanMessage(msg) && msg.role === 'system')\n .map(msg => ({\n role: 'system' as const,\n content: normalizeMessageContent(msg.content),\n }));\n}\n\n/**\n * Extract conversation history (remembered messages) from LLM span\n * Excludes system messages and the current input message\n */\nfunction extractRememberedMessages(llmSpan: SpanRecord, currentInputContent: string): MastraDBMessage[] {\n const input = llmSpan.input;\n if (!hasMessagesArray(input)) {\n return [];\n }\n const filtered = input.messages.filter(isSpanMessage) as unknown as SpanMessage[];\n const messages = filtered\n .filter(msg => msg.role !== 'system')\n .filter(msg => normalizeMessageContent(msg.content) !== currentInputContent);\n\n return messages.map(msg => createMastraDBMessage(msg, llmSpan.startedAt));\n}\n\n/**\n * Reconstruct tool invocations from tool call spans\n */\nfunction reconstructToolInvocations(spanTree: SpanTree, parentSpanId: string) {\n const toolSpans = getChildrenOfType<SpanRecord>(spanTree, parentSpanId, SpanType.TOOL_CALL);\n\n return toolSpans.map(toolSpan => ({\n toolCallId: toolSpan.spanId,\n toolName: toolSpan.entityName ?? toolSpan.entityId ?? 'unknown',\n toolId: toolSpan.entityId,\n args: toolSpan.input || {},\n result: toolSpan.output || {},\n state: 'result' as const,\n }));\n}\n\n/**\n * Validate trace structure and throw descriptive errors\n */\nexport function validateTrace(trace: TraceRecord): void {\n if (!trace) {\n throw new Error('Trace is null or undefined');\n }\n\n if (!trace.spans || !Array.isArray(trace.spans)) {\n throw new Error('Trace must have a spans array');\n }\n\n if (trace.spans.length === 0) {\n throw new Error('Trace has no spans');\n }\n\n // Check for circular references in parent-child relationships\n const spanIds = new Set(trace.spans.map(span => span.spanId));\n for (const span of trace.spans) {\n if (span.parentSpanId && !spanIds.has(span.parentSpanId)) {\n throw new Error(`Span ${span.spanId} references non-existent parent ${span.parentSpanId}`);\n }\n }\n}\n\n/**\n * Find the most recent model span that contains conversation history\n */\nfunction findPrimaryLLMSpan(spanTree: SpanTree, rootAgentSpan: SpanRecord): SpanRecord {\n const directLLMSpans = getChildrenOfType<SpanRecord>(spanTree, rootAgentSpan.spanId, SpanType.MODEL_GENERATION);\n if (directLLMSpans.length > 0) {\n // There should only be one model generation span per agent run which is a direct child of the root agent span\n return directLLMSpans[0]!;\n }\n\n throw new Error('No model generation span found in trace');\n}\n\n/**\n * Extract common trace validation and span tree building logic\n */\nfunction prepareTraceForTransformation(trace: TraceRecord) {\n validateTrace(trace);\n const spanTree = buildSpanTree(trace.spans);\n\n // Find the root agent run span\n const rootAgentSpan = spanTree.rootSpans.find(span => span.spanType === 'agent_run') as SpanRecord | undefined;\n\n if (!rootAgentSpan) {\n throw new Error('No root agent_run span found in trace');\n }\n\n return { spanTree, rootAgentSpan };\n}\n\nexport function transformTraceToScorerInputAndOutput(trace: TraceRecord): {\n input: ScorerRunInputForAgent;\n output: ScorerRunOutputForAgent;\n} {\n const { spanTree, rootAgentSpan } = prepareTraceForTransformation(trace);\n\n if (!rootAgentSpan.output) {\n throw new Error('Root agent span has no output');\n }\n\n // Build input\n const primaryLLMSpan = findPrimaryLLMSpan(spanTree, rootAgentSpan);\n const inputMessages = extractInputMessages(rootAgentSpan);\n const systemMessages = extractSystemMessages(primaryLLMSpan);\n\n // Extract remembered messages from LLM span (excluding current input)\n const currentInputContent = inputMessages[0]?.content.content || '';\n const rememberedMessages = extractRememberedMessages(primaryLLMSpan, currentInputContent);\n\n const input = {\n inputMessages,\n rememberedMessages,\n systemMessages,\n taggedSystemMessages: {}, // Todo: Support tagged system messages\n };\n\n // Build output\n const toolInvocations = reconstructToolInvocations(spanTree, rootAgentSpan.spanId);\n const responseText = hasTextProperty(rootAgentSpan.output) ? (rootAgentSpan.output.text ?? '') : '';\n\n // Build parts array: tool invocations first, then text\n const parts: Array<{ type: 'tool-invocation'; toolInvocation: any } | { type: 'text'; text: string }> = [];\n\n // Add tool invocation parts\n for (const toolInvocation of toolInvocations) {\n parts.push({\n type: 'tool-invocation',\n toolInvocation,\n });\n }\n\n // Add text part if present\n if (responseText.trim()) {\n parts.push({\n type: 'text',\n text: responseText,\n });\n }\n\n const responseMessage: MastraDBMessage = {\n id: '',\n role: 'assistant',\n content: {\n format: 2,\n parts: parts as any, // Type assertion needed due to providerMetadata optional field\n content: responseText,\n toolInvocations, // Always include, even if empty array\n },\n createdAt: new Date(rootAgentSpan.endedAt || rootAgentSpan.startedAt),\n };\n\n const output: MastraDBMessage[] = [responseMessage];\n\n return {\n input,\n output,\n };\n}\n","import pMap from 'p-map';\nimport z from 'zod';\nimport { ErrorCategory, ErrorDomain, MastraError } from '../../error';\nimport { InternalSpans } from '../../observability';\nimport type { TracingContext } from '../../observability';\nimport type { SpanRecord, TraceRecord, MastraStorage } from '../../storage';\nimport { createStep, createWorkflow } from '../../workflows/evented';\nimport type { MastraScorer, ScorerRun } from '../base';\nimport type { ScoreRowData } from '../types';\nimport { saveScorePayloadSchema } from '../types';\nimport { transformTraceToScorerInputAndOutput } from './utils';\n\nconst getTraceStep = createStep({\n id: '__process-trace-scoring',\n inputSchema: z.object({\n targets: z.array(\n z.object({\n traceId: z.string(),\n spanId: z.string().optional(),\n }),\n ),\n scorerId: z.string(),\n }),\n outputSchema: z.any(),\n execute: async ({ inputData, tracingContext, mastra }) => {\n const logger = mastra.getLogger();\n if (!logger) {\n console.warn(\n '[scoreTracesWorkflow] Logger not initialized: no debug or error logs will be recorded for scoring traces.',\n );\n }\n\n const storage = mastra.getStorage();\n if (!storage) {\n const mastraError = new MastraError({\n id: 'MASTRA_STORAGE_NOT_FOUND_FOR_TRACE_SCORING',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n text: 'Storage not found for trace scoring',\n details: {\n scorerId: inputData.scorerId,\n },\n });\n logger?.error(mastraError.toString());\n logger?.trackException(mastraError);\n return;\n }\n\n let scorer: MastraScorer | undefined;\n try {\n scorer = mastra.getScorerById(inputData.scorerId);\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MASTRA_SCORER_NOT_FOUND_FOR_TRACE_SCORING',\n domain: ErrorDomain.SCORER,\n category: ErrorCategory.SYSTEM,\n text: `Scorer not found for trace scoring`,\n details: {\n scorerId: inputData.scorerId,\n },\n },\n error,\n );\n logger?.error(mastraError.toString());\n logger?.trackException(mastraError);\n return;\n }\n\n await pMap(\n inputData.targets,\n async target => {\n try {\n await runScorerOnTarget({ storage, scorer, target, tracingContext });\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MASTRA_SCORER_FAILED_TO_RUN_SCORER_ON_TRACE',\n domain: ErrorDomain.SCORER,\n category: ErrorCategory.SYSTEM,\n details: {\n scorerId: scorer.id,\n spanId: target.spanId || '',\n traceId: target.traceId,\n },\n },\n error,\n );\n logger?.error(mastraError.toString());\n logger?.trackException(mastraError);\n }\n },\n { concurrency: 3 },\n );\n },\n});\n\nexport async function runScorerOnTarget({\n storage,\n scorer,\n target,\n tracingContext,\n}: {\n storage: MastraStorage;\n scorer: MastraScorer;\n target: { traceId: string; spanId?: string };\n tracingContext: TracingContext;\n}) {\n // TODO: add storage api to get a single span\n const observabilityStore = await storage.getStore('observability');\n if (!observabilityStore) {\n throw new MastraError({\n id: 'MASTRA_OBSERVABILITY_STORAGE_NOT_AVAILABLE',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n text: 'Observability storage domain is not available',\n });\n }\n const trace = await observabilityStore.getTrace({ traceId: target.traceId });\n if (!trace) {\n throw new Error(`Trace not found for scoring, traceId: ${target.traceId}`);\n }\n\n let span: SpanRecord | undefined;\n if (target.spanId) {\n span = trace.spans.find(span => span.spanId === target.spanId);\n } else {\n span = trace.spans.find(span => span.parentSpanId === null);\n }\n\n if (!span) {\n throw new Error(\n `Span not found for scoring, traceId: ${target.traceId}, spanId: ${target.spanId ?? 'Not provided'}`,\n );\n }\n\n const scorerRun = buildScorerRun({\n scorerType: scorer.type === 'agent' ? 'agent' : undefined,\n tracingContext,\n trace,\n targetSpan: span,\n });\n\n const result = await scorer.run(scorerRun);\n const scorerResult = {\n ...result,\n scorer: {\n id: scorer.id,\n name: scorer.name || scorer.id,\n description: scorer.description,\n hasJudge: !!scorer.judge,\n },\n traceId: target.traceId,\n spanId: target.spanId,\n entityId: span.entityId || span.entityName || 'unknown',\n entityType: span.spanType,\n entity: { traceId: span.traceId, spanId: span.spanId },\n source: 'TEST',\n scorerId: scorer.id,\n };\n\n const savedScoreRecord = await validateAndSaveScore({ storage, scorerResult });\n await attachScoreToSpan({ storage, span, scoreRecord: savedScoreRecord });\n}\n\nasync function validateAndSaveScore({ storage, scorerResult }: { storage: MastraStorage; scorerResult: ScorerRun }) {\n const scoresStore = await storage.getStore('scores');\n if (!scoresStore) {\n throw new MastraError({\n id: 'MASTRA_SCORES_STORAGE_NOT_AVAILABLE',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n text: 'Scores storage domain is not available',\n });\n }\n const payloadToSave = saveScorePayloadSchema.parse(scorerResult);\n const result = await scoresStore.saveScore(payloadToSave);\n return result.score;\n}\n\nfunction buildScorerRun({\n scorerType,\n tracingContext,\n trace,\n targetSpan,\n}: {\n scorerType?: string;\n tracingContext: TracingContext;\n trace: TraceRecord;\n targetSpan: SpanRecord;\n}) {\n let runPayload: ScorerRun;\n if (scorerType === 'agent') {\n const { input, output } = transformTraceToScorerInputAndOutput(trace);\n runPayload = {\n input,\n output,\n };\n } else {\n runPayload = { input: targetSpan.input, output: targetSpan.output };\n }\n\n runPayload.tracingContext = tracingContext;\n return runPayload;\n}\n\nasync function attachScoreToSpan({\n storage,\n span,\n scoreRecord,\n}: {\n storage: MastraStorage;\n span: SpanRecord;\n scoreRecord: ScoreRowData;\n}) {\n const observabilityStore = await storage.getStore('observability');\n if (!observabilityStore) {\n throw new MastraError({\n id: 'MASTRA_OBSERVABILITY_STORAGE_NOT_AVAILABLE',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n text: 'Observability storage domain is not available',\n });\n }\n const existingLinks = span.links || [];\n const link = {\n type: 'score',\n scoreId: scoreRecord.id,\n scorerName: scoreRecord.scorer.id,\n score: scoreRecord.score,\n createdAt: scoreRecord.createdAt,\n };\n await observabilityStore.updateSpan({\n spanId: span.spanId,\n traceId: span.traceId,\n updates: { links: [...existingLinks, link] },\n });\n}\n\nexport const scoreTracesWorkflow = createWorkflow({\n id: '__batch-scoring-traces',\n inputSchema: z.object({\n targets: z.array(\n z.object({\n traceId: z.string(),\n spanId: z.string().optional(),\n }),\n ),\n scorerId: z.string(),\n }),\n outputSchema: z.any(),\n steps: [getTraceStep],\n options: {\n tracingPolicy: {\n internal: InternalSpans.ALL,\n },\n validateInputs: false,\n },\n});\n\nscoreTracesWorkflow.then(getTraceStep).commit();\n"]}
@@ -1,5 +1,5 @@
1
- import { createStep, createWorkflow } from '../../chunk-RHKNKJNM.js';
2
- import { saveScorePayloadSchema } from '../../chunk-5K45E5VE.js';
1
+ import { createStep, createWorkflow } from '../../chunk-QWTB53GS.js';
2
+ import { saveScorePayloadSchema } from '../../chunk-GPJGPARM.js';
3
3
  import { MastraError } from '../../chunk-FJEVLHJT.js';
4
4
  import pMap from 'p-map';
5
5
  import z from 'zod';
@@ -351,7 +351,8 @@ async function runScorerOnTarget({
351
351
  scorer: {
352
352
  id: scorer.id,
353
353
  name: scorer.name || scorer.id,
354
- description: scorer.description
354
+ description: scorer.description,
355
+ hasJudge: !!scorer.judge
355
356
  },
356
357
  traceId: target.traceId,
357
358
  spanId: target.spanId,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/evals/scoreTraces/scoreTraces.ts","../../../src/evals/scoreTraces/utils.ts","../../../src/evals/scoreTraces/scoreTracesWorkflow.ts"],"names":["span"],"mappings":";;;;;;;AAGA,eAAsB,WAAA,CAAY;AAAA,EAChC,QAAA;AAAA,EACA,OAAA;AAAA,EACA;AACF,CAAA,EAIG;AACD,EAAA,MAAM,QAAA,GAAW,MAAA,CAAO,qBAAA,CAAsB,wBAAwB,CAAA;AACtE,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAM,MAAM,QAAA,CAAS,SAAA,EAAU;AAErC,IAAA,MAAM,GAAA,CAAI,MAAM,EAAE,SAAA,EAAW,EAAE,OAAA,EAAS,QAAA,IAAY,CAAA;AAAA,EACtD,SAAS,KAAA,EAAO;AACd,IAAA,MAAM,cAAc,IAAI,WAAA;AAAA,MACtB;AAAA,QACE,QAAA,EAAU,QAAA;AAAA,QACV,MAAA,EAAQ,QAAA;AAAA,QACR,EAAA,EAAI,2CAAA;AAAA,QACJ,OAAA,EAAS;AAAA,UACP,QAAA;AAAA,UACA,OAAA,EAAS,IAAA,CAAK,SAAA,CAAU,OAAO;AAAA;AACjC,OACF;AAAA,MACA;AAAA,KACF;AACA,IAAA,MAAA,CAAO,SAAA,EAAU,EAAG,cAAA,CAAe,WAAW,CAAA;AAC9C,IAAA,MAAA,CAAO,SAAA,EAAU,EAAG,KAAA,CAAM,WAAA,CAAY,UAAU,CAAA;AAAA,EAClD;AACF;;;ACbA,SAAS,cAAc,KAAA,EAAsC;AAC3D,EAAA,OACE,OAAO,KAAA,KAAU,QAAA,IACjB,KAAA,KAAU,IAAA,IACV,MAAA,IAAU,KAAA,IACV,OAAQ,KAAA,CAAsB,IAAA,KAAS,QAAA,IACvC,SAAA,IAAa,KAAA;AAEjB;AA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,CAAA;AAAA,EACpB,OAAA,EAAS;AAAA,IACP,aAAA,EAAe;AAAA,MACb,QAAA,EAAA,EAAA;AAAA,KACF;AAAA,IACA,cAAA,EAAgB;AAAA;AAEpB,CAAC;AAED,mBAAA,CAAoB,IAAA,CAAK,YAAY,CAAA,CAAE,MAAA,EAAO","file":"index.js","sourcesContent":["import { MastraError } from '../../error';\nimport type { Mastra } from '../../mastra';\n\nexport async function scoreTraces({\n scorerId,\n targets,\n mastra,\n}: {\n scorerId: string;\n targets: { traceId: string; spanId?: string }[];\n mastra: Mastra;\n}) {\n const workflow = mastra.__getInternalWorkflow('__batch-scoring-traces');\n try {\n const run = await workflow.createRun();\n\n await run.start({ inputData: { targets, scorerId } });\n } catch (error) {\n const mastraError = new MastraError(\n {\n category: 'SYSTEM',\n domain: 'SCORER',\n id: 'MASTRA_SCORER_FAILED_TO_RUN_TRACE_SCORING',\n details: {\n scorerId,\n targets: JSON.stringify(targets),\n },\n },\n error,\n );\n mastra.getLogger()?.trackException(mastraError);\n mastra.getLogger()?.error(mastraError.toString());\n }\n}\n","import type { MastraDBMessage } from '../../agent';\nimport { SpanType } from '../../observability';\nimport type { SpanRecord, TraceRecord } from '../../storage';\nimport type { ScorerRunInputForAgent, ScorerRunOutputForAgent } from '../types';\n\n// Types for span input/output structures\ninterface SpanMessage {\n role: string;\n content: string | Array<{ type: string; text: string }>;\n}\n\ninterface SpanInputWithMessages {\n messages: SpanMessage[];\n}\n\ninterface SpanOutputWithText {\n text?: string;\n}\n\n// Type guards for span data\nfunction isSpanMessage(value: unknown): value is SpanMessage {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'role' in value &&\n typeof (value as SpanMessage).role === 'string' &&\n 'content' in value\n );\n}\n\nfunction hasMessagesArray(value: unknown): value is SpanInputWithMessages {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'messages' in value &&\n Array.isArray((value as SpanInputWithMessages).messages)\n );\n}\n\nfunction hasTextProperty(value: unknown): value is SpanOutputWithText {\n return typeof value === 'object' && value !== null && 'text' in value;\n}\n\n// // Span tree structure for efficient lookups\ninterface SpanTree {\n spanMap: Map<string, SpanRecord>;\n childrenMap: Map<string, SpanRecord[]>;\n rootSpans: SpanRecord[];\n}\n\n/**\n * Build a hierarchical span tree with efficient lookup maps\n */\nexport function buildSpanTree(spans: SpanRecord[]): SpanTree {\n const spanMap = new Map<string, SpanRecord>();\n const childrenMap = new Map<string, SpanRecord[]>();\n const rootSpans: SpanRecord[] = [];\n\n // First pass: build span map\n for (const span of spans) {\n spanMap.set(span.spanId, span);\n }\n\n // Second pass: build parent-child relationships\n for (const span of spans) {\n if (span.parentSpanId == null) {\n // Root span (parentSpanId is null or undefined)\n rootSpans.push(span);\n } else {\n const siblings = childrenMap.get(span.parentSpanId) || [];\n siblings.push(span);\n childrenMap.set(span.parentSpanId, siblings);\n }\n }\n\n // Sort children by startedAt timestamp for temporal ordering\n for (const children of childrenMap.values()) {\n children.sort((a, b) => new Date(a.startedAt).getTime() - new Date(b.startedAt).getTime());\n }\n\n // Sort root spans by startedAt\n rootSpans.sort((a, b) => new Date(a.startedAt).getTime() - new Date(b.startedAt).getTime());\n\n return { spanMap, childrenMap, rootSpans };\n}\n\n/**\n * Extract children spans of a specific type\n */\nfunction getChildrenOfType<T extends SpanRecord>(spanTree: SpanTree, parentSpanId: string, spanType: SpanType): T[] {\n const children = spanTree.childrenMap.get(parentSpanId) || [];\n return children.filter(span => span.spanType === spanType) as T[];\n}\n\n/**\n * Normalize message content to string format\n * For arrays with multiple text parts, returns only the last text part (AI SDK convention)\n */\nfunction normalizeMessageContent(content: string | Array<{ type: string; text: string }>): string {\n if (typeof content === 'string') {\n return content;\n }\n\n // Extract text parts and return only the last one (AI SDK convention)\n const textParts = content.filter(part => part.type === 'text');\n return textParts.length > 0 ? textParts[textParts.length - 1]?.text || '' : '';\n}\n\n/**\n * Create MastraDBMessage directly from span message data\n */\nfunction createMastraDBMessage(\n message: { role: string; content: string | Array<{ type: string; text: string }> },\n createdAt: Date,\n id: string = '',\n): MastraDBMessage {\n const contentText = normalizeMessageContent(message.content);\n const role = message.role as 'user' | 'assistant' | 'system';\n\n return {\n id,\n role,\n content: {\n format: 2,\n parts: [{ type: 'text', text: contentText }],\n content: contentText,\n },\n createdAt: new Date(createdAt),\n };\n}\n\n/**\n * Extract input messages from agent run span\n */\nfunction extractInputMessages(agentSpan: SpanRecord): MastraDBMessage[] {\n const input = agentSpan.input;\n\n // Handle different input formats\n if (typeof input === 'string') {\n return [\n createMastraDBMessage(\n {\n role: 'user',\n content: input,\n },\n agentSpan.startedAt,\n ),\n ];\n }\n\n if (Array.isArray(input)) {\n const messages = input.filter(isSpanMessage) as SpanMessage[];\n return messages.map(msg => createMastraDBMessage(msg, agentSpan.startedAt));\n }\n\n if (hasMessagesArray(input)) {\n const messages = input.messages.filter(isSpanMessage) as SpanMessage[];\n return messages.map(msg => createMastraDBMessage(msg, agentSpan.startedAt));\n }\n return [];\n}\n\n/**\n * Extract system messages from LLM span\n */\nfunction extractSystemMessages(llmSpan: SpanRecord): Array<{ role: 'system'; content: string }> {\n const input = llmSpan.input;\n if (!hasMessagesArray(input)) {\n return [];\n }\n return input.messages\n .filter((msg): msg is SpanMessage & { role: 'system' } => isSpanMessage(msg) && msg.role === 'system')\n .map(msg => ({\n role: 'system' as const,\n content: normalizeMessageContent(msg.content),\n }));\n}\n\n/**\n * Extract conversation history (remembered messages) from LLM span\n * Excludes system messages and the current input message\n */\nfunction extractRememberedMessages(llmSpan: SpanRecord, currentInputContent: string): MastraDBMessage[] {\n const input = llmSpan.input;\n if (!hasMessagesArray(input)) {\n return [];\n }\n const filtered = input.messages.filter(isSpanMessage) as unknown as SpanMessage[];\n const messages = filtered\n .filter(msg => msg.role !== 'system')\n .filter(msg => normalizeMessageContent(msg.content) !== currentInputContent);\n\n return messages.map(msg => createMastraDBMessage(msg, llmSpan.startedAt));\n}\n\n/**\n * Reconstruct tool invocations from tool call spans\n */\nfunction reconstructToolInvocations(spanTree: SpanTree, parentSpanId: string) {\n const toolSpans = getChildrenOfType<SpanRecord>(spanTree, parentSpanId, SpanType.TOOL_CALL);\n\n return toolSpans.map(toolSpan => ({\n toolCallId: toolSpan.spanId,\n toolName: toolSpan.entityName ?? toolSpan.entityId ?? 'unknown',\n toolId: toolSpan.entityId,\n args: toolSpan.input || {},\n result: toolSpan.output || {},\n state: 'result' as const,\n }));\n}\n\n/**\n * Validate trace structure and throw descriptive errors\n */\nexport function validateTrace(trace: TraceRecord): void {\n if (!trace) {\n throw new Error('Trace is null or undefined');\n }\n\n if (!trace.spans || !Array.isArray(trace.spans)) {\n throw new Error('Trace must have a spans array');\n }\n\n if (trace.spans.length === 0) {\n throw new Error('Trace has no spans');\n }\n\n // Check for circular references in parent-child relationships\n const spanIds = new Set(trace.spans.map(span => span.spanId));\n for (const span of trace.spans) {\n if (span.parentSpanId && !spanIds.has(span.parentSpanId)) {\n throw new Error(`Span ${span.spanId} references non-existent parent ${span.parentSpanId}`);\n }\n }\n}\n\n/**\n * Find the most recent model span that contains conversation history\n */\nfunction findPrimaryLLMSpan(spanTree: SpanTree, rootAgentSpan: SpanRecord): SpanRecord {\n const directLLMSpans = getChildrenOfType<SpanRecord>(spanTree, rootAgentSpan.spanId, SpanType.MODEL_GENERATION);\n if (directLLMSpans.length > 0) {\n // There should only be one model generation span per agent run which is a direct child of the root agent span\n return directLLMSpans[0]!;\n }\n\n throw new Error('No model generation span found in trace');\n}\n\n/**\n * Extract common trace validation and span tree building logic\n */\nfunction prepareTraceForTransformation(trace: TraceRecord) {\n validateTrace(trace);\n const spanTree = buildSpanTree(trace.spans);\n\n // Find the root agent run span\n const rootAgentSpan = spanTree.rootSpans.find(span => span.spanType === 'agent_run') as SpanRecord | undefined;\n\n if (!rootAgentSpan) {\n throw new Error('No root agent_run span found in trace');\n }\n\n return { spanTree, rootAgentSpan };\n}\n\nexport function transformTraceToScorerInputAndOutput(trace: TraceRecord): {\n input: ScorerRunInputForAgent;\n output: ScorerRunOutputForAgent;\n} {\n const { spanTree, rootAgentSpan } = prepareTraceForTransformation(trace);\n\n if (!rootAgentSpan.output) {\n throw new Error('Root agent span has no output');\n }\n\n // Build input\n const primaryLLMSpan = findPrimaryLLMSpan(spanTree, rootAgentSpan);\n const inputMessages = extractInputMessages(rootAgentSpan);\n const systemMessages = extractSystemMessages(primaryLLMSpan);\n\n // Extract remembered messages from LLM span (excluding current input)\n const currentInputContent = inputMessages[0]?.content.content || '';\n const rememberedMessages = extractRememberedMessages(primaryLLMSpan, currentInputContent);\n\n const input = {\n inputMessages,\n rememberedMessages,\n systemMessages,\n taggedSystemMessages: {}, // Todo: Support tagged system messages\n };\n\n // Build output\n const toolInvocations = reconstructToolInvocations(spanTree, rootAgentSpan.spanId);\n const responseText = hasTextProperty(rootAgentSpan.output) ? (rootAgentSpan.output.text ?? '') : '';\n\n // Build parts array: tool invocations first, then text\n const parts: Array<{ type: 'tool-invocation'; toolInvocation: any } | { type: 'text'; text: string }> = [];\n\n // Add tool invocation parts\n for (const toolInvocation of toolInvocations) {\n parts.push({\n type: 'tool-invocation',\n toolInvocation,\n });\n }\n\n // Add text part if present\n if (responseText.trim()) {\n parts.push({\n type: 'text',\n text: responseText,\n });\n }\n\n const responseMessage: MastraDBMessage = {\n id: '',\n role: 'assistant',\n content: {\n format: 2,\n parts: parts as any, // Type assertion needed due to providerMetadata optional field\n content: responseText,\n toolInvocations, // Always include, even if empty array\n },\n createdAt: new Date(rootAgentSpan.endedAt || rootAgentSpan.startedAt),\n };\n\n const output: MastraDBMessage[] = [responseMessage];\n\n return {\n input,\n output,\n };\n}\n","import pMap from 'p-map';\nimport z from 'zod';\nimport { ErrorCategory, ErrorDomain, MastraError } from '../../error';\nimport { InternalSpans } from '../../observability';\nimport type { TracingContext } from '../../observability';\nimport type { SpanRecord, TraceRecord, MastraStorage } from '../../storage';\nimport { createStep, createWorkflow } from '../../workflows/evented';\nimport type { MastraScorer, ScorerRun } from '../base';\nimport type { ScoreRowData } from '../types';\nimport { saveScorePayloadSchema } from '../types';\nimport { transformTraceToScorerInputAndOutput } from './utils';\n\nconst getTraceStep = createStep({\n id: '__process-trace-scoring',\n inputSchema: z.object({\n targets: z.array(\n z.object({\n traceId: z.string(),\n spanId: z.string().optional(),\n }),\n ),\n scorerId: z.string(),\n }),\n outputSchema: z.any(),\n execute: async ({ inputData, tracingContext, mastra }) => {\n const logger = mastra.getLogger();\n if (!logger) {\n console.warn(\n '[scoreTracesWorkflow] Logger not initialized: no debug or error logs will be recorded for scoring traces.',\n );\n }\n\n const storage = mastra.getStorage();\n if (!storage) {\n const mastraError = new MastraError({\n id: 'MASTRA_STORAGE_NOT_FOUND_FOR_TRACE_SCORING',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n text: 'Storage not found for trace scoring',\n details: {\n scorerId: inputData.scorerId,\n },\n });\n logger?.error(mastraError.toString());\n logger?.trackException(mastraError);\n return;\n }\n\n let scorer: MastraScorer | undefined;\n try {\n scorer = mastra.getScorerById(inputData.scorerId);\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MASTRA_SCORER_NOT_FOUND_FOR_TRACE_SCORING',\n domain: ErrorDomain.SCORER,\n category: ErrorCategory.SYSTEM,\n text: `Scorer not found for trace scoring`,\n details: {\n scorerId: inputData.scorerId,\n },\n },\n error,\n );\n logger?.error(mastraError.toString());\n logger?.trackException(mastraError);\n return;\n }\n\n await pMap(\n inputData.targets,\n async target => {\n try {\n await runScorerOnTarget({ storage, scorer, target, tracingContext });\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MASTRA_SCORER_FAILED_TO_RUN_SCORER_ON_TRACE',\n domain: ErrorDomain.SCORER,\n category: ErrorCategory.SYSTEM,\n details: {\n scorerId: scorer.id,\n spanId: target.spanId || '',\n traceId: target.traceId,\n },\n },\n error,\n );\n logger?.error(mastraError.toString());\n logger?.trackException(mastraError);\n }\n },\n { concurrency: 3 },\n );\n },\n});\n\nexport async function runScorerOnTarget({\n storage,\n scorer,\n target,\n tracingContext,\n}: {\n storage: MastraStorage;\n scorer: MastraScorer;\n target: { traceId: string; spanId?: string };\n tracingContext: TracingContext;\n}) {\n // TODO: add storage api to get a single span\n const observabilityStore = await storage.getStore('observability');\n if (!observabilityStore) {\n throw new MastraError({\n id: 'MASTRA_OBSERVABILITY_STORAGE_NOT_AVAILABLE',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n text: 'Observability storage domain is not available',\n });\n }\n const trace = await observabilityStore.getTrace({ traceId: target.traceId });\n if (!trace) {\n throw new Error(`Trace not found for scoring, traceId: ${target.traceId}`);\n }\n\n let span: SpanRecord | undefined;\n if (target.spanId) {\n span = trace.spans.find(span => span.spanId === target.spanId);\n } else {\n span = trace.spans.find(span => span.parentSpanId === null);\n }\n\n if (!span) {\n throw new Error(\n `Span not found for scoring, traceId: ${target.traceId}, spanId: ${target.spanId ?? 'Not provided'}`,\n );\n }\n\n const scorerRun = buildScorerRun({\n scorerType: scorer.type === 'agent' ? 'agent' : undefined,\n tracingContext,\n trace,\n targetSpan: span,\n });\n\n const result = await scorer.run(scorerRun);\n const scorerResult = {\n ...result,\n scorer: {\n id: scorer.id,\n name: scorer.name || scorer.id,\n description: scorer.description,\n },\n traceId: target.traceId,\n spanId: target.spanId,\n entityId: span.entityId || span.entityName || 'unknown',\n entityType: span.spanType,\n entity: { traceId: span.traceId, spanId: span.spanId },\n source: 'TEST',\n scorerId: scorer.id,\n };\n\n const savedScoreRecord = await validateAndSaveScore({ storage, scorerResult });\n await attachScoreToSpan({ storage, span, scoreRecord: savedScoreRecord });\n}\n\nasync function validateAndSaveScore({ storage, scorerResult }: { storage: MastraStorage; scorerResult: ScorerRun }) {\n const scoresStore = await storage.getStore('scores');\n if (!scoresStore) {\n throw new MastraError({\n id: 'MASTRA_SCORES_STORAGE_NOT_AVAILABLE',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n text: 'Scores storage domain is not available',\n });\n }\n const payloadToSave = saveScorePayloadSchema.parse(scorerResult);\n const result = await scoresStore.saveScore(payloadToSave);\n return result.score;\n}\n\nfunction buildScorerRun({\n scorerType,\n tracingContext,\n trace,\n targetSpan,\n}: {\n scorerType?: string;\n tracingContext: TracingContext;\n trace: TraceRecord;\n targetSpan: SpanRecord;\n}) {\n let runPayload: ScorerRun;\n if (scorerType === 'agent') {\n const { input, output } = transformTraceToScorerInputAndOutput(trace);\n runPayload = {\n input,\n output,\n };\n } else {\n runPayload = { input: targetSpan.input, output: targetSpan.output };\n }\n\n runPayload.tracingContext = tracingContext;\n return runPayload;\n}\n\nasync function attachScoreToSpan({\n storage,\n span,\n scoreRecord,\n}: {\n storage: MastraStorage;\n span: SpanRecord;\n scoreRecord: ScoreRowData;\n}) {\n const observabilityStore = await storage.getStore('observability');\n if (!observabilityStore) {\n throw new MastraError({\n id: 'MASTRA_OBSERVABILITY_STORAGE_NOT_AVAILABLE',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n text: 'Observability storage domain is not available',\n });\n }\n const existingLinks = span.links || [];\n const link = {\n type: 'score',\n scoreId: scoreRecord.id,\n scorerName: scoreRecord.scorer.id,\n score: scoreRecord.score,\n createdAt: scoreRecord.createdAt,\n };\n await observabilityStore.updateSpan({\n spanId: span.spanId,\n traceId: span.traceId,\n updates: { links: [...existingLinks, link] },\n });\n}\n\nexport const scoreTracesWorkflow = createWorkflow({\n id: '__batch-scoring-traces',\n inputSchema: z.object({\n targets: z.array(\n z.object({\n traceId: z.string(),\n spanId: z.string().optional(),\n }),\n ),\n scorerId: z.string(),\n }),\n outputSchema: z.any(),\n steps: [getTraceStep],\n options: {\n tracingPolicy: {\n internal: InternalSpans.ALL,\n },\n validateInputs: false,\n },\n});\n\nscoreTracesWorkflow.then(getTraceStep).commit();\n"]}
1
+ {"version":3,"sources":["../../../src/evals/scoreTraces/scoreTraces.ts","../../../src/evals/scoreTraces/utils.ts","../../../src/evals/scoreTraces/scoreTracesWorkflow.ts"],"names":["span"],"mappings":";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MAAA,EAAO","file":"index.js","sourcesContent":["import { MastraError } from '../../error';\nimport type { Mastra } from '../../mastra';\n\nexport async function scoreTraces({\n scorerId,\n targets,\n mastra,\n}: {\n scorerId: string;\n targets: { traceId: string; spanId?: string }[];\n mastra: Mastra;\n}) {\n const workflow = mastra.__getInternalWorkflow('__batch-scoring-traces');\n try {\n const run = await workflow.createRun();\n\n await run.start({ inputData: { targets, scorerId } });\n } catch (error) {\n const mastraError = new MastraError(\n {\n category: 'SYSTEM',\n domain: 'SCORER',\n id: 'MASTRA_SCORER_FAILED_TO_RUN_TRACE_SCORING',\n details: {\n scorerId,\n targets: JSON.stringify(targets),\n },\n },\n error,\n );\n mastra.getLogger()?.trackException(mastraError);\n mastra.getLogger()?.error(mastraError.toString());\n }\n}\n","import type { MastraDBMessage } from '../../agent';\nimport { SpanType } from '../../observability';\nimport type { SpanRecord, TraceRecord } from '../../storage';\nimport type { ScorerRunInputForAgent, ScorerRunOutputForAgent } from '../types';\n\n// Types for span input/output structures\ninterface SpanMessage {\n role: string;\n content: string | Array<{ type: string; text: string }>;\n}\n\ninterface SpanInputWithMessages {\n messages: SpanMessage[];\n}\n\ninterface SpanOutputWithText {\n text?: string;\n}\n\n// Type guards for span data\nfunction isSpanMessage(value: unknown): value is SpanMessage {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'role' in value &&\n typeof (value as SpanMessage).role === 'string' &&\n 'content' in value\n );\n}\n\nfunction hasMessagesArray(value: unknown): value is SpanInputWithMessages {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'messages' in value &&\n Array.isArray((value as SpanInputWithMessages).messages)\n );\n}\n\nfunction hasTextProperty(value: unknown): value is SpanOutputWithText {\n return typeof value === 'object' && value !== null && 'text' in value;\n}\n\n// // Span tree structure for efficient lookups\ninterface SpanTree {\n spanMap: Map<string, SpanRecord>;\n childrenMap: Map<string, SpanRecord[]>;\n rootSpans: SpanRecord[];\n}\n\n/**\n * Build a hierarchical span tree with efficient lookup maps\n */\nexport function buildSpanTree(spans: SpanRecord[]): SpanTree {\n const spanMap = new Map<string, SpanRecord>();\n const childrenMap = new Map<string, SpanRecord[]>();\n const rootSpans: SpanRecord[] = [];\n\n // First pass: build span map\n for (const span of spans) {\n spanMap.set(span.spanId, span);\n }\n\n // Second pass: build parent-child relationships\n for (const span of spans) {\n if (span.parentSpanId == null) {\n // Root span (parentSpanId is null or undefined)\n rootSpans.push(span);\n } else {\n const siblings = childrenMap.get(span.parentSpanId) || [];\n siblings.push(span);\n childrenMap.set(span.parentSpanId, siblings);\n }\n }\n\n // Sort children by startedAt timestamp for temporal ordering\n for (const children of childrenMap.values()) {\n children.sort((a, b) => new Date(a.startedAt).getTime() - new Date(b.startedAt).getTime());\n }\n\n // Sort root spans by startedAt\n rootSpans.sort((a, b) => new Date(a.startedAt).getTime() - new Date(b.startedAt).getTime());\n\n return { spanMap, childrenMap, rootSpans };\n}\n\n/**\n * Extract children spans of a specific type\n */\nfunction getChildrenOfType<T extends SpanRecord>(spanTree: SpanTree, parentSpanId: string, spanType: SpanType): T[] {\n const children = spanTree.childrenMap.get(parentSpanId) || [];\n return children.filter(span => span.spanType === spanType) as T[];\n}\n\n/**\n * Normalize message content to string format\n * For arrays with multiple text parts, returns only the last text part (AI SDK convention)\n */\nfunction normalizeMessageContent(content: string | Array<{ type: string; text: string }>): string {\n if (typeof content === 'string') {\n return content;\n }\n\n // Extract text parts and return only the last one (AI SDK convention)\n const textParts = content.filter(part => part.type === 'text');\n return textParts.length > 0 ? textParts[textParts.length - 1]?.text || '' : '';\n}\n\n/**\n * Create MastraDBMessage directly from span message data\n */\nfunction createMastraDBMessage(\n message: { role: string; content: string | Array<{ type: string; text: string }> },\n createdAt: Date,\n id: string = '',\n): MastraDBMessage {\n const contentText = normalizeMessageContent(message.content);\n const role = message.role as 'user' | 'assistant' | 'system';\n\n return {\n id,\n role,\n content: {\n format: 2,\n parts: [{ type: 'text', text: contentText }],\n content: contentText,\n },\n createdAt: new Date(createdAt),\n };\n}\n\n/**\n * Extract input messages from agent run span\n */\nfunction extractInputMessages(agentSpan: SpanRecord): MastraDBMessage[] {\n const input = agentSpan.input;\n\n // Handle different input formats\n if (typeof input === 'string') {\n return [\n createMastraDBMessage(\n {\n role: 'user',\n content: input,\n },\n agentSpan.startedAt,\n ),\n ];\n }\n\n if (Array.isArray(input)) {\n const messages = input.filter(isSpanMessage) as SpanMessage[];\n return messages.map(msg => createMastraDBMessage(msg, agentSpan.startedAt));\n }\n\n if (hasMessagesArray(input)) {\n const messages = input.messages.filter(isSpanMessage) as SpanMessage[];\n return messages.map(msg => createMastraDBMessage(msg, agentSpan.startedAt));\n }\n return [];\n}\n\n/**\n * Extract system messages from LLM span\n */\nfunction extractSystemMessages(llmSpan: SpanRecord): Array<{ role: 'system'; content: string }> {\n const input = llmSpan.input;\n if (!hasMessagesArray(input)) {\n return [];\n }\n return input.messages\n .filter((msg): msg is SpanMessage & { role: 'system' } => isSpanMessage(msg) && msg.role === 'system')\n .map(msg => ({\n role: 'system' as const,\n content: normalizeMessageContent(msg.content),\n }));\n}\n\n/**\n * Extract conversation history (remembered messages) from LLM span\n * Excludes system messages and the current input message\n */\nfunction extractRememberedMessages(llmSpan: SpanRecord, currentInputContent: string): MastraDBMessage[] {\n const input = llmSpan.input;\n if (!hasMessagesArray(input)) {\n return [];\n }\n const filtered = input.messages.filter(isSpanMessage) as unknown as SpanMessage[];\n const messages = filtered\n .filter(msg => msg.role !== 'system')\n .filter(msg => normalizeMessageContent(msg.content) !== currentInputContent);\n\n return messages.map(msg => createMastraDBMessage(msg, llmSpan.startedAt));\n}\n\n/**\n * Reconstruct tool invocations from tool call spans\n */\nfunction reconstructToolInvocations(spanTree: SpanTree, parentSpanId: string) {\n const toolSpans = getChildrenOfType<SpanRecord>(spanTree, parentSpanId, SpanType.TOOL_CALL);\n\n return toolSpans.map(toolSpan => ({\n toolCallId: toolSpan.spanId,\n toolName: toolSpan.entityName ?? toolSpan.entityId ?? 'unknown',\n toolId: toolSpan.entityId,\n args: toolSpan.input || {},\n result: toolSpan.output || {},\n state: 'result' as const,\n }));\n}\n\n/**\n * Validate trace structure and throw descriptive errors\n */\nexport function validateTrace(trace: TraceRecord): void {\n if (!trace) {\n throw new Error('Trace is null or undefined');\n }\n\n if (!trace.spans || !Array.isArray(trace.spans)) {\n throw new Error('Trace must have a spans array');\n }\n\n if (trace.spans.length === 0) {\n throw new Error('Trace has no spans');\n }\n\n // Check for circular references in parent-child relationships\n const spanIds = new Set(trace.spans.map(span => span.spanId));\n for (const span of trace.spans) {\n if (span.parentSpanId && !spanIds.has(span.parentSpanId)) {\n throw new Error(`Span ${span.spanId} references non-existent parent ${span.parentSpanId}`);\n }\n }\n}\n\n/**\n * Find the most recent model span that contains conversation history\n */\nfunction findPrimaryLLMSpan(spanTree: SpanTree, rootAgentSpan: SpanRecord): SpanRecord {\n const directLLMSpans = getChildrenOfType<SpanRecord>(spanTree, rootAgentSpan.spanId, SpanType.MODEL_GENERATION);\n if (directLLMSpans.length > 0) {\n // There should only be one model generation span per agent run which is a direct child of the root agent span\n return directLLMSpans[0]!;\n }\n\n throw new Error('No model generation span found in trace');\n}\n\n/**\n * Extract common trace validation and span tree building logic\n */\nfunction prepareTraceForTransformation(trace: TraceRecord) {\n validateTrace(trace);\n const spanTree = buildSpanTree(trace.spans);\n\n // Find the root agent run span\n const rootAgentSpan = spanTree.rootSpans.find(span => span.spanType === 'agent_run') as SpanRecord | undefined;\n\n if (!rootAgentSpan) {\n throw new Error('No root agent_run span found in trace');\n }\n\n return { spanTree, rootAgentSpan };\n}\n\nexport function transformTraceToScorerInputAndOutput(trace: TraceRecord): {\n input: ScorerRunInputForAgent;\n output: ScorerRunOutputForAgent;\n} {\n const { spanTree, rootAgentSpan } = prepareTraceForTransformation(trace);\n\n if (!rootAgentSpan.output) {\n throw new Error('Root agent span has no output');\n }\n\n // Build input\n const primaryLLMSpan = findPrimaryLLMSpan(spanTree, rootAgentSpan);\n const inputMessages = extractInputMessages(rootAgentSpan);\n const systemMessages = extractSystemMessages(primaryLLMSpan);\n\n // Extract remembered messages from LLM span (excluding current input)\n const currentInputContent = inputMessages[0]?.content.content || '';\n const rememberedMessages = extractRememberedMessages(primaryLLMSpan, currentInputContent);\n\n const input = {\n inputMessages,\n rememberedMessages,\n systemMessages,\n taggedSystemMessages: {}, // Todo: Support tagged system messages\n };\n\n // Build output\n const toolInvocations = reconstructToolInvocations(spanTree, rootAgentSpan.spanId);\n const responseText = hasTextProperty(rootAgentSpan.output) ? (rootAgentSpan.output.text ?? '') : '';\n\n // Build parts array: tool invocations first, then text\n const parts: Array<{ type: 'tool-invocation'; toolInvocation: any } | { type: 'text'; text: string }> = [];\n\n // Add tool invocation parts\n for (const toolInvocation of toolInvocations) {\n parts.push({\n type: 'tool-invocation',\n toolInvocation,\n });\n }\n\n // Add text part if present\n if (responseText.trim()) {\n parts.push({\n type: 'text',\n text: responseText,\n });\n }\n\n const responseMessage: MastraDBMessage = {\n id: '',\n role: 'assistant',\n content: {\n format: 2,\n parts: parts as any, // Type assertion needed due to providerMetadata optional field\n content: responseText,\n toolInvocations, // Always include, even if empty array\n },\n createdAt: new Date(rootAgentSpan.endedAt || rootAgentSpan.startedAt),\n };\n\n const output: MastraDBMessage[] = [responseMessage];\n\n return {\n input,\n output,\n };\n}\n","import pMap from 'p-map';\nimport z from 'zod';\nimport { ErrorCategory, ErrorDomain, MastraError } from '../../error';\nimport { InternalSpans } from '../../observability';\nimport type { TracingContext } from '../../observability';\nimport type { SpanRecord, TraceRecord, MastraStorage } from '../../storage';\nimport { createStep, createWorkflow } from '../../workflows/evented';\nimport type { MastraScorer, ScorerRun } from '../base';\nimport type { ScoreRowData } from '../types';\nimport { saveScorePayloadSchema } from '../types';\nimport { transformTraceToScorerInputAndOutput } from './utils';\n\nconst getTraceStep = createStep({\n id: '__process-trace-scoring',\n inputSchema: z.object({\n targets: z.array(\n z.object({\n traceId: z.string(),\n spanId: z.string().optional(),\n }),\n ),\n scorerId: z.string(),\n }),\n outputSchema: z.any(),\n execute: async ({ inputData, tracingContext, mastra }) => {\n const logger = mastra.getLogger();\n if (!logger) {\n console.warn(\n '[scoreTracesWorkflow] Logger not initialized: no debug or error logs will be recorded for scoring traces.',\n );\n }\n\n const storage = mastra.getStorage();\n if (!storage) {\n const mastraError = new MastraError({\n id: 'MASTRA_STORAGE_NOT_FOUND_FOR_TRACE_SCORING',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n text: 'Storage not found for trace scoring',\n details: {\n scorerId: inputData.scorerId,\n },\n });\n logger?.error(mastraError.toString());\n logger?.trackException(mastraError);\n return;\n }\n\n let scorer: MastraScorer | undefined;\n try {\n scorer = mastra.getScorerById(inputData.scorerId);\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MASTRA_SCORER_NOT_FOUND_FOR_TRACE_SCORING',\n domain: ErrorDomain.SCORER,\n category: ErrorCategory.SYSTEM,\n text: `Scorer not found for trace scoring`,\n details: {\n scorerId: inputData.scorerId,\n },\n },\n error,\n );\n logger?.error(mastraError.toString());\n logger?.trackException(mastraError);\n return;\n }\n\n await pMap(\n inputData.targets,\n async target => {\n try {\n await runScorerOnTarget({ storage, scorer, target, tracingContext });\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MASTRA_SCORER_FAILED_TO_RUN_SCORER_ON_TRACE',\n domain: ErrorDomain.SCORER,\n category: ErrorCategory.SYSTEM,\n details: {\n scorerId: scorer.id,\n spanId: target.spanId || '',\n traceId: target.traceId,\n },\n },\n error,\n );\n logger?.error(mastraError.toString());\n logger?.trackException(mastraError);\n }\n },\n { concurrency: 3 },\n );\n },\n});\n\nexport async function runScorerOnTarget({\n storage,\n scorer,\n target,\n tracingContext,\n}: {\n storage: MastraStorage;\n scorer: MastraScorer;\n target: { traceId: string; spanId?: string };\n tracingContext: TracingContext;\n}) {\n // TODO: add storage api to get a single span\n const observabilityStore = await storage.getStore('observability');\n if (!observabilityStore) {\n throw new MastraError({\n id: 'MASTRA_OBSERVABILITY_STORAGE_NOT_AVAILABLE',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n text: 'Observability storage domain is not available',\n });\n }\n const trace = await observabilityStore.getTrace({ traceId: target.traceId });\n if (!trace) {\n throw new Error(`Trace not found for scoring, traceId: ${target.traceId}`);\n }\n\n let span: SpanRecord | undefined;\n if (target.spanId) {\n span = trace.spans.find(span => span.spanId === target.spanId);\n } else {\n span = trace.spans.find(span => span.parentSpanId === null);\n }\n\n if (!span) {\n throw new Error(\n `Span not found for scoring, traceId: ${target.traceId}, spanId: ${target.spanId ?? 'Not provided'}`,\n );\n }\n\n const scorerRun = buildScorerRun({\n scorerType: scorer.type === 'agent' ? 'agent' : undefined,\n tracingContext,\n trace,\n targetSpan: span,\n });\n\n const result = await scorer.run(scorerRun);\n const scorerResult = {\n ...result,\n scorer: {\n id: scorer.id,\n name: scorer.name || scorer.id,\n description: scorer.description,\n hasJudge: !!scorer.judge,\n },\n traceId: target.traceId,\n spanId: target.spanId,\n entityId: span.entityId || span.entityName || 'unknown',\n entityType: span.spanType,\n entity: { traceId: span.traceId, spanId: span.spanId },\n source: 'TEST',\n scorerId: scorer.id,\n };\n\n const savedScoreRecord = await validateAndSaveScore({ storage, scorerResult });\n await attachScoreToSpan({ storage, span, scoreRecord: savedScoreRecord });\n}\n\nasync function validateAndSaveScore({ storage, scorerResult }: { storage: MastraStorage; scorerResult: ScorerRun }) {\n const scoresStore = await storage.getStore('scores');\n if (!scoresStore) {\n throw new MastraError({\n id: 'MASTRA_SCORES_STORAGE_NOT_AVAILABLE',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n text: 'Scores storage domain is not available',\n });\n }\n const payloadToSave = saveScorePayloadSchema.parse(scorerResult);\n const result = await scoresStore.saveScore(payloadToSave);\n return result.score;\n}\n\nfunction buildScorerRun({\n scorerType,\n tracingContext,\n trace,\n targetSpan,\n}: {\n scorerType?: string;\n tracingContext: TracingContext;\n trace: TraceRecord;\n targetSpan: SpanRecord;\n}) {\n let runPayload: ScorerRun;\n if (scorerType === 'agent') {\n const { input, output } = transformTraceToScorerInputAndOutput(trace);\n runPayload = {\n input,\n output,\n };\n } else {\n runPayload = { input: targetSpan.input, output: targetSpan.output };\n }\n\n runPayload.tracingContext = tracingContext;\n return runPayload;\n}\n\nasync function attachScoreToSpan({\n storage,\n span,\n scoreRecord,\n}: {\n storage: MastraStorage;\n span: SpanRecord;\n scoreRecord: ScoreRowData;\n}) {\n const observabilityStore = await storage.getStore('observability');\n if (!observabilityStore) {\n throw new MastraError({\n id: 'MASTRA_OBSERVABILITY_STORAGE_NOT_AVAILABLE',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n text: 'Observability storage domain is not available',\n });\n }\n const existingLinks = span.links || [];\n const link = {\n type: 'score',\n scoreId: scoreRecord.id,\n scorerName: scoreRecord.scorer.id,\n score: scoreRecord.score,\n createdAt: scoreRecord.createdAt,\n };\n await observabilityStore.updateSpan({\n spanId: span.spanId,\n traceId: span.traceId,\n updates: { links: [...existingLinks, link] },\n });\n}\n\nexport const scoreTracesWorkflow = createWorkflow({\n id: '__batch-scoring-traces',\n inputSchema: z.object({\n targets: z.array(\n z.object({\n traceId: z.string(),\n spanId: z.string().optional(),\n }),\n ),\n scorerId: z.string(),\n }),\n outputSchema: z.any(),\n steps: [getTraceStep],\n options: {\n tracingPolicy: {\n internal: InternalSpans.ALL,\n },\n validateInputs: false,\n },\n});\n\nscoreTracesWorkflow.then(getTraceStep).commit();\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"scoreTracesWorkflow.d.ts","sourceRoot":"","sources":["../../../src/evals/scoreTraces/scoreTracesWorkflow.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,KAAK,EAA2B,aAAa,EAAE,MAAM,eAAe,CAAC;AAE5E,OAAO,KAAK,EAAE,YAAY,EAAa,MAAM,SAAS,CAAC;AA0FvD,wBAAsB,iBAAiB,CAAC,EACtC,OAAO,EACP,MAAM,EACN,MAAM,EACN,cAAc,GACf,EAAE;IACD,OAAO,EAAE,aAAa,CAAC;IACvB,MAAM,EAAE,YAAY,CAAC;IACrB,MAAM,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IAC7C,cAAc,EAAE,cAAc,CAAC;CAChC,iBAuDA;AA4ED,eAAO,MAAM,mBAAmB;;;;;;;;;;;;;;;;;;EAmB9B,CAAC"}
1
+ {"version":3,"file":"scoreTracesWorkflow.d.ts","sourceRoot":"","sources":["../../../src/evals/scoreTraces/scoreTracesWorkflow.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,KAAK,EAA2B,aAAa,EAAE,MAAM,eAAe,CAAC;AAE5E,OAAO,KAAK,EAAE,YAAY,EAAa,MAAM,SAAS,CAAC;AA0FvD,wBAAsB,iBAAiB,CAAC,EACtC,OAAO,EACP,MAAM,EACN,MAAM,EACN,cAAc,GACf,EAAE;IACD,OAAO,EAAE,aAAa,CAAC;IACvB,MAAM,EAAE,YAAY,CAAC;IACrB,MAAM,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IAC7C,cAAc,EAAE,cAAc,CAAC;CAChC,iBAwDA;AA4ED,eAAO,MAAM,mBAAmB;;;;;;;;;;;;;;;;;;EAmB9B,CAAC"}