@mastra/core 1.18.0-alpha.3 → 1.18.0-alpha.5

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 (223) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/dist/_types/@internal_core/dist/index.d.ts +1078 -256
  3. package/dist/agent/agent-legacy.d.ts +2 -0
  4. package/dist/agent/agent-legacy.d.ts.map +1 -1
  5. package/dist/agent/agent.d.ts.map +1 -1
  6. package/dist/agent/index.cjs +8 -8
  7. package/dist/agent/index.js +1 -1
  8. package/dist/agent/workflows/prepare-stream/map-results-step.d.ts.map +1 -1
  9. package/dist/{chunk-ZFH5KWHO.js → chunk-27EVOYQC.js} +3 -3
  10. package/dist/{chunk-ZFH5KWHO.js.map → chunk-27EVOYQC.js.map} +1 -1
  11. package/dist/{chunk-32NEFSTI.js → chunk-3CTQJRNS.js} +17 -12
  12. package/dist/chunk-3CTQJRNS.js.map +1 -0
  13. package/dist/{chunk-QXPUTX3W.cjs → chunk-4BZRWJBH.cjs} +33 -32
  14. package/dist/chunk-4BZRWJBH.cjs.map +1 -0
  15. package/dist/{chunk-AHFHYQS6.js → chunk-4FMKWOPC.js} +4 -4
  16. package/dist/{chunk-AHFHYQS6.js.map → chunk-4FMKWOPC.js.map} +1 -1
  17. package/dist/{chunk-BFRUEBG3.js → chunk-5LA5TY63.js} +4 -4
  18. package/dist/{chunk-BFRUEBG3.js.map → chunk-5LA5TY63.js.map} +1 -1
  19. package/dist/{chunk-OKKJRRSS.cjs → chunk-7456ZWIM.cjs} +32 -14
  20. package/dist/chunk-7456ZWIM.cjs.map +1 -0
  21. package/dist/{chunk-D5VCCQ4L.js → chunk-7IKOVR4F.js} +5 -5
  22. package/dist/{chunk-D5VCCQ4L.js.map → chunk-7IKOVR4F.js.map} +1 -1
  23. package/dist/{chunk-K4NN2KQQ.cjs → chunk-AV4YSAZL.cjs} +6 -2
  24. package/dist/chunk-AV4YSAZL.cjs.map +1 -0
  25. package/dist/{chunk-7USX5P3I.js → chunk-AYVJ4EXL.js} +28 -5
  26. package/dist/chunk-AYVJ4EXL.js.map +1 -0
  27. package/dist/{chunk-B6D4D2CY.cjs → chunk-BF7IH4JU.cjs} +297 -68
  28. package/dist/chunk-BF7IH4JU.cjs.map +1 -0
  29. package/dist/{chunk-5IZ346TV.cjs → chunk-BL7DAQXE.cjs} +7 -7
  30. package/dist/{chunk-5IZ346TV.cjs.map → chunk-BL7DAQXE.cjs.map} +1 -1
  31. package/dist/{chunk-ZFZ6HQFT.cjs → chunk-BZUTYPXP.cjs} +210 -187
  32. package/dist/chunk-BZUTYPXP.cjs.map +1 -0
  33. package/dist/{chunk-UORUVXKY.js → chunk-DBHNKGT2.js} +6 -6
  34. package/dist/{chunk-UORUVXKY.js.map → chunk-DBHNKGT2.js.map} +1 -1
  35. package/dist/{chunk-GRMC2OYN.js → chunk-FA4PTEBK.js} +6 -3
  36. package/dist/chunk-FA4PTEBK.js.map +1 -0
  37. package/dist/{chunk-QVVWKMFM.cjs → chunk-GXXNF6NF.cjs} +25 -25
  38. package/dist/{chunk-QVVWKMFM.cjs.map → chunk-GXXNF6NF.cjs.map} +1 -1
  39. package/dist/{chunk-GVHBM6VU.cjs → chunk-H3DHOME4.cjs} +29 -11
  40. package/dist/chunk-H3DHOME4.cjs.map +1 -0
  41. package/dist/{chunk-ABA3KD3X.js → chunk-HRT662B6.js} +3 -3
  42. package/dist/{chunk-ABA3KD3X.js.map → chunk-HRT662B6.js.map} +1 -1
  43. package/dist/chunk-IHVB4C5U.cjs +4 -0
  44. package/dist/{chunk-ROOVGRNA.cjs.map → chunk-IHVB4C5U.cjs.map} +1 -1
  45. package/dist/{chunk-FB6O7FNK.js → chunk-IM6BRUQI.js} +9 -9
  46. package/dist/{chunk-FB6O7FNK.js.map → chunk-IM6BRUQI.js.map} +1 -1
  47. package/dist/{chunk-6LHF5UDX.cjs → chunk-INENOZKZ.cjs} +9 -9
  48. package/dist/{chunk-6LHF5UDX.cjs.map → chunk-INENOZKZ.cjs.map} +1 -1
  49. package/dist/{chunk-PYNUWPGW.cjs → chunk-JVL4ANDA.cjs} +19 -19
  50. package/dist/{chunk-PYNUWPGW.cjs.map → chunk-JVL4ANDA.cjs.map} +1 -1
  51. package/dist/{chunk-OVWOD5GI.cjs → chunk-JWE3L5J2.cjs} +20 -20
  52. package/dist/{chunk-OVWOD5GI.cjs.map → chunk-JWE3L5J2.cjs.map} +1 -1
  53. package/dist/{chunk-HDPQ3LEE.js → chunk-K7AE4BHR.js} +4 -4
  54. package/dist/{chunk-HDPQ3LEE.js.map → chunk-K7AE4BHR.js.map} +1 -1
  55. package/dist/{chunk-4K2NKQGN.cjs → chunk-KCRQQDEF.cjs} +201 -196
  56. package/dist/chunk-KCRQQDEF.cjs.map +1 -0
  57. package/dist/{chunk-CX5I6VS4.js → chunk-KRFGPA2H.js} +280 -69
  58. package/dist/chunk-KRFGPA2H.js.map +1 -0
  59. package/dist/{chunk-OXS5X7PW.cjs → chunk-LKZQG2ZZ.cjs} +13 -13
  60. package/dist/{chunk-OXS5X7PW.cjs.map → chunk-LKZQG2ZZ.cjs.map} +1 -1
  61. package/dist/{chunk-W2QYKEBN.js → chunk-MJF7NZEF.js} +545 -33
  62. package/dist/chunk-MJF7NZEF.js.map +1 -0
  63. package/dist/{chunk-SLHDZJ4B.js → chunk-PMWMEK4T.js} +5 -4
  64. package/dist/chunk-PMWMEK4T.js.map +1 -0
  65. package/dist/chunk-S43VACTO.js +3 -0
  66. package/dist/{chunk-DMX7MC4N.js.map → chunk-S43VACTO.js.map} +1 -1
  67. package/dist/{chunk-X36INADV.cjs → chunk-V2NQOABM.cjs} +563 -51
  68. package/dist/chunk-V2NQOABM.cjs.map +1 -0
  69. package/dist/{chunk-IR4WRS3N.js → chunk-W4I7AX2S.js} +31 -13
  70. package/dist/chunk-W4I7AX2S.js.map +1 -0
  71. package/dist/{chunk-OYAHOEQP.js → chunk-W6QY3O3X.js} +27 -9
  72. package/dist/chunk-W6QY3O3X.js.map +1 -0
  73. package/dist/{chunk-MP2VGF73.js → chunk-WNI6ACXE.js} +3 -3
  74. package/dist/{chunk-MP2VGF73.js.map → chunk-WNI6ACXE.js.map} +1 -1
  75. package/dist/{chunk-VVR3SFKH.cjs → chunk-XC6ZFHUA.cjs} +70 -70
  76. package/dist/{chunk-VVR3SFKH.cjs.map → chunk-XC6ZFHUA.cjs.map} +1 -1
  77. package/dist/{chunk-3UM5VCQ5.cjs → chunk-XNWKYVLQ.cjs} +3 -3
  78. package/dist/{chunk-3UM5VCQ5.cjs.map → chunk-XNWKYVLQ.cjs.map} +1 -1
  79. package/dist/{chunk-64565EZF.cjs → chunk-XQRTJIC7.cjs} +22 -22
  80. package/dist/{chunk-64565EZF.cjs.map → chunk-XQRTJIC7.cjs.map} +1 -1
  81. package/dist/{chunk-T5XU5TAV.cjs → chunk-XRW4AYLH.cjs} +82 -82
  82. package/dist/{chunk-T5XU5TAV.cjs.map → chunk-XRW4AYLH.cjs.map} +1 -1
  83. package/dist/{chunk-YBVRBNRY.js → chunk-YIBYKN6M.js} +7 -7
  84. package/dist/{chunk-YBVRBNRY.js.map → chunk-YIBYKN6M.js.map} +1 -1
  85. package/dist/datasets/dataset.d.ts +1 -0
  86. package/dist/datasets/dataset.d.ts.map +1 -1
  87. package/dist/datasets/experiment/index.d.ts.map +1 -1
  88. package/dist/datasets/index.cjs +17 -17
  89. package/dist/datasets/index.js +2 -2
  90. package/dist/datasets/manager.d.ts +1 -0
  91. package/dist/datasets/manager.d.ts.map +1 -1
  92. package/dist/docs/SKILL.md +1 -1
  93. package/dist/docs/assets/SOURCE_MAP.json +611 -534
  94. package/dist/docs/references/reference-configuration.md +24 -0
  95. package/dist/docs/references/reference-core-mastra-model-gateway.md +2 -0
  96. package/dist/evals/index.cjs +23 -23
  97. package/dist/evals/index.js +3 -3
  98. package/dist/evals/scoreTraces/index.cjs +7 -7
  99. package/dist/evals/scoreTraces/index.js +3 -3
  100. package/dist/harness/index.cjs +17 -17
  101. package/dist/harness/index.js +7 -7
  102. package/dist/index.cjs +2 -2
  103. package/dist/index.js +1 -1
  104. package/dist/integration/index.cjs +2 -2
  105. package/dist/integration/index.js +1 -1
  106. package/dist/llm/index.cjs +16 -16
  107. package/dist/llm/index.js +5 -5
  108. package/dist/llm/model/gateways/models-dev.d.ts.map +1 -1
  109. package/dist/llm/model/provider-types.generated.d.ts +11 -2
  110. package/dist/loop/index.cjs +14 -14
  111. package/dist/loop/index.js +1 -1
  112. package/dist/mastra/index.cjs +2 -2
  113. package/dist/mastra/index.js +1 -1
  114. package/dist/memory/index.cjs +14 -14
  115. package/dist/memory/index.js +1 -1
  116. package/dist/models-dev-5X6CFNIO.cjs +12 -0
  117. package/dist/{models-dev-MIC2CW43.cjs.map → models-dev-5X6CFNIO.cjs.map} +1 -1
  118. package/dist/models-dev-NFYFNV6D.js +3 -0
  119. package/dist/{models-dev-VDZIOMAC.js.map → models-dev-NFYFNV6D.js.map} +1 -1
  120. package/dist/netlify-EYSCS3HJ.js +3 -0
  121. package/dist/{netlify-2CGMKEKT.js.map → netlify-EYSCS3HJ.js.map} +1 -1
  122. package/dist/netlify-MZJ7FN5B.cjs +12 -0
  123. package/dist/{netlify-KZ4HQR5N.cjs.map → netlify-MZJ7FN5B.cjs.map} +1 -1
  124. package/dist/observability/index.cjs +18 -18
  125. package/dist/observability/index.js +1 -1
  126. package/dist/observability/no-op.d.ts +14 -1
  127. package/dist/observability/no-op.d.ts.map +1 -1
  128. package/dist/observability/types/core.d.ts +35 -4
  129. package/dist/observability/types/core.d.ts.map +1 -1
  130. package/dist/observability/types/feedback.d.ts +42 -11
  131. package/dist/observability/types/feedback.d.ts.map +1 -1
  132. package/dist/observability/types/logging.d.ts +6 -9
  133. package/dist/observability/types/logging.d.ts.map +1 -1
  134. package/dist/observability/types/metrics.d.ts +6 -4
  135. package/dist/observability/types/metrics.d.ts.map +1 -1
  136. package/dist/observability/types/scores.d.ts +25 -10
  137. package/dist/observability/types/scores.d.ts.map +1 -1
  138. package/dist/observability/types/tracing.d.ts +14 -5
  139. package/dist/observability/types/tracing.d.ts.map +1 -1
  140. package/dist/processor-provider/index.cjs +10 -10
  141. package/dist/processor-provider/index.js +1 -1
  142. package/dist/processors/index.cjs +44 -44
  143. package/dist/processors/index.js +1 -1
  144. package/dist/processors/runner.d.ts.map +1 -1
  145. package/dist/provider-registry-ODJKK7NU.js +3 -0
  146. package/dist/{provider-registry-QRWUBN5N.js.map → provider-registry-ODJKK7NU.js.map} +1 -1
  147. package/dist/provider-registry-YGVNXVGE.cjs +40 -0
  148. package/dist/{provider-registry-HGWTTWCL.cjs.map → provider-registry-YGVNXVGE.cjs.map} +1 -1
  149. package/dist/provider-registry.json +27 -9
  150. package/dist/relevance/index.cjs +3 -3
  151. package/dist/relevance/index.js +1 -1
  152. package/dist/server/types.d.ts +16 -0
  153. package/dist/server/types.d.ts.map +1 -1
  154. package/dist/storage/constants.cjs +56 -56
  155. package/dist/storage/constants.d.ts.map +1 -1
  156. package/dist/storage/constants.js +1 -1
  157. package/dist/storage/domains/datasets/inmemory.d.ts.map +1 -1
  158. package/dist/storage/domains/observability/base.d.ts +10 -2
  159. package/dist/storage/domains/observability/base.d.ts.map +1 -1
  160. package/dist/storage/domains/observability/feedback.d.ts +1 -1
  161. package/dist/storage/domains/observability/feedback.d.ts.map +1 -1
  162. package/dist/storage/domains/observability/inmemory.d.ts +13 -2
  163. package/dist/storage/domains/observability/inmemory.d.ts.map +1 -1
  164. package/dist/storage/domains/observability/record-builders.d.ts.map +1 -1
  165. package/dist/storage/domains/observability/scores.d.ts +1 -1
  166. package/dist/storage/domains/observability/scores.d.ts.map +1 -1
  167. package/dist/storage/domains/observability/tracing.d.ts +8 -8
  168. package/dist/storage/domains/shared.d.ts +1 -1
  169. package/dist/storage/domains/shared.d.ts.map +1 -1
  170. package/dist/storage/index.cjs +340 -268
  171. package/dist/storage/index.js +3 -3
  172. package/dist/storage/types.d.ts +3 -0
  173. package/dist/storage/types.d.ts.map +1 -1
  174. package/dist/stream/index.cjs +8 -8
  175. package/dist/stream/index.js +1 -1
  176. package/dist/test-utils/llm-mock.cjs +4 -4
  177. package/dist/test-utils/llm-mock.js +1 -1
  178. package/dist/tool-loop-agent/index.cjs +4 -4
  179. package/dist/tool-loop-agent/index.js +1 -1
  180. package/dist/tools/index.cjs +11 -7
  181. package/dist/tools/index.d.ts +1 -1
  182. package/dist/tools/index.d.ts.map +1 -1
  183. package/dist/tools/index.js +1 -1
  184. package/dist/tools/is-vercel-tool.cjs +2 -2
  185. package/dist/tools/is-vercel-tool.js +1 -1
  186. package/dist/tools/validation.d.ts +1 -0
  187. package/dist/tools/validation.d.ts.map +1 -1
  188. package/dist/utils.cjs +23 -23
  189. package/dist/utils.js +1 -1
  190. package/dist/vector/index.cjs +7 -7
  191. package/dist/vector/index.js +1 -1
  192. package/dist/workflows/evented/index.cjs +10 -10
  193. package/dist/workflows/evented/index.js +1 -1
  194. package/dist/workflows/index.cjs +24 -24
  195. package/dist/workflows/index.js +1 -1
  196. package/dist/workspace/index.cjs +68 -68
  197. package/dist/workspace/index.js +1 -1
  198. package/package.json +4 -4
  199. package/src/llm/model/provider-types.generated.d.ts +11 -2
  200. package/dist/chunk-32NEFSTI.js.map +0 -1
  201. package/dist/chunk-4K2NKQGN.cjs.map +0 -1
  202. package/dist/chunk-7USX5P3I.js.map +0 -1
  203. package/dist/chunk-B6D4D2CY.cjs.map +0 -1
  204. package/dist/chunk-CX5I6VS4.js.map +0 -1
  205. package/dist/chunk-DMX7MC4N.js +0 -3
  206. package/dist/chunk-GRMC2OYN.js.map +0 -1
  207. package/dist/chunk-GVHBM6VU.cjs.map +0 -1
  208. package/dist/chunk-IR4WRS3N.js.map +0 -1
  209. package/dist/chunk-K4NN2KQQ.cjs.map +0 -1
  210. package/dist/chunk-OKKJRRSS.cjs.map +0 -1
  211. package/dist/chunk-OYAHOEQP.js.map +0 -1
  212. package/dist/chunk-QXPUTX3W.cjs.map +0 -1
  213. package/dist/chunk-ROOVGRNA.cjs +0 -4
  214. package/dist/chunk-SLHDZJ4B.js.map +0 -1
  215. package/dist/chunk-W2QYKEBN.js.map +0 -1
  216. package/dist/chunk-X36INADV.cjs.map +0 -1
  217. package/dist/chunk-ZFZ6HQFT.cjs.map +0 -1
  218. package/dist/models-dev-MIC2CW43.cjs +0 -12
  219. package/dist/models-dev-VDZIOMAC.js +0 -3
  220. package/dist/netlify-2CGMKEKT.js +0 -3
  221. package/dist/netlify-KZ4HQR5N.cjs +0 -12
  222. package/dist/provider-registry-HGWTTWCL.cjs +0 -40
  223. package/dist/provider-registry-QRWUBN5N.js +0 -3
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/observability/types/core.ts","../../_internal-core/src/storage/domains/shared.ts","../../_internal-core/src/storage/domains/observability/logs.ts","../../_internal-core/src/storage/domains/observability/scores.ts","../../_internal-core/src/storage/domains/observability/feedback.ts","../../_internal-core/src/storage/domains/observability/metrics.ts","../../_internal-core/src/storage/domains/observability/discovery.ts","../src/observability/types/tracing.ts","../src/observability/types/metrics.ts","../src/observability/no-op.ts","../src/observability/utils.ts","../src/observability/context-factory.ts","../src/observability/context.ts"],"names":["SamplingStrategyType","EntityType","z","sourceField","SpanType","InternalSpans","TracingEventType"],"mappings":";;;AAqQO,IAAK,oBAAA,qBAAAA,qBAAAA,KAAL;AACL,EAAAA,sBAAA,QAAA,CAAA,GAAS,QAAA;AACT,EAAAA,sBAAA,OAAA,CAAA,GAAQ,OAAA;AACR,EAAAA,sBAAA,OAAA,CAAA,GAAQ,OAAA;AACR,EAAAA,sBAAA,QAAA,CAAA,GAAS,QAAA;AAJC,EAAA,OAAAA,qBAAAA;AAAA,CAAA,EAAA,oBAAA,IAAA,EAAA;AClQL,IAAK,UAAA,qBAAAC,WAAAA,KAAL;AAELA,EAAAA,WAAAA,CAAA,OAAA,CAAA,GAAQ,OAAA;AAERA,EAAAA,WAAAA,CAAA,MAAA,CAAA,GAAO,MAAA;AAEPA,EAAAA,WAAAA,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Aa,KAAA,CAAM,IAAA,CAAK,MAAM,CAAA,GAAI,KAAA;AAAA,QAC5D;AAAA,MACF;AAAA,KACD,CAAA;AAAA,EACH,SAAS,KAAA,EAAO;AACd,IAAA,OAAA,CAAQ,IAAA,CAAK,gEAAgE,KAAK,CAAA;AAClF,IAAA,OAAO,GAAA;AAAA,EACT;AACF","file":"chunk-CX5I6VS4.js","sourcesContent":["/**\n * Top-level observability infrastructure types.\n *\n * This file contains the core observability interfaces for managing instances,\n * exporters, bridges, configuration, event bus, and the context mixin.\n *\n * For tracing-specific types (spans, span types, attributes, etc.), see tracing.ts.\n */\nimport type { IMastraLogger } from '../../logger';\nimport type { Mastra } from '../../mastra';\nimport type { RequestContext } from '../../request-context';\nimport type { FeedbackEvent } from './feedback';\nimport type { LoggerContext, LogEvent } from './logging';\nimport type { MetricsContext, MetricEvent } from './metrics';\nimport type { ScoreEvent } from './scores';\nimport type {\n AnySpan,\n CreateSpanOptions,\n EntityType,\n ExportedSpan,\n Span,\n SpanIds,\n SpanOutputProcessor,\n SpanType,\n StartSpanOptions,\n TracingContext,\n TracingEvent,\n} from './tracing';\n\n// ============================================================================\n// ObservabilityContext\n// ============================================================================\n\n/**\n * Canonical observability correlation and execution context.\n * These fields can travel alongside observability signals without being encoded in labels.\n */\nexport interface CorrelationContext {\n // Correlation\n traceId?: string;\n spanId?: string;\n tags?: string[];\n\n // Context\n entityType?: EntityType;\n entityId?: string;\n entityName?: string;\n parentEntityType?: EntityType;\n parentEntityId?: string;\n parentEntityName?: string;\n rootEntityType?: EntityType;\n rootEntityId?: string;\n rootEntityName?: string;\n userId?: string;\n organizationId?: string;\n resourceId?: string;\n runId?: string;\n sessionId?: string;\n threadId?: string;\n requestId?: string;\n environment?: string;\n source?: string;\n serviceName?: string;\n experimentId?: string;\n}\n\n/**\n * Mixin interface that provides unified observability access.\n * All execution contexts (tools, workflow steps, processors) extend this\n * to gain access to tracing, logging, and metrics.\n *\n * ## Naming conventions\n *\n * `tracingContext` is the **source** — it represents your position in the span tree.\n * Creating a child span produces a new `tracingContext` with that child as `currentSpan`.\n *\n * `loggerVNext` and `metrics` are **derived** — they are rebuilt from the current span so that\n * log entries and metric data points are automatically correlated to the active trace:\n *\n * ```\n * tracingContext → create child span → new tracingContext\n * → new loggerVNext (correlated to child span)\n * → new metrics (tagged with child span metadata)\n * ```\n *\n * The short names (`tracing`, `loggerVNext`, `metrics`) read naturally at **usage sites**:\n * `tracing.createSpan()`, `loggerVNext.info()`, `metrics.record()`.\n *\n * `loggerVNext` uses the VNext suffix to distinguish from the existing `logger: IMastraLogger`\n * infrastructure logger used throughout the codebase (e.g. `MastraPrimitives.logger`).\n *\n * The `tracingContext` alias is preferred at **forwarding sites** where the \"Context\"\n * suffix clarifies that a structural context object is being passed, not a subsystem.\n */\nexport interface ObservabilityContext {\n /** Tracing context for span creation and tree navigation. */\n tracing: TracingContext;\n\n /** Logger derived from the current span — log entries are trace-correlated. Uses VNext suffix to avoid conflict with IMastraLogger. */\n loggerVNext: LoggerContext;\n\n /** Metrics derived from the current span — data points are span-tagged. */\n metrics: MetricsContext;\n\n /**\n * Alias for `tracing`. Preferred at forwarding sites where the \"Context\" suffix\n * clarifies that a structural context object is being passed between functions.\n */\n tracingContext: TracingContext;\n}\n\n// ============================================================================\n// ObservabilityEventBus\n// ============================================================================\n\n/**\n * Generic event bus interface for observability events.\n * Implementations handle buffering, batching, and delivery to exporters.\n */\nexport interface ObservabilityEventBus<TEvent> {\n /** Emit an event to the bus */\n emit(event: TEvent): void;\n\n /** Subscribe to events. Returns unsubscribe function. */\n subscribe(handler: (event: TEvent) => void): () => void;\n\n /** Flush any buffered events */\n flush(): Promise<void>;\n\n /** Shutdown the bus and release resources */\n shutdown(): Promise<void>;\n}\n\n/**\n * Union of all observability event types.\n * Used by the unified ObservabilityBus that handles all signals.\n */\nexport type ObservabilityEvent = TracingEvent | LogEvent | MetricEvent | ScoreEvent | FeedbackEvent;\n\n// ============================================================================\n// ObservabilityInstance\n// ============================================================================\n\n/**\n * Primary interface for Observability\n */\nexport interface ObservabilityInstance {\n /**\n * Get current configuration\n */\n getConfig(): Readonly<ObservabilityInstanceConfig>;\n\n /**\n * Get all exporters\n */\n getExporters(): readonly ObservabilityExporter[];\n\n /**\n * Get all span output processors\n */\n getSpanOutputProcessors(): readonly SpanOutputProcessor[];\n\n /**\n * Get the logger instance (for exporters and other components)\n */\n getLogger(): IMastraLogger;\n\n /**\n * Get the bridge instance if configured\n */\n getBridge(): ObservabilityBridge | undefined;\n\n /**\n * Start a new span of a specific SpanType\n */\n startSpan<TType extends SpanType>(options: StartSpanOptions<TType>): Span<TType>;\n\n /**\n * Rebuild a span from exported data for lifecycle operations.\n * Used by durable execution engines (e.g., Inngest) to end/update spans\n * that were created in a previous durable operation.\n *\n * @param cached - The exported span data to rebuild from\n * @returns A span that can have end()/update()/error() called on it\n */\n rebuildSpan<TType extends SpanType>(cached: ExportedSpan<TType>): Span<TType>;\n\n /**\n * Force flush any buffered/queued spans from all exporters and the bridge\n * without shutting down the observability instance.\n *\n * This is useful in serverless environments (like Vercel's fluid compute) where\n * you need to ensure all spans are exported before the runtime instance is\n * terminated, while keeping the observability system active for future requests.\n *\n * Unlike shutdown(), flush() does not release resources or prevent future tracing.\n */\n flush(): Promise<void>;\n\n /**\n * Shutdown tracing and clean up resources\n */\n shutdown(): Promise<void>;\n\n /**\n * Override setLogger to add tracing specific initialization log\n */\n __setLogger(logger: IMastraLogger): void;\n\n /**\n * Get a LoggerContext for this instance, optionally correlated to a span.\n * When a span is provided, the returned logger automatically includes\n * the span's traceId, spanId, and other metadata in every log entry.\n * Returns no-op context when logging is not configured on this instance.\n *\n * @param span - Optional span to correlate logs with\n */\n getLoggerContext?(span?: AnySpan): LoggerContext;\n\n /**\n * Get a MetricsContext for this instance, optionally tagged from a span.\n * When a span is provided, the returned metrics context automatically\n * includes the span's metadata as labels/tags on emitted data points.\n * Returns no-op context when metrics are not configured on this instance.\n *\n * @param span - Optional span to derive metric tags from\n */\n getMetricsContext?(span?: AnySpan): MetricsContext;\n}\n\n// ============================================================================\n// ObservabilityEntrypoint\n// ============================================================================\n\nexport interface ObservabilityEntrypoint {\n shutdown(): Promise<void>;\n\n setMastraContext(options: { mastra: Mastra }): void;\n\n setLogger(options: { logger: IMastraLogger }): void;\n\n getSelectedInstance(options: ConfigSelectorOptions): ObservabilityInstance | undefined;\n\n // Registry management methods\n registerInstance(name: string, instance: ObservabilityInstance, isDefault?: boolean): void;\n getInstance(name: string): ObservabilityInstance | undefined;\n getDefaultInstance(): ObservabilityInstance | undefined;\n listInstances(): ReadonlyMap<string, ObservabilityInstance>;\n unregisterInstance(name: string): boolean;\n hasInstance(name: string): boolean;\n setConfigSelector(selector: ConfigSelector): void;\n clear(): void;\n}\n\n// ============================================================================\n// Sampling Strategy\n// ============================================================================\n\n/**\n * Sampling strategy types\n */\nexport enum SamplingStrategyType {\n ALWAYS = 'always',\n NEVER = 'never',\n RATIO = 'ratio',\n CUSTOM = 'custom',\n}\n\n/**\n * Sampling strategy configuration\n */\nexport type SamplingStrategy =\n | { type: SamplingStrategyType.ALWAYS }\n | { type: SamplingStrategyType.NEVER }\n | { type: SamplingStrategyType.RATIO; probability: number }\n | { type: SamplingStrategyType.CUSTOM; sampler: (options?: CustomSamplerOptions) => boolean };\n\n/**\n * Options passed when using a custom sampler strategy\n */\nexport interface CustomSamplerOptions {\n requestContext?: RequestContext;\n metadata?: Record<string, any>;\n}\n\n// ============================================================================\n// Serialization Options\n// ============================================================================\n\n/**\n * Options for controlling serialization of span data.\n * These options control how input, output, and attributes are cleaned before export.\n */\nexport interface SerializationOptions {\n /**\n * Maximum length for string values\n * @default 1024\n */\n maxStringLength?: number;\n /**\n * Maximum depth for nested objects\n * @default 6\n */\n maxDepth?: number;\n /**\n * Maximum number of items in arrays\n * @default 50\n */\n maxArrayLength?: number;\n /**\n * Maximum number of keys in objects\n * @default 50\n */\n maxObjectKeys?: number;\n}\n\n// ============================================================================\n// Registry Config\n// ============================================================================\n\n/**\n * Configuration for a single observability instance\n */\nexport interface ObservabilityInstanceConfig {\n /** Unique identifier for this config in the observability registry */\n name: string;\n /** Service name for observability */\n serviceName: string;\n /** Sampling strategy - controls whether tracing is collected (defaults to ALWAYS) */\n sampling?: SamplingStrategy;\n /** Custom exporters */\n exporters?: ObservabilityExporter[];\n /** Custom processors */\n spanOutputProcessors?: SpanOutputProcessor[];\n /** OpenTelemetry bridge for integration with existing OTEL infrastructure */\n bridge?: ObservabilityBridge;\n /** Set to `true` if you want to see spans internal to the operation of mastra */\n includeInternalSpans?: boolean;\n /**\n * RequestContext keys to automatically extract as metadata for all spans\n * created with this observability configuration.\n * Supports dot notation for nested values.\n */\n requestContextKeys?: string[];\n /**\n * Options for controlling serialization of span data (input/output/attributes).\n * Use these to customize truncation limits for large payloads.\n */\n serializationOptions?: SerializationOptions;\n}\n\n/**\n * Complete Observability registry configuration\n */\nexport interface ObservabilityRegistryConfig {\n /** Enables default exporters, with sampling: always, and sensitive data filtering */\n default?: {\n enabled?: boolean;\n };\n /** Map of tracing instance names to their configurations or pre-instantiated instances */\n configs?: Record<string, Omit<ObservabilityInstanceConfig, 'name'> | ObservabilityInstance>;\n /** Optional selector function to choose which tracing instance to use */\n configSelector?: ConfigSelector;\n}\n\n// ============================================================================\n// Config Selector\n// ============================================================================\n\n/**\n * Options passed when using a custom tracing config selector\n */\nexport interface ConfigSelectorOptions {\n /** Request Context */\n requestContext?: RequestContext;\n}\n\n/**\n * Function to select which tracing instance to use for a given span\n * Returns the name of the tracing instance, or undefined to use default\n */\nexport type ConfigSelector = (\n options: ConfigSelectorOptions,\n availableConfigs: ReadonlyMap<string, ObservabilityInstance>,\n) => string | undefined;\n\n// ============================================================================\n// Exporter and Bridge Interfaces\n// ============================================================================\n\nexport interface InitExporterOptions {\n mastra?: Mastra;\n config?: ObservabilityInstanceConfig;\n}\n\nexport interface InitBridgeOptions {\n mastra?: Mastra;\n config?: ObservabilityInstanceConfig;\n}\n\n/**\n * Shared Observability event interface for Exporters & Bridges\n */\nexport interface ObservabilityEvents {\n /** Handle tracing events */\n onTracingEvent?(event: TracingEvent): void | Promise<void>;\n\n /** Handle log events */\n onLogEvent?(event: LogEvent): void | Promise<void>;\n\n /** Handle metric events */\n onMetricEvent?(event: MetricEvent): void | Promise<void>;\n\n /** Handle score events */\n onScoreEvent?(event: ScoreEvent): void | Promise<void>;\n\n /** Handle feedback events */\n onFeedbackEvent?(event: FeedbackEvent): void | Promise<void>;\n\n /** Export tracing events */\n exportTracingEvent(event: TracingEvent): Promise<void>;\n}\n\n/**\n * Interface for tracing exporters\n */\nexport interface ObservabilityExporter extends ObservabilityEvents {\n /** Exporter name */\n name: string;\n\n /** Initialize exporter with tracing configuration and/or access to Mastra */\n init?(options: InitExporterOptions): void;\n\n /** Sets logger instance on the exporter. */\n __setLogger?(logger: IMastraLogger): void;\n\n addScoreToTrace?({\n traceId,\n spanId,\n score,\n reason,\n scorerName,\n metadata,\n }: {\n traceId: string;\n spanId?: string;\n score: number;\n reason?: string;\n scorerName: string;\n metadata?: Record<string, any>;\n }): Promise<void>;\n\n /**\n * Force flush any buffered/queued spans without shutting down the exporter.\n * This is useful in serverless environments where you need to ensure spans\n * are exported before the runtime instance is terminated, while keeping\n * the exporter active for future requests.\n *\n * Unlike shutdown(), flush() does not release resources or prevent future exports.\n */\n flush(): Promise<void>;\n\n /** Shutdown exporter */\n shutdown(): Promise<void>;\n}\n\n/**\n * Interface for observability bridges\n */\nexport interface ObservabilityBridge extends ObservabilityEvents {\n /** Bridge name */\n name: string;\n\n /** Initialize bridge with observability configuration and/or access to Mastra */\n init?(options: InitBridgeOptions): void;\n\n /** Sets logger instance on the bridge */\n __setLogger?(logger: IMastraLogger): void;\n\n /**\n * Execute an async function within the tracing context of a Mastra span.\n * This enables auto-instrumented operations (HTTP, DB) to have correct parent spans\n * in the external tracing system (e.g., OpenTelemetry, DataDog, etc.).\n *\n * @param spanId - The ID of the Mastra span to use as context\n * @param fn - The async function to execute within the span context\n * @returns The result of the function execution\n */\n executeInContext?<T>(spanId: string, fn: () => Promise<T>): Promise<T>;\n\n /**\n * Execute a synchronous function within the tracing context of a Mastra span.\n * This enables auto-instrumented operations (HTTP, DB) to have correct parent spans\n * in the external tracing system (e.g., OpenTelemetry, DataDog, etc.).\n *\n * @param spanId - The ID of the Mastra span to use as context\n * @param fn - The synchronous function to execute within the span context\n * @returns The result of the function execution\n */\n executeInContextSync?<T>(spanId: string, fn: () => T): T;\n\n /**\n * Create a span in the bridge's tracing system.\n * Called during Mastra span construction to get bridge-generated identifiers.\n *\n * @param options - Span creation options from Mastra\n * @returns Span identifiers (spanId, traceId, parentSpanId) from bridge, or undefined if creation fails\n */\n createSpan(options: CreateSpanOptions<SpanType>): SpanIds | undefined;\n\n /**\n * Force flush any buffered/queued spans without shutting down the bridge.\n * This is useful in serverless environments where you need to ensure spans\n * are exported before the runtime instance is terminated, while keeping\n * the bridge active for future requests.\n *\n * Unlike shutdown(), flush() does not release resources or prevent future exports.\n */\n flush(): Promise<void>;\n\n /** Shutdown bridge and cleanup resources */\n shutdown(): Promise<void>;\n}\n","import { z } from 'zod/v4';\n\n/** Types of entities that can produce observability spans. */\nexport enum EntityType {\n /** Agent/Model execution */\n AGENT = 'agent',\n /** Eval */\n EVAL = 'eval',\n /** Input Processor */\n INPUT_PROCESSOR = 'input_processor',\n /** Input Step Processor */\n INPUT_STEP_PROCESSOR = 'input_step_processor',\n /** Output Processor */\n OUTPUT_PROCESSOR = 'output_processor',\n /** Output Step Processor */\n OUTPUT_STEP_PROCESSOR = 'output_step_processor',\n /** Workflow Step */\n WORKFLOW_STEP = 'workflow_step',\n /** Tool */\n TOOL = 'tool',\n /** Workflow */\n WORKFLOW_RUN = 'workflow_run',\n}\n\n/**\n * Common DB fields\n */\nexport const createdAtField = z.date().describe('Database record creation time');\n\nexport const updatedAtField = z.date().describe('Database record last update time');\n\nexport const dbTimestamps = {\n createdAt: createdAtField,\n updatedAt: updatedAtField.nullable(),\n} as const satisfies z.ZodRawShape;\n\n/**\n * Pagination arguments for list queries (page and perPage only)\n * Uses z.coerce to handle string → number conversion from query params\n */\nexport const paginationArgsSchema = z\n .object({\n page: z.coerce.number().int().min(0).optional().default(0).describe('Zero-indexed page number'),\n perPage: z.coerce.number().int().min(1).max(100).optional().default(10).describe('Number of items per page'),\n })\n .describe('Pagination options for list queries');\n\n/** Input type for pagination arguments (page and perPage). */\nexport type PaginationArgs = z.input<typeof paginationArgsSchema>;\n\n/**\n * Pagination response info\n * Used across all paginated endpoints\n */\nexport const paginationInfoSchema = z.object({\n total: z.number().describe('Total number of items available'),\n page: z.number().describe('Current page'),\n perPage: z\n .union([z.number(), z.literal(false)])\n .describe('Number of items per page, or false if pagination is disabled'),\n hasMore: z.boolean().describe('True if more pages are available'),\n});\n\n/**\n * Date range for filtering by time\n * Uses z.coerce to handle ISO string → Date conversion from query params\n */\nexport const dateRangeSchema = z\n .object({\n start: z.coerce.date().optional().describe('Start of date range (inclusive by default)'),\n end: z.coerce.date().optional().describe('End of date range (inclusive by default)'),\n startExclusive: z\n .boolean()\n .optional()\n .describe('When true, excludes the start date from results (uses > instead of >=)'),\n endExclusive: z\n .boolean()\n .optional()\n .describe('When true, excludes the end date from results (uses < instead of <=)'),\n })\n .describe('Date range filter for timestamps');\n\n/** Date range with optional inclusive/exclusive boundaries. */\nexport type DateRange = z.input<typeof dateRangeSchema>;\n\nexport const sortDirectionSchema = z.enum(['ASC', 'DESC']).describe(\"Sort direction: 'ASC' | 'DESC'\");\n\nexport const entityTypeField = z\n .nativeEnum(EntityType)\n .describe(`Entity type (e.g., 'agent' | 'processor' | 'tool' | 'workflow')`);\n\nexport const entityIdField = z.string().describe('ID of the entity (e.g., \"weatherAgent\", \"orderWorkflow\")');\n\nexport const entityNameField = z.string().describe('Name of the entity');\n\nexport const userIdField = z.string().describe('Human end-user who triggered execution');\n\nexport const organizationIdField = z.string().describe('Multi-tenant organization/account');\n\nexport const resourceIdField = z.string().describe('Broader resource context (Mastra memory compatibility)');\n\nexport const runIdField = z.string().describe('Unique execution run identifier');\n\nexport const sessionIdField = z.string().describe('Session identifier for grouping traces');\n\nexport const threadIdField = z.string().describe('Conversation thread identifier');\n\nexport const requestIdField = z.string().describe('HTTP request ID for log correlation');\n\nexport const environmentField = z.string().describe(`Environment (e.g., \"production\" | \"staging\" | \"development\")`);\n\nexport const sourceField = z.string().describe(`Source of execution (e.g., \"local\" | \"cloud\" | \"ci\")`);\n\nexport const serviceNameField = z.string().describe('Name of the service');\n\n// Parent entity hierarchy fields\nexport const parentEntityTypeField = z.nativeEnum(EntityType).describe('Entity type of the parent entity');\nexport const parentEntityIdField = z.string().describe('ID of the parent entity');\nexport const parentEntityNameField = z.string().describe('Name of the parent entity');\n\n// Root entity hierarchy fields\nexport const rootEntityTypeField = z.nativeEnum(EntityType).describe('Entity type of the root entity');\nexport const rootEntityIdField = z.string().describe('ID of the root entity');\nexport const rootEntityNameField = z.string().describe('Name of the root entity');\n\n// Experimentation\nexport const experimentIdField = z.string().describe('Experiment or eval run identifier');\n\n// ============================================================================\n// Common observability fields (shared across tracing, metrics, logs)\n// ============================================================================\n\nexport const scopeField = z\n .record(z.string(), z.unknown())\n .describe('Arbitrary package/app version info (e.g., {\"core\": \"1.0.0\", \"memory\": \"1.0.0\", \"gitSha\": \"abcd1234\"})');\n\nexport const metadataField = z.record(z.string(), z.unknown()).describe('User-defined metadata for custom filtering');\n\nexport const tagsField = z.array(z.string()).describe('Labels for filtering');\n\n/**\n * Context fields shared across observability signals (metrics, logs).\n * All fields are nullish — each signal uses them as optional context.\n */\nexport const contextFields = {\n // Entity identification\n entityType: entityTypeField.nullish(),\n entityId: entityIdField.nullish(),\n entityName: entityNameField.nullish(),\n\n // Parent entity hierarchy\n parentEntityType: parentEntityTypeField.nullish(),\n parentEntityId: parentEntityIdField.nullish(),\n parentEntityName: parentEntityNameField.nullish(),\n\n // Root entity hierarchy\n rootEntityType: rootEntityTypeField.nullish(),\n rootEntityId: rootEntityIdField.nullish(),\n rootEntityName: rootEntityNameField.nullish(),\n\n // Identity & tenancy\n userId: userIdField.nullish(),\n organizationId: organizationIdField.nullish(),\n resourceId: resourceIdField.nullish(),\n\n // Correlation IDs\n runId: runIdField.nullish(),\n sessionId: sessionIdField.nullish(),\n threadId: threadIdField.nullish(),\n requestId: requestIdField.nullish(),\n\n // Deployment context\n environment: environmentField.nullish(),\n source: sourceField.nullish(),\n serviceName: serviceNameField.nullish(),\n scope: scopeField.nullish(),\n\n // Experimentation\n experimentId: experimentIdField.nullish(),\n} as const;\n\n/**\n * Common filter fields shared across observability signal filters (metrics, logs, scores, feedback).\n * All fields are optional — each signal extends this with signal-specific filters.\n */\nexport const commonFilterFields = {\n timestamp: dateRangeSchema.optional().describe('Filter by timestamp range'),\n traceId: z.string().optional().describe('Filter by trace ID'),\n spanId: z.string().optional().describe('Filter by span ID'),\n entityType: entityTypeField.optional(),\n entityName: entityNameField.optional(),\n userId: userIdField.optional(),\n organizationId: organizationIdField.optional(),\n experimentId: experimentIdField.optional(),\n serviceName: serviceNameField.optional(),\n environment: environmentField.optional(),\n} as const;\n\n/**\n * Additional filters shared by observability signals that carry correlation context.\n * Logs and metrics should generally expose this same context filter surface.\n */\nexport const observabilitySignalFilterFields = {\n parentEntityType: parentEntityTypeField.optional(),\n parentEntityName: parentEntityNameField.optional(),\n rootEntityType: rootEntityTypeField.optional(),\n rootEntityName: rootEntityNameField.optional(),\n resourceId: resourceIdField.optional(),\n runId: runIdField.optional(),\n sessionId: sessionIdField.optional(),\n threadId: threadIdField.optional(),\n requestId: requestIdField.optional(),\n source: sourceField.optional(),\n tags: z.array(z.string()).optional().describe('Filter by tags (must have all specified tags)'),\n} as const;\n\n// ============================================================================\n// Tracing identifier fields (shared across scores, feedback, metrics)\n// ============================================================================\n\n/** Zod schema for trace ID field */\nexport const traceIdField = z.string().describe('Unique trace identifier');\n\n/** Zod schema for span ID field */\nexport const spanIdField = z.string().describe('Unique span identifier within a trace');\n","import { z } from 'zod/v4';\nimport {\n commonFilterFields,\n contextFields,\n metadataField,\n observabilitySignalFilterFields,\n paginationArgsSchema,\n paginationInfoSchema,\n sortDirectionSchema,\n spanIdField,\n tagsField,\n traceIdField,\n} from '../shared';\n\n// ============================================================================\n// Field Schemas\n// ============================================================================\n\n/** Log level schema for validation */\nexport const logLevelSchema = z.enum(['debug', 'info', 'warn', 'error', 'fatal']);\n\nconst messageField = z.string().describe('Log message');\nconst logDataField = z.record(z.string(), z.unknown()).describe('Structured data attached to the log');\n\n// ============================================================================\n// LogRecord Schema (Storage Format)\n// ============================================================================\n\n/**\n * Schema for logs as stored in the database.\n * Includes all fields from ExportedLog plus storage-specific fields.\n */\nexport const logRecordSchema = z\n .object({\n timestamp: z.date().describe('When the log was created'),\n level: logLevelSchema.describe('Log severity level'),\n message: messageField,\n data: logDataField.nullish(),\n\n // Correlation\n traceId: traceIdField.nullish(),\n spanId: spanIdField.nullish(),\n\n // Context fields (same as tracing)\n ...contextFields,\n\n // Filtering\n tags: tagsField.nullish(),\n metadata: metadataField.nullish(),\n })\n .describe('Log record as stored in the database');\n\n/** Log record type for storage */\nexport type LogRecord = z.infer<typeof logRecordSchema>;\n\n// ============================================================================\n// LogRecordInput Schema (User-Facing API)\n// ============================================================================\n\n/**\n * Schema for user-provided log input (minimal required fields).\n * The logger enriches this with context before emitting ExportedLog.\n */\nexport const logRecordInputSchema = z\n .object({\n level: logLevelSchema,\n message: messageField,\n data: logDataField.optional(),\n tags: tagsField.optional(),\n })\n .describe('User-provided log input');\n\n/** User-facing log input type */\nexport type LogRecordInput = z.infer<typeof logRecordInputSchema>;\n\n// ============================================================================\n// Create Log Schemas\n// ============================================================================\n\n/** Schema for creating a log record */\nexport const createLogRecordSchema = logRecordSchema;\n\n/** Log record for creation (excludes db timestamps) */\nexport type CreateLogRecord = z.infer<typeof createLogRecordSchema>;\n\n/** Schema for batchCreateLogs operation arguments */\nexport const batchCreateLogsArgsSchema = z\n .object({\n logs: z.array(createLogRecordSchema),\n })\n .describe('Arguments for batch creating logs');\n\n/** Arguments for batch creating logs */\nexport type BatchCreateLogsArgs = z.infer<typeof batchCreateLogsArgsSchema>;\n\n// ============================================================================\n// Log Filter Schema\n// ============================================================================\n\n/** Schema for filtering logs in list queries */\nexport const logsFilterSchema = z\n .object({\n ...commonFilterFields,\n ...observabilitySignalFilterFields,\n\n // Log-specific filters\n level: z\n .union([logLevelSchema, z.array(logLevelSchema)])\n .optional()\n .describe('Filter by log level(s)'),\n })\n .describe('Filters for querying logs');\n\n/** Filters for querying logs */\nexport type LogsFilter = z.infer<typeof logsFilterSchema>;\n\n// ============================================================================\n// List Logs Schemas\n// ============================================================================\n\n/** Fields available for ordering log results */\nexport const logsOrderByFieldSchema = z.enum(['timestamp']).describe(\"Field to order by: 'timestamp'\");\n\n/** Order by configuration for log queries */\nexport const logsOrderBySchema = z\n .object({\n field: logsOrderByFieldSchema.default('timestamp').describe('Field to order by'),\n direction: sortDirectionSchema.default('DESC').describe('Sort direction'),\n })\n .describe('Order by configuration');\n\n/** Schema for listLogs operation arguments */\nexport const listLogsArgsSchema = z\n .object({\n filters: logsFilterSchema.optional().describe('Optional filters to apply'),\n pagination: paginationArgsSchema.default({ page: 0, perPage: 10 }).describe('Pagination settings'),\n orderBy: logsOrderBySchema\n .default({ field: 'timestamp', direction: 'DESC' })\n .describe('Ordering configuration (defaults to timestamp desc)'),\n })\n .describe('Arguments for listing logs');\n\n/** Arguments for listing logs */\nexport type ListLogsArgs = z.input<typeof listLogsArgsSchema>;\n\n/** Schema for listLogs operation response */\nexport const listLogsResponseSchema = z.object({\n pagination: paginationInfoSchema,\n logs: z.array(logRecordSchema),\n});\n\n/** Response containing paginated logs */\nexport type ListLogsResponse = z.infer<typeof listLogsResponseSchema>;\n","import { z } from 'zod/v4';\nimport {\n commonFilterFields,\n experimentIdField,\n paginationArgsSchema,\n paginationInfoSchema,\n sortDirectionSchema,\n spanIdField,\n traceIdField,\n} from '../shared';\n\n// ============================================================================\n// Field Schemas\n// ============================================================================\n\nconst scorerIdField = z.string().describe('Identifier of the scorer (e.g., relevance, accuracy)');\nconst scorerVersionField = z.string().describe('Version of the scorer');\nconst sourceField = z.string().describe('Source of the score (e.g., manual, automated, experiment)');\nconst scoreValueField = z.number().describe('Score value (range defined by scorer)');\nconst scoreReasonField = z.string().describe('Explanation for the score');\n\n// ============================================================================\n// ScoreRecord Schema (Storage Format)\n// ============================================================================\n\n/**\n * Schema for scores as stored in the database.\n * Includes all fields from ExportedScore plus storage-specific fields.\n */\nexport const scoreRecordSchema = z\n .object({\n timestamp: z.date().describe('When the score was recorded'),\n\n // Target\n traceId: traceIdField,\n spanId: spanIdField.nullish().describe('Span ID this score applies to'),\n\n // Score data\n scorerId: scorerIdField,\n scorerVersion: scorerVersionField.nullish(),\n source: sourceField.nullish(),\n score: scoreValueField,\n reason: scoreReasonField.nullish(),\n experimentId: experimentIdField.nullish(),\n\n /** Trace ID of the scoring run (links to trace that generated this score) */\n scoreTraceId: z.string().nullish().describe('Trace ID of the scoring run for debugging score generation'),\n\n // User-defined metadata (context fields stored here)\n metadata: z.record(z.string(), z.unknown()).nullish().describe('User-defined metadata'),\n })\n .describe('Score record as stored in the database');\n\n/** Score record type for storage */\nexport type ScoreRecord = z.infer<typeof scoreRecordSchema>;\n\n// ============================================================================\n// ScoreInput Schema (User-Facing API)\n// ============================================================================\n\n/**\n * Schema for user-provided score input (minimal required fields).\n * The span/trace context adds traceId/spanId before emitting ExportedScore.\n */\nexport const scoreInputSchema = z\n .object({\n scorerId: scorerIdField,\n scorerVersion: scorerVersionField.optional(),\n source: sourceField.optional(),\n score: scoreValueField,\n reason: scoreReasonField.optional(),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional scorer-specific metadata'),\n experimentId: experimentIdField.optional(),\n scoreTraceId: z.string().optional().describe('Trace ID of the scoring run for debugging score generation'),\n })\n .describe('User-provided score input');\n\n/** User-facing score input type */\nexport type ScoreInput = z.infer<typeof scoreInputSchema>;\n\n// ============================================================================\n// Create Score Schemas\n// ============================================================================\n\n/** Schema for creating a score record */\nexport const createScoreRecordSchema = scoreRecordSchema;\n\n/** Score record for creation */\nexport type CreateScoreRecord = z.infer<typeof createScoreRecordSchema>;\n\n/** Schema for createScore operation arguments */\nexport const createScoreArgsSchema = z\n .object({\n score: createScoreRecordSchema,\n })\n .describe('Arguments for creating a score');\n\n/** Arguments for creating a score */\nexport type CreateScoreArgs = z.infer<typeof createScoreArgsSchema>;\n\n/** Schema for createScore operation body in client/server */\nexport const createScoreBodySchema = z\n .object({\n score: createScoreRecordSchema.omit({ timestamp: true }),\n })\n .describe('Arguments for creating a score');\n\n/** Body for creating a score in client/server */\nexport type CreateScoreBody = z.infer<typeof createScoreBodySchema>;\n\n/** Schema for createScore operation response */\nexport const createScoreResponseSchema = z.object({ success: z.boolean() }).describe('Response from creating a score');\n\n/** Response from creating a score */\nexport type CreateScoreResponse = z.infer<typeof createScoreResponseSchema>;\n\n/** Schema for batchCreateScores operation arguments */\nexport const batchCreateScoresArgsSchema = z\n .object({\n scores: z.array(createScoreRecordSchema),\n })\n .describe('Arguments for batch recording scores');\n\n/** Arguments for batch creating scores */\nexport type BatchCreateScoresArgs = z.infer<typeof batchCreateScoresArgsSchema>;\n\n// ============================================================================\n// Score Filter Schema\n// ============================================================================\n\n/** Schema for filtering scores in list queries */\nexport const scoresFilterSchema = z\n .object({\n ...commonFilterFields,\n\n // Score-specific filters\n scorerId: z\n .union([z.string(), z.array(z.string())])\n .optional()\n .describe('Filter by scorer ID(s)'),\n })\n .describe('Filters for querying scores');\n\n/** Filters for querying scores */\nexport type ScoresFilter = z.infer<typeof scoresFilterSchema>;\n\n// ============================================================================\n// List Scores Schemas\n// ============================================================================\n\n/** Fields available for ordering score results */\nexport const scoresOrderByFieldSchema = z\n .enum(['timestamp', 'score'])\n .describe(\"Field to order by: 'timestamp' | 'score'\");\n\n/** Order by configuration for score queries */\nexport const scoresOrderBySchema = z\n .object({\n field: scoresOrderByFieldSchema.default('timestamp').describe('Field to order by'),\n direction: sortDirectionSchema.default('DESC').describe('Sort direction'),\n })\n .describe('Order by configuration');\n\n/** Schema for listScores operation arguments */\nexport const listScoresArgsSchema = z\n .object({\n filters: scoresFilterSchema.optional().describe('Optional filters to apply'),\n pagination: paginationArgsSchema.default({ page: 0, perPage: 10 }).describe('Pagination settings'),\n orderBy: scoresOrderBySchema\n .default({ field: 'timestamp', direction: 'DESC' })\n .describe('Ordering configuration (defaults to timestamp desc)'),\n })\n .describe('Arguments for listing scores');\n\n/** Arguments for listing scores */\nexport type ListScoresArgs = z.input<typeof listScoresArgsSchema>;\n\n/** Schema for listScores operation response */\nexport const listScoresResponseSchema = z.object({\n pagination: paginationInfoSchema,\n scores: z.array(scoreRecordSchema),\n});\n\n/** Response containing paginated scores */\nexport type ListScoresResponse = z.infer<typeof listScoresResponseSchema>;\n","import { z } from 'zod/v4';\nimport {\n commonFilterFields,\n experimentIdField,\n paginationArgsSchema,\n paginationInfoSchema,\n sortDirectionSchema,\n spanIdField,\n traceIdField,\n userIdField,\n} from '../shared';\n\n// ============================================================================\n// Field Schemas\n// ============================================================================\n\nconst feedbackSourceField = z.string().describe(\"Source of feedback (e.g., 'user', 'system', 'manual')\");\nconst feedbackTypeField = z.string().describe(\"Type of feedback (e.g., 'thumbs', 'rating', 'correction')\");\nconst feedbackValueField = z\n .union([z.number(), z.string()])\n .describe('Feedback value (rating number or correction text)');\nconst feedbackCommentField = z.string().describe('Additional comment or context');\n\n// ============================================================================\n// FeedbackRecord Schema (Storage Format)\n// ============================================================================\n\n/**\n * Schema for feedback as stored in the database.\n * Includes all fields from ExportedFeedback plus storage-specific fields.\n */\nexport const feedbackRecordSchema = z\n .object({\n timestamp: z.date().describe('When the feedback was recorded'),\n\n // Target\n traceId: traceIdField,\n spanId: spanIdField.nullish().describe('Span ID this feedback applies to'),\n\n // Feedback data\n source: feedbackSourceField,\n feedbackType: feedbackTypeField,\n value: feedbackValueField,\n comment: feedbackCommentField.nullish(),\n experimentId: experimentIdField.nullish(),\n\n // Identity\n userId: userIdField.nullish(),\n\n // Source linkage (e.g. dataset item result ID)\n sourceId: z\n .string()\n .nullish()\n .describe('ID of the source record this feedback is linked to (e.g. experiment result ID)'),\n\n // User-defined metadata (context fields stored here)\n metadata: z.record(z.string(), z.unknown()).nullish().describe('User-defined metadata'),\n })\n .describe('Feedback record as stored in the database');\n\n/** Feedback record type for storage */\nexport type FeedbackRecord = z.infer<typeof feedbackRecordSchema>;\n\n// ============================================================================\n// FeedbackInput Schema (User-Facing API)\n// ============================================================================\n\n/**\n * Schema for user-provided feedback input (minimal required fields).\n * The span/trace context adds traceId/spanId before emitting ExportedFeedback.\n */\nexport const feedbackInputSchema = z\n .object({\n source: feedbackSourceField,\n feedbackType: feedbackTypeField,\n value: feedbackValueField,\n comment: feedbackCommentField.optional(),\n userId: userIdField.optional(),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional feedback-specific metadata'),\n experimentId: experimentIdField.optional(),\n sourceId: z.string().optional().describe('ID of the source record this feedback is linked to'),\n })\n .describe('User-provided feedback input');\n\n/** User-facing feedback input type */\nexport type FeedbackInput = z.infer<typeof feedbackInputSchema>;\n\n// ============================================================================\n// Create Feedback Schemas\n// ============================================================================\n\n/** Schema for creating a feedback record */\nexport const createFeedbackRecordSchema = feedbackRecordSchema;\n\n/** Feedback record for creation */\nexport type CreateFeedbackRecord = z.infer<typeof createFeedbackRecordSchema>;\n\n/** Schema for createFeedback operation arguments */\nexport const createFeedbackArgsSchema = z\n .object({\n feedback: createFeedbackRecordSchema,\n })\n .describe('Arguments for creating feedback');\n\n/** Arguments for creating feedback */\nexport type CreateFeedbackArgs = z.infer<typeof createFeedbackArgsSchema>;\n\n/** Schema for createFeedback operation body in client/server */\nexport const createFeedbackBodySchema = z\n .object({\n feedback: createFeedbackRecordSchema.omit({ timestamp: true }),\n })\n .describe('Arguments for creating feedback');\n\n/** Body for creating feedback in client/server */\nexport type CreateFeedbackBody = z.infer<typeof createFeedbackBodySchema>;\n\n/** Schema for createFeedback operation response */\nexport const createFeedbackResponseSchema = z\n .object({ success: z.boolean() })\n .describe('Response from creating feedback');\n\n/** Response from creating feedback */\nexport type CreateFeedbackResponse = z.infer<typeof createFeedbackResponseSchema>;\n\n/** Schema for batchCreateFeedback operation arguments */\nexport const batchCreateFeedbackArgsSchema = z\n .object({\n feedbacks: z.array(createFeedbackRecordSchema),\n })\n .describe('Arguments for batch recording feedback');\n\n/** Arguments for batch creating feedback */\nexport type BatchCreateFeedbackArgs = z.infer<typeof batchCreateFeedbackArgsSchema>;\n\n// ============================================================================\n// Feedback Filter Schema\n// ============================================================================\n\n/** Schema for filtering feedback in list queries */\nexport const feedbackFilterSchema = z\n .object({\n ...commonFilterFields,\n\n // Feedback-specific filters\n feedbackType: z\n .union([z.string(), z.array(z.string())])\n .optional()\n .describe('Filter by feedback type(s)'),\n source: z.string().optional().describe('Filter by feedback source (e.g., user, system, manual)'),\n })\n .describe('Filters for querying feedback');\n\n/** Filters for querying feedback */\nexport type FeedbackFilter = z.infer<typeof feedbackFilterSchema>;\n\n// ============================================================================\n// List Feedback Schemas\n// ============================================================================\n\n/** Fields available for ordering feedback results */\nexport const feedbackOrderByFieldSchema = z.enum(['timestamp']).describe(\"Field to order by: 'timestamp'\");\n\n/** Order by configuration for feedback queries */\nexport const feedbackOrderBySchema = z\n .object({\n field: feedbackOrderByFieldSchema.default('timestamp').describe('Field to order by'),\n direction: sortDirectionSchema.default('DESC').describe('Sort direction'),\n })\n .describe('Order by configuration');\n\n/** Schema for listFeedback operation arguments */\nexport const listFeedbackArgsSchema = z\n .object({\n filters: feedbackFilterSchema.optional().describe('Optional filters to apply'),\n pagination: paginationArgsSchema.default({ page: 0, perPage: 10 }).describe('Pagination settings'),\n orderBy: feedbackOrderBySchema\n .default({ field: 'timestamp', direction: 'DESC' })\n .describe('Ordering configuration (defaults to timestamp desc)'),\n })\n .describe('Arguments for listing feedback');\n\n/** Arguments for listing feedback */\nexport type ListFeedbackArgs = z.input<typeof listFeedbackArgsSchema>;\n\n/** Schema for listFeedback operation response */\nexport const listFeedbackResponseSchema = z.object({\n pagination: paginationInfoSchema,\n feedback: z.array(feedbackRecordSchema),\n});\n\n/** Response containing paginated feedback */\nexport type ListFeedbackResponse = z.infer<typeof listFeedbackResponseSchema>;\n","import { z } from 'zod/v4';\nimport {\n commonFilterFields,\n contextFields,\n observabilitySignalFilterFields,\n tagsField,\n paginationArgsSchema,\n paginationInfoSchema,\n sortDirectionSchema,\n spanIdField,\n traceIdField,\n metadataField,\n} from '../shared';\n\n// ============================================================================\n// Field Schemas\n// ============================================================================\n\n/**\n * @deprecated MetricType is no longer stored. All metrics are raw events\n * with aggregation determined at query time.\n */\nexport const metricTypeSchema = z.enum(['counter', 'gauge', 'histogram']);\n\nconst metricNameField = z.string().describe('Metric name (e.g., mastra_agent_duration_ms)');\nconst metricValueField = z.number().describe('Metric value');\nconst labelsField = z.record(z.string(), z.string()).describe('Metric labels for dimensional filtering');\nconst providerField = z.string().describe('Model provider');\nconst modelField = z.string().describe('Model');\nconst estimatedCostField = z.number().describe('Estimated cost');\nconst costUnitField = z.string().describe('Unit for the estimated cost (e.g., usd)');\nconst costMetadField = z.record(z.string(), z.unknown()).nullish().describe('Structured costing metadata');\n\n// ============================================================================\n// MetricRecord Schema (Storage Format)\n// ============================================================================\n\n/**\n * Schema for metrics as stored in the database.\n * Each record is a single metric observation.\n */\nexport const metricRecordSchema = z\n .object({\n timestamp: z.date().describe('When the metric was recorded'),\n name: metricNameField,\n value: metricValueField,\n\n // Correlation\n traceId: traceIdField.nullish(),\n spanId: spanIdField.nullish(),\n\n // Context (entity hierarchy, identity, correlation, deployment, experimentation)\n ...contextFields,\n\n // Canonical costing fields\n provider: providerField.nullish(),\n model: modelField.nullish(),\n\n // Estimated cost related fields\n estimatedCost: estimatedCostField.nullish(),\n costUnit: costUnitField.nullish(),\n costMetadata: costMetadField.nullish(),\n\n // Filtering\n tags: tagsField.nullish(),\n\n // User-defined labels used for filtering\n labels: labelsField.default({}),\n\n // User-defined metadata\n metadata: metadataField.nullish(),\n })\n .describe('Metric record as stored in the database');\n\n/** Metric record type for storage */\nexport type MetricRecord = z.infer<typeof metricRecordSchema>;\n\n// ============================================================================\n// MetricInput Schema (User-Facing API)\n// ============================================================================\n\n/**\n * Schema for user-provided metric input (minimal required fields).\n * The metrics context enriches this with environment before emitting ExportedMetric.\n */\nexport const metricInputSchema = z\n .object({\n name: metricNameField,\n value: metricValueField,\n labels: labelsField.optional(),\n })\n .describe('User-provided metric input');\n\n/** User-facing metric input type */\nexport type MetricInput = z.infer<typeof metricInputSchema>;\n\n// ============================================================================\n// Create Metric Schemas\n// ============================================================================\n\n/** Schema for creating a metric record (without db timestamps) */\nexport const createMetricRecordSchema = metricRecordSchema;\n\n/** Metric record for creation (excludes db timestamps) */\nexport type CreateMetricRecord = z.infer<typeof createMetricRecordSchema>;\n\n/** Schema for batchCreateMetrics operation arguments */\nexport const batchCreateMetricsArgsSchema = z\n .object({\n metrics: z.array(createMetricRecordSchema),\n })\n .describe('Arguments for batch recording metrics');\n\n/** Arguments for batch recording metrics */\nexport type BatchCreateMetricsArgs = z.infer<typeof batchCreateMetricsArgsSchema>;\n\n// ============================================================================\n// Metric Aggregation Schemas\n// ============================================================================\n\n/** Aggregation type schema */\nexport const aggregationTypeSchema = z.enum(['sum', 'avg', 'min', 'max', 'count', 'last']);\nexport type AggregationType = z.infer<typeof aggregationTypeSchema>;\n\n/** Aggregation interval schema */\nexport const aggregationIntervalSchema = z.enum(['1m', '5m', '15m', '1h', '1d']);\nexport type AggregationInterval = z.infer<typeof aggregationIntervalSchema>;\n\n/** Schema for metric aggregation configuration */\nexport const metricsAggregationSchema = z\n .object({\n type: aggregationTypeSchema.describe('Aggregation function'),\n interval: aggregationIntervalSchema.optional().describe('Time bucket interval'),\n groupBy: z.array(z.string()).optional().describe('Label keys to group by'),\n })\n .describe('Metrics aggregation configuration');\n\n/** Metrics aggregation configuration type */\nexport type MetricsAggregation = z.infer<typeof metricsAggregationSchema>;\n\n// ============================================================================\n// Metric Filter Schema\n// ============================================================================\n\n/** Schema for filtering metrics in queries */\nexport const metricsFilterSchema = z\n .object({\n ...commonFilterFields,\n ...observabilitySignalFilterFields,\n\n // Metric identification\n name: z.array(z.string()).nonempty().optional().describe('Filter by metric name(s)'),\n\n // Canonical costing filters\n provider: providerField.optional(),\n model: modelField.optional(),\n costUnit: costUnitField.optional(),\n\n // Label filters (exact match on label values)\n labels: z.record(z.string(), z.string()).optional().describe('Exact match on label key-value pairs'),\n })\n .describe('Filters for querying metrics');\n\n/** Filters for querying metrics */\nexport type MetricsFilter = z.infer<typeof metricsFilterSchema>;\n\n/** Fields available for ordering metric list results */\nexport const metricsOrderByFieldSchema = z.enum(['timestamp']).describe(\"Field to order by: 'timestamp'\");\n\n/** Order by configuration for metric list queries */\nexport const metricsOrderBySchema = z\n .object({\n field: metricsOrderByFieldSchema.default('timestamp').describe('Field to order by'),\n direction: sortDirectionSchema.default('DESC').describe('Sort direction'),\n })\n .describe('Order by configuration');\n\n/** Schema for listMetrics operation arguments */\nexport const listMetricsArgsSchema = z\n .object({\n filters: metricsFilterSchema.optional().describe('Optional filters to apply'),\n pagination: paginationArgsSchema.default({ page: 0, perPage: 10 }).describe('Pagination settings'),\n orderBy: metricsOrderBySchema\n .default({ field: 'timestamp', direction: 'DESC' })\n .describe('Ordering configuration (defaults to timestamp desc)'),\n })\n .describe('Arguments for listing metrics');\n\n/** Arguments for listing metrics */\nexport type ListMetricsArgs = z.input<typeof listMetricsArgsSchema>;\n\n/** Schema for listMetrics operation response */\nexport const listMetricsResponseSchema = z.object({\n pagination: paginationInfoSchema,\n metrics: z.array(metricRecordSchema),\n});\n\n/** Response containing paginated metrics */\nexport type ListMetricsResponse = z.infer<typeof listMetricsResponseSchema>;\n\n// ============================================================================\n// OLAP Query Schemas\n// ============================================================================\n\n/** Compare period for aggregate queries with period-over-period comparison */\nexport const comparePeriodSchema = z\n .enum(['previous_period', 'previous_day', 'previous_week'])\n .describe('Comparison period for aggregate queries');\n\n// --- getMetricAggregate ---\n\nexport const getMetricAggregateArgsSchema = z\n .object({\n name: z.array(z.string()).nonempty().describe('Metric name(s) to aggregate'),\n aggregation: aggregationTypeSchema.describe('Aggregation function'),\n filters: metricsFilterSchema.optional().describe('Optional filters'),\n comparePeriod: comparePeriodSchema.optional().describe('Optional comparison period'),\n })\n .describe('Arguments for getting a metric aggregate');\n\nexport type GetMetricAggregateArgs = z.infer<typeof getMetricAggregateArgsSchema>;\n\nexport const getMetricAggregateResponseSchema = z.object({\n value: z.number().nullable().describe('Aggregated value'),\n estimatedCost: z.number().nullable().optional().describe('Aggregated estimated cost from the same filtered row set'),\n costUnit: z\n .string()\n .nullable()\n .optional()\n .describe('Shared cost unit for the aggregated rows, or null when mixed/unknown'),\n previousValue: z.number().nullable().optional().describe('Value from comparison period'),\n previousEstimatedCost: z\n .number()\n .nullable()\n .optional()\n .describe('Aggregated estimated cost from the comparison period'),\n changePercent: z.number().nullable().optional().describe('Percentage change from comparison period'),\n costChangePercent: z\n .number()\n .nullable()\n .optional()\n .describe('Percentage change in estimated cost from comparison period'),\n});\n\nexport type GetMetricAggregateResponse = z.infer<typeof getMetricAggregateResponseSchema>;\n\n// --- getMetricBreakdown ---\n\nexport const getMetricBreakdownArgsSchema = z\n .object({\n name: z.array(z.string()).nonempty().describe('Metric name(s) to break down'),\n groupBy: z.array(z.string()).min(1).describe('Fields to group by'),\n aggregation: aggregationTypeSchema.describe('Aggregation function'),\n filters: metricsFilterSchema.optional().describe('Optional filters'),\n })\n .describe('Arguments for getting a metric breakdown');\n\nexport type GetMetricBreakdownArgs = z.infer<typeof getMetricBreakdownArgsSchema>;\n\nexport const getMetricBreakdownResponseSchema = z.object({\n groups: z.array(\n z.object({\n dimensions: z.record(z.string(), z.string().nullable()).describe('Dimension values for this group'),\n value: z.number().describe('Aggregated value for this group'),\n estimatedCost: z.number().nullable().optional().describe('Summed estimated cost for this group'),\n costUnit: z\n .string()\n .nullable()\n .optional()\n .describe('Shared cost unit for this group, or null when mixed/unknown'),\n }),\n ),\n});\n\nexport type GetMetricBreakdownResponse = z.infer<typeof getMetricBreakdownResponseSchema>;\n\n// --- getMetricTimeSeries ---\n\nexport const getMetricTimeSeriesArgsSchema = z\n .object({\n name: z.array(z.string()).nonempty().describe('Metric name(s)'),\n interval: aggregationIntervalSchema.describe('Time bucket interval'),\n aggregation: aggregationTypeSchema.describe('Aggregation function'),\n filters: metricsFilterSchema.optional().describe('Optional filters'),\n groupBy: z.array(z.string()).optional().describe('Optional fields to group by'),\n })\n .describe('Arguments for getting metric time series');\n\nexport type GetMetricTimeSeriesArgs = z.infer<typeof getMetricTimeSeriesArgsSchema>;\n\nexport const getMetricTimeSeriesResponseSchema = z.object({\n series: z.array(\n z.object({\n name: z.string().describe('Series name (metric name or group key)'),\n costUnit: z\n .string()\n .nullable()\n .optional()\n .describe('Shared cost unit for this series, or null when mixed/unknown'),\n points: z.array(\n z.object({\n timestamp: z.date().describe('Bucket timestamp'),\n value: z.number().describe('Aggregated value'),\n estimatedCost: z.number().nullable().optional().describe('Summed estimated cost in this bucket'),\n }),\n ),\n }),\n ),\n});\n\nexport type GetMetricTimeSeriesResponse = z.infer<typeof getMetricTimeSeriesResponseSchema>;\n\n// --- getMetricPercentiles ---\n\nexport const getMetricPercentilesArgsSchema = z\n .object({\n name: z.string().describe('Metric name'),\n percentiles: z.array(z.number().min(0).max(1)).describe('Percentile values (0-1)'),\n interval: aggregationIntervalSchema.describe('Time bucket interval'),\n filters: metricsFilterSchema.optional().describe('Optional filters'),\n })\n .describe('Arguments for getting metric percentiles');\n\nexport type GetMetricPercentilesArgs = z.infer<typeof getMetricPercentilesArgsSchema>;\n\nexport const getMetricPercentilesResponseSchema = z.object({\n series: z.array(\n z.object({\n percentile: z.number().describe('Percentile value'),\n points: z.array(\n z.object({\n timestamp: z.date().describe('Bucket timestamp'),\n value: z.number().describe('Percentile value at this bucket'),\n }),\n ),\n }),\n ),\n});\n\nexport type GetMetricPercentilesResponse = z.infer<typeof getMetricPercentilesResponseSchema>;\n","import { z } from 'zod/v4';\nimport { entityTypeField } from '../shared';\n\n// ============================================================================\n// Metric Discovery\n// ============================================================================\n\n// --- getMetricNames ---\n\nexport const getMetricNamesArgsSchema = z\n .object({\n prefix: z.string().optional().describe('Filter metric names by prefix'),\n limit: z.number().int().min(1).optional().describe('Maximum number of names to return'),\n })\n .describe('Arguments for getting metric names');\n\nexport type GetMetricNamesArgs = z.infer<typeof getMetricNamesArgsSchema>;\n\nexport const getMetricNamesResponseSchema = z.object({\n names: z.array(z.string()).describe('Distinct metric names'),\n});\n\nexport type GetMetricNamesResponse = z.infer<typeof getMetricNamesResponseSchema>;\n\n// --- getMetricLabelKeys ---\n\nexport const getMetricLabelKeysArgsSchema = z\n .object({\n metricName: z.string().describe('Metric name to get label keys for'),\n })\n .describe('Arguments for getting metric label keys');\n\nexport type GetMetricLabelKeysArgs = z.infer<typeof getMetricLabelKeysArgsSchema>;\n\nexport const getMetricLabelKeysResponseSchema = z.object({\n keys: z.array(z.string()).describe('Distinct label keys for the metric'),\n});\n\nexport type GetMetricLabelKeysResponse = z.infer<typeof getMetricLabelKeysResponseSchema>;\n\n// --- getMetricLabelValues ---\n\nexport const getMetricLabelValuesArgsSchema = z\n .object({\n metricName: z.string().describe('Metric name'),\n labelKey: z.string().describe('Label key to get values for'),\n prefix: z.string().optional().describe('Filter values by prefix'),\n limit: z.number().int().min(1).optional().describe('Maximum number of values to return'),\n })\n .describe('Arguments for getting label values');\n\nexport type GetMetricLabelValuesArgs = z.infer<typeof getMetricLabelValuesArgsSchema>;\n\nexport const getMetricLabelValuesResponseSchema = z.object({\n values: z.array(z.string()).describe('Distinct label values'),\n});\n\nexport type GetMetricLabelValuesResponse = z.infer<typeof getMetricLabelValuesResponseSchema>;\n\n// ============================================================================\n// Entity & Environment Discovery\n// ============================================================================\n\n// --- getEntityTypes ---\n\nexport const getEntityTypesArgsSchema = z.object({}).describe('Arguments for getting entity types');\n\nexport type GetEntityTypesArgs = z.infer<typeof getEntityTypesArgsSchema>;\n\nexport const getEntityTypesResponseSchema = z.object({\n entityTypes: z.array(entityTypeField).describe('Distinct entity types'),\n});\n\nexport type GetEntityTypesResponse = z.infer<typeof getEntityTypesResponseSchema>;\n\n// --- getEntityNames ---\n\nexport const getEntityNamesArgsSchema = z\n .object({\n entityType: entityTypeField.optional().describe('Optional entity type filter'),\n })\n .describe('Arguments for getting entity names');\n\nexport type GetEntityNamesArgs = z.infer<typeof getEntityNamesArgsSchema>;\n\nexport const getEntityNamesResponseSchema = z.object({\n names: z.array(z.string()).describe('Distinct entity names'),\n});\n\nexport type GetEntityNamesResponse = z.infer<typeof getEntityNamesResponseSchema>;\n\n// --- getServiceNames ---\n\nexport const getServiceNamesArgsSchema = z.object({}).describe('Arguments for getting service names');\n\nexport type GetServiceNamesArgs = z.infer<typeof getServiceNamesArgsSchema>;\n\nexport const getServiceNamesResponseSchema = z.object({\n serviceNames: z.array(z.string()).describe('Distinct service names'),\n});\n\nexport type GetServiceNamesResponse = z.infer<typeof getServiceNamesResponseSchema>;\n\n// --- getEnvironments ---\n\nexport const getEnvironmentsArgsSchema = z.object({}).describe('Arguments for getting environments');\n\nexport type GetEnvironmentsArgs = z.infer<typeof getEnvironmentsArgsSchema>;\n\nexport const getEnvironmentsResponseSchema = z.object({\n environments: z.array(z.string()).describe('Distinct environments'),\n});\n\nexport type GetEnvironmentsResponse = z.infer<typeof getEnvironmentsResponseSchema>;\n\n// --- getTags ---\n\nexport const getTagsArgsSchema = z\n .object({\n entityType: entityTypeField.optional().describe('Optional entity type filter'),\n })\n .describe('Arguments for getting tags');\n\nexport type GetTagsArgs = z.infer<typeof getTagsArgsSchema>;\n\nexport const getTagsResponseSchema = z.object({\n tags: z.array(z.string()).describe('Distinct tags'),\n});\n\nexport type GetTagsResponse = z.infer<typeof getTagsResponseSchema>;\n","/**\n * Tracing interfaces\n *\n * Span types, attributes, span lifecycle, and tracing-specific types.\n * For top-level observability infrastructure (instances, exporters, bridges, config),\n * see observability.ts.\n */\nimport { EntityType } from '@internal/core/storage';\n\nimport type { MastraError } from '../../error';\nimport type { Mastra } from '../../mastra';\nimport type { RequestContext } from '../../request-context';\nimport type { LanguageModelUsage, ProviderMetadata, StepStartPayload } from '../../stream/types';\nimport type { WorkflowRunStatus, WorkflowStepStatus } from '../../workflows';\nimport type { CustomSamplerOptions, ObservabilityInstance, CorrelationContext } from './core';\nimport type { FeedbackInput } from './feedback';\nimport type { ScoreInput } from './scores';\n\n// ============================================================================\n// Span Types\n// ============================================================================\n\n/**\n * AI-specific span types with their associated metadata\n */\nexport enum SpanType {\n /** Agent run - root span for agent processes */\n AGENT_RUN = 'agent_run',\n /** Generic span for custom operations */\n GENERIC = 'generic',\n /** Model generation with model calls, token usage, prompts, completions */\n MODEL_GENERATION = 'model_generation',\n /** Single model execution step within a generation (one API call) */\n MODEL_STEP = 'model_step',\n /** Individual model streaming chunk/event */\n MODEL_CHUNK = 'model_chunk',\n /** MCP (Model Context Protocol) tool execution */\n MCP_TOOL_CALL = 'mcp_tool_call',\n /** Input or Output Processor execution */\n PROCESSOR_RUN = 'processor_run',\n /** Function/tool execution with inputs, outputs, errors */\n TOOL_CALL = 'tool_call',\n /** Workflow run - root span for workflow processes */\n WORKFLOW_RUN = 'workflow_run',\n /** Workflow step execution with step status, data flow */\n WORKFLOW_STEP = 'workflow_step',\n /** Workflow conditional execution with condition evaluation */\n WORKFLOW_CONDITIONAL = 'workflow_conditional',\n /** Individual condition evaluation within conditional */\n WORKFLOW_CONDITIONAL_EVAL = 'workflow_conditional_eval',\n /** Workflow parallel execution */\n WORKFLOW_PARALLEL = 'workflow_parallel',\n /** Workflow loop execution */\n WORKFLOW_LOOP = 'workflow_loop',\n /** Workflow sleep operation */\n WORKFLOW_SLEEP = 'workflow_sleep',\n /** Workflow wait for event operation */\n WORKFLOW_WAIT_EVENT = 'workflow_wait_event',\n}\n\nexport { EntityType };\n\n// ============================================================================\n// Type-Specific Attributes Interfaces\n// ============================================================================\n\n/**\n * Base attributes that all spans can have\n */\nexport interface AIBaseAttributes {}\n\n/**\n * Agent Run attributes\n */\nexport interface AgentRunAttributes extends AIBaseAttributes {\n /** Conversation/thread/session identifier for multi-turn interactions */\n conversationId?: string;\n /** Agent Instructions **/\n instructions?: string;\n /** Agent Prompt **/\n prompt?: string;\n /** Available tools for this execution */\n availableTools?: string[];\n /** Maximum steps allowed */\n maxSteps?: number;\n /** Tripwire abort details when a processor triggered a tripwire */\n tripwireAbort?: {\n /** Abort reason */\n reason?: string;\n /** Processor that triggered the tripwire */\n processorId?: string;\n /** Whether retry was requested */\n retry?: boolean;\n /** Additional metadata */\n metadata?: unknown;\n };\n}\n\n/**\n * Detailed breakdown of input token usage by type.\n * Based on OpenInference semantic conventions.\n */\nexport interface InputTokenDetails {\n /** Regular text tokens (non-cached, non-audio, non-image) */\n text?: number;\n /** Tokens served from cache (cache hit/read) */\n cacheRead?: number;\n /** Tokens written to cache (cache creation - Anthropic only) */\n cacheWrite?: number;\n /** Audio input tokens */\n audio?: number;\n /** Image input tokens (includes PDF pages) */\n image?: number;\n}\n\n/**\n * Detailed breakdown of output token usage by type.\n * Based on OpenInference semantic conventions.\n */\nexport interface OutputTokenDetails {\n /** Regular text output tokens */\n text?: number;\n /** Reasoning/thinking tokens (o1, Claude thinking, Gemini thoughts) */\n reasoning?: number;\n /** Audio output tokens */\n audio?: number;\n /** Image output tokens (DALL-E, etc.) */\n image?: number;\n}\n\n/** Token usage statistics */\nexport interface UsageStats {\n /** Total input tokens (sum of all input details) */\n inputTokens?: number;\n /** Total output tokens (sum of all output details) */\n outputTokens?: number;\n /** Detailed breakdown of input token usage */\n inputDetails?: InputTokenDetails;\n /** Detailed breakdown of output token usage */\n outputDetails?: OutputTokenDetails;\n}\n\n/**\n * Model Generation attributes\n */\nexport interface ModelGenerationAttributes extends AIBaseAttributes {\n /** Model name (e.g., 'gpt-4', 'claude-3') */\n model?: string;\n /** Model provider (e.g., 'openai', 'anthropic') */\n provider?: string;\n /** Type of result/output this LLM call produced */\n resultType?: 'tool_selection' | 'response_generation' | 'reasoning' | 'planning';\n /** Token usage statistics */\n usage?: UsageStats;\n /** Model parameters */\n parameters?: {\n maxOutputTokens?: number;\n temperature?: number;\n topP?: number;\n topK?: number;\n presencePenalty?: number;\n frequencyPenalty?: number;\n stopSequences?: string[];\n seed?: number;\n maxRetries?: number;\n abortSignal?: any;\n headers?: Record<string, string | undefined>;\n };\n /** Whether this was a streaming response */\n streaming?: boolean;\n /** Reason the generation finished */\n finishReason?: string;\n /**\n * When the first token/chunk of the completion was received.\n * Used to calculate time-to-first-token (TTFT) metrics.\n * Only applicable for streaming responses.\n */\n completionStartTime?: Date;\n /** Actual model used in the response (may differ from request model) */\n responseModel?: string;\n /** Unique identifier for the response */\n responseId?: string;\n /** Server address for the model endpoint */\n serverAddress?: string;\n /** Server port for the model endpoint */\n serverPort?: number;\n}\n\n/**\n * Model Step attributes - for a single model execution within a generation\n */\nexport interface ModelStepAttributes extends AIBaseAttributes {\n /** Index of this step in the generation (0, 1, 2, ...) */\n stepIndex?: number;\n /** Token usage statistics */\n usage?: UsageStats;\n /** Reason this step finished (stop, tool-calls, length, etc.) */\n finishReason?: string;\n /** Should execution continue */\n isContinued?: boolean;\n /** Result warnings */\n warnings?: Record<string, any>;\n}\n\n/**\n * Model Chunk attributes - for individual streaming chunks/events\n */\nexport interface ModelChunkAttributes extends AIBaseAttributes {\n /** Type of chunk (text-delta, reasoning-delta, tool-call, etc.) */\n chunkType?: string;\n /** Sequence number of this chunk in the stream */\n sequenceNumber?: number;\n}\n\n/**\n * Tool Call attributes\n */\nexport interface ToolCallAttributes extends AIBaseAttributes {\n toolType?: string;\n toolDescription?: string;\n success?: boolean;\n}\n\n/**\n * MCP Tool Call attributes\n */\nexport interface MCPToolCallAttributes extends AIBaseAttributes {\n /** MCP server identifier */\n mcpServer: string;\n /** MCP server version */\n serverVersion?: string;\n /** Tool description */\n toolDescription?: string;\n /** Whether tool execution was successful */\n success?: boolean;\n}\n\n/**\n * Processor attributes\n */\nexport interface ProcessorRunAttributes extends AIBaseAttributes {\n /** Processor executor type (workflow or legacy) */\n processorExecutor?: 'workflow' | 'legacy';\n /** Processor index in the agent */\n processorIndex?: number;\n /** MessageList mutations performed by this processor */\n messageListMutations?: Array<{\n type: 'add' | 'addSystem' | 'removeByIds' | 'clear';\n source?: string;\n count?: number;\n ids?: string[];\n text?: string;\n tag?: string;\n message?: any;\n }>;\n /** Tripwire abort details when a processor triggered a tripwire */\n tripwireAbort?: {\n /** Abort reason */\n reason?: string;\n /** Whether retry was requested */\n retry?: boolean;\n /** Additional metadata */\n metadata?: unknown;\n };\n}\n\n/**\n * Workflow Run attributes\n */\nexport interface WorkflowRunAttributes extends AIBaseAttributes {\n /** Workflow status */\n status?: WorkflowRunStatus;\n}\n\n/**\n * Workflow Step attributes\n */\nexport interface WorkflowStepAttributes extends AIBaseAttributes {\n /** Step status */\n status?: WorkflowStepStatus;\n}\n\n/**\n * Workflow Conditional attributes\n */\nexport interface WorkflowConditionalAttributes extends AIBaseAttributes {\n /** Number of conditions evaluated */\n conditionCount: number;\n /** Which condition indexes evaluated to true */\n truthyIndexes?: number[];\n /** Which steps will be executed */\n selectedSteps?: string[];\n}\n\n/**\n * Workflow Conditional Evaluation attributes\n */\nexport interface WorkflowConditionalEvalAttributes extends AIBaseAttributes {\n /** Index of this condition in the conditional */\n conditionIndex: number;\n /** Result of condition evaluation */\n result?: boolean;\n}\n\n/**\n * Workflow Parallel attributes\n */\nexport interface WorkflowParallelAttributes extends AIBaseAttributes {\n /** Number of parallel branches */\n branchCount: number;\n /** Step IDs being executed in parallel */\n parallelSteps?: string[];\n}\n\n/**\n * Workflow Loop attributes\n */\nexport interface WorkflowLoopAttributes extends AIBaseAttributes {\n /** Type of loop (foreach, dowhile, dountil) */\n loopType?: 'foreach' | 'dowhile' | 'dountil';\n /** Current iteration number (for individual iterations) */\n iteration?: number;\n /** Total iterations (if known) */\n totalIterations?: number;\n /** Number of steps to run concurrently in foreach loop */\n concurrency?: number;\n}\n\n/**\n * Workflow Sleep attributes\n */\nexport interface WorkflowSleepAttributes extends AIBaseAttributes {\n /** Sleep duration in milliseconds */\n durationMs?: number;\n /** Sleep until date */\n untilDate?: Date;\n /** Sleep type */\n sleepType?: 'fixed' | 'dynamic';\n}\n\n/**\n * Workflow Wait Event attributes\n */\nexport interface WorkflowWaitEventAttributes extends AIBaseAttributes {\n /** Event name being waited for */\n eventName?: string;\n /** Timeout in milliseconds */\n timeoutMs?: number;\n /** Whether event was received or timed out */\n eventReceived?: boolean;\n /** Wait duration in milliseconds */\n waitDurationMs?: number;\n}\n\n/**\n * AI-specific span types mapped to their attributes\n */\nexport interface SpanTypeMap {\n [SpanType.AGENT_RUN]: AgentRunAttributes;\n [SpanType.WORKFLOW_RUN]: WorkflowRunAttributes;\n [SpanType.MODEL_GENERATION]: ModelGenerationAttributes;\n [SpanType.MODEL_STEP]: ModelStepAttributes;\n [SpanType.MODEL_CHUNK]: ModelChunkAttributes;\n [SpanType.TOOL_CALL]: ToolCallAttributes;\n [SpanType.MCP_TOOL_CALL]: MCPToolCallAttributes;\n [SpanType.PROCESSOR_RUN]: ProcessorRunAttributes;\n [SpanType.WORKFLOW_STEP]: WorkflowStepAttributes;\n [SpanType.WORKFLOW_CONDITIONAL]: WorkflowConditionalAttributes;\n [SpanType.WORKFLOW_CONDITIONAL_EVAL]: WorkflowConditionalEvalAttributes;\n [SpanType.WORKFLOW_PARALLEL]: WorkflowParallelAttributes;\n [SpanType.WORKFLOW_LOOP]: WorkflowLoopAttributes;\n [SpanType.WORKFLOW_SLEEP]: WorkflowSleepAttributes;\n [SpanType.WORKFLOW_WAIT_EVENT]: WorkflowWaitEventAttributes;\n [SpanType.GENERIC]: AIBaseAttributes;\n}\n\n/**\n * Union type for cases that need to handle any span type\n */\nexport type AnySpanAttributes = SpanTypeMap[keyof SpanTypeMap];\n\n// ============================================================================\n// Span Interfaces\n// ============================================================================\n\n/** Error information attached to a span when it fails. */\nexport interface SpanErrorInfo {\n message: string;\n id?: string;\n domain?: string;\n category?: string;\n details?: Record<string, any>;\n}\n\n/**\n * Base Span interface\n */\ninterface BaseSpan<TType extends SpanType> {\n /** Unique span identifier */\n id: string;\n /** OpenTelemetry-compatible trace ID (32 hex chars) - present on all spans */\n traceId: string;\n /** Name of the span */\n name: string;\n /** Type of the span */\n type: TType;\n /** Entity type that created the span */\n entityType?: EntityType;\n /** Entity id that created the span */\n entityId?: string;\n /** Entity name that created the span */\n entityName?: string;\n /** When span started */\n startTime: Date;\n /** When span ended */\n endTime?: Date;\n /** Span-type specific attributes */\n attributes?: SpanTypeMap[TType];\n /** User-defined metadata */\n metadata?: Record<string, any>;\n /** Labels used to categorize and filter traces. Only valid on root spans. */\n tags?: string[];\n /** Input passed at the start of the span */\n input?: any;\n /** Output generated at the end of the span */\n output?: any;\n /** Error information if span failed */\n errorInfo?: SpanErrorInfo;\n /** Snapshot of the RequestContext */\n requestContext?: Record<string, any>;\n /** Is an event span? (event occurs at startTime, has no endTime) */\n isEvent: boolean;\n}\n\n/**\n * Span interface, used internally for tracing\n */\nexport interface Span<TType extends SpanType> extends BaseSpan<TType> {\n /** Is an internal span? (spans internal to the operation of mastra) */\n isInternal: boolean;\n /** Parent span reference (undefined for root spans) */\n parent?: AnySpan;\n /** Pointer to the ObservabilityInstance instance */\n observabilityInstance: ObservabilityInstance;\n /** Trace-level state shared across all spans in this trace */\n traceState?: TraceState;\n\n // Methods for span lifecycle\n /** End the span */\n end(options?: EndSpanOptions<TType>): void;\n\n /** Record an error for the span, optionally end the span as well */\n error(options: ErrorSpanOptions<TType>): void;\n\n /** Update span attributes */\n update(options: UpdateSpanOptions<TType>): void;\n\n /** Create child span - can be any span type independent of parent */\n createChildSpan(options: ChildSpanOptions<SpanType.MODEL_GENERATION>): AIModelGenerationSpan;\n createChildSpan<TChildType extends SpanType>(options: ChildSpanOptions<TChildType>): Span<TChildType>;\n\n /** Create event span - can be any span type independent of parent */\n createEventSpan<TChildType extends SpanType>(options: ChildEventOptions<TChildType>): Span<TChildType>;\n\n /** Returns `TRUE` if the span is the root span of a trace */\n get isRootSpan(): boolean;\n\n /** Returns `TRUE` if the span is a valid span (not a NO-OP Span) */\n get isValid(): boolean;\n\n /** Get the closest parent spanId that isn't an internal span */\n getParentSpanId(includeInternalSpans?: boolean): string | undefined;\n\n /** Find the closest parent span of a specific type by walking up the parent chain */\n findParent<T extends SpanType>(spanType: T): Span<T> | undefined;\n\n /**\n * Optional hook for implementations that expose canonical correlation\n * context directly from the span instance.\n */\n getCorrelationContext?(): CorrelationContext;\n\n /** Returns a lightweight span ready for export */\n exportSpan(includeInternalSpans?: boolean): ExportedSpan<TType> | undefined;\n\n /** Returns the traceId on span, unless NoOpSpan, then undefined */\n get externalTraceId(): string | undefined;\n\n /**\n * Execute an async function within this span's tracing context.\n *\n * When a bridge is configured, this enables auto-instrumented operations\n * (HTTP requests, database queries, etc.) to be properly nested under this\n * span in the external tracing system.\n *\n * @param fn - The async function to execute within the span context\n * @returns The result of the function execution\n *\n * @example\n * ```typescript\n * const result = await modelSpan.executeInContext(async () => {\n * return model.generateText(...);\n * });\n * ```\n */\n executeInContext<T>(fn: () => Promise<T>): Promise<T>;\n\n /**\n * Execute a synchronous function within this span's tracing context.\n *\n * When a bridge is configured, this enables auto-instrumented operations\n * (HTTP requests, database queries, etc.) to be properly nested under this\n * span in the external tracing system.\n *\n * @param fn - The synchronous function to execute within the span context\n * @returns The result of the function execution\n *\n * @example\n * ```typescript\n * const result = modelSpan.executeInContextSync(() => {\n * return model.streamText(...);\n * });\n * ```\n */\n executeInContextSync<T>(fn: () => T): T;\n}\n\n/** Context for bridging Mastra spans with external tracing systems (e.g., OpenTelemetry). */\nexport interface BridgeSpanContext {\n /**\n * Execute an async function within this span's tracing context.\n *\n * When a bridge is configured, this enables auto-instrumented operations\n * (HTTP requests, database queries, etc.) to be properly nested under this\n * span in the external tracing system.\n *\n * @param fn - The async function to execute within the span context\n * @returns The result of the function execution\n *\n * @example\n * ```typescript\n * const result = await modelSpan.executeInContext(async () => {\n * return model.generateText(...);\n * });\n * ```\n */\n executeInContext<T>(fn: () => Promise<T>): Promise<T>;\n\n /**\n * Execute a synchronous function within this span's tracing context.\n *\n * When a bridge is configured, this enables auto-instrumented operations\n * (HTTP requests, database queries, etc.) to be properly nested under this\n * span in the external tracing system.\n *\n * @param fn - The synchronous function to execute within the span context\n * @returns The result of the function execution\n *\n * @example\n * ```typescript\n * const result = modelSpan.executeInContextSync(() => {\n * return model.streamText(...);\n * });\n * ```\n */\n executeInContextSync<T>(fn: () => T): T;\n}\n\n/**\n * Specialized span interface for MODEL_GENERATION spans\n * Provides access to creating a ModelSpanTracker for tracking MODEL_STEP and MODEL_CHUNK spans\n */\nexport interface AIModelGenerationSpan extends Span<SpanType.MODEL_GENERATION> {\n /** Create a ModelSpanTracker for tracking model execution steps and chunks */\n createTracker(): IModelSpanTracker | undefined;\n}\n\n/**\n * Span data structure shared between exported and recorded spans.\n * Contains all span fields in a serializable format (no object references).\n *\n * This is the common base for:\n * - ExportedSpan: span data sent to exporters\n * - RecordedSpan: span data loaded from storage with annotation methods\n */\nexport interface SpanData<TType extends SpanType> extends BaseSpan<TType> {\n /** Parent span id reference (undefined for root spans) */\n parentSpanId?: string;\n /** `TRUE` if the span is the root span of a trace */\n isRootSpan: boolean;\n /**\n * Tags for this trace (only present on root spans).\n * Tags are string labels used to categorize and filter traces.\n */\n tags?: string[];\n}\n\n/**\n * Exported Span interface, used for tracing exporters.\n * This is the format sent to ObservabilityExporter implementations.\n */\nexport interface ExportedSpan<TType extends SpanType> extends SpanData<TType> {}\n\n/**\n * Options for ending a model generation span\n */\nexport interface EndGenerationOptions extends EndSpanOptions<SpanType.MODEL_GENERATION> {\n /** Raw usage data from AI SDK - will be converted to UsageStats with cache token details */\n usage?: LanguageModelUsage;\n /** Provider-specific metadata for extracting cache tokens */\n providerMetadata?: ProviderMetadata;\n}\n\n/** Tracks model execution steps and streaming chunks within a MODEL_GENERATION span. */\nexport interface IModelSpanTracker {\n getTracingContext(): TracingContext;\n reportGenerationError(options: ErrorSpanOptions<SpanType.MODEL_GENERATION>): void;\n endGeneration(options?: EndGenerationOptions): void;\n updateGeneration(options: UpdateSpanOptions<SpanType.MODEL_GENERATION>): void;\n wrapStream<T extends { pipeThrough: Function }>(stream: T): T;\n startStep(payload?: StepStartPayload): void;\n}\n\n/**\n * Union type for cases that need to handle any span\n */\nexport type AnySpan = Span<keyof SpanTypeMap>;\n\n/**\n * Union type for cases that need to handle any exported span\n */\nexport type AnyExportedSpan = ExportedSpan<keyof SpanTypeMap>;\n\n// ============================================================================\n// Recorded Span & Trace Interfaces\n// ============================================================================\n\n/**\n * A recorded span is span data that has been captured/persisted and can have\n * scores and feedback attached post-hoc. Unlike live Span objects, RecordedSpan\n * has immutable core data but supports annotation methods.\n *\n * Spans are organized in a tree structure via parent/children references,\n * with all references pointing to the same objects in memory.\n *\n * Use cases:\n * - Spans loaded from storage for evaluation\n * - Spans from completed traces being annotated\n * - Post-hoc quality scoring and user feedback\n */\nexport interface RecordedSpan<TType extends SpanType> extends SpanData<TType> {\n /** Parent span reference (undefined for root spans) */\n readonly parent?: AnyRecordedSpan;\n\n /** Child spans in execution order */\n readonly children: ReadonlyArray<AnyRecordedSpan>;\n\n /**\n * Add a quality score to this recorded span.\n * Scores are emitted via the ObservabilityBus and can be persisted/exported.\n */\n addScore(score: ScoreInput): void;\n\n /**\n * Add user feedback to this recorded span.\n * Feedback is emitted via the ObservabilityBus and can be persisted/exported.\n */\n addFeedback(feedback: FeedbackInput): void;\n}\n\n/**\n * Union type for cases that need to handle any recorded span\n */\nexport type AnyRecordedSpan = RecordedSpan<keyof SpanTypeMap>;\n\n/**\n * A recorded trace is a complete execution trace loaded from storage.\n * Provides both tree access (via rootSpan) and flat access (via spans).\n * All references point to the same span objects - no memory duplication.\n *\n * Obtained via mastra.getTrace(traceId) for post-execution annotation.\n */\nexport interface RecordedTrace {\n /** The trace identifier */\n readonly traceId: string;\n\n /** Root span of the trace tree (entry point for tree traversal) */\n readonly rootSpan: AnyRecordedSpan;\n\n /** All spans in flat array for iteration (same objects as in tree) */\n readonly spans: ReadonlyArray<AnyRecordedSpan>;\n\n /**\n * Get a specific recorded span by ID.\n * @param spanId - The span identifier\n * @returns The recorded span if found, null otherwise\n */\n getSpan(spanId: string): AnyRecordedSpan | null;\n\n /**\n * Add a score at the trace level.\n * Uses root span's metadata for context inheritance.\n */\n addScore(score: ScoreInput): void;\n\n /**\n * Add feedback at the trace level.\n * Uses root span's metadata for context inheritance.\n */\n addFeedback(feedback: FeedbackInput): void;\n}\n\n// ============================================================================\n// Tracing Interfaces\n// ============================================================================\n\n// ============================================================================\n// Span Create/Update/Error Option Types\n// ============================================================================\n\ninterface CreateBaseOptions<TType extends SpanType> {\n /** Span attributes */\n attributes?: SpanTypeMap[TType];\n /** Span metadata */\n metadata?: Record<string, any>;\n /** Span name */\n name: string;\n /** Span type */\n type: TType;\n /** Entity type that created the span */\n entityType?: EntityType;\n /** Entity id that created the span */\n entityId?: string;\n /** Entity name that created the span */\n entityName?: string;\n /** Policy-level tracing configuration */\n tracingPolicy?: TracingPolicy;\n /** Request Context for metadata extraction */\n requestContext?: RequestContext;\n}\n\n/**\n * Options for creating new spans\n */\nexport interface CreateSpanOptions<TType extends SpanType> extends CreateBaseOptions<TType> {\n /** Input data */\n input?: any;\n /** Output data (for event spans) */\n output?: any;\n /** Labels used to categorize and filter traces. Only valid on root spans. */\n tags?: string[];\n /** Parent span */\n parent?: AnySpan;\n /** Is an event span? */\n isEvent?: boolean;\n /**\n * Trace ID to use for this span (1-32 hexadecimal characters).\n * Only used for root spans without a parent.\n */\n traceId?: string;\n /**\n * Span ID to use for this span (1-16 hexadecimal characters).\n * Only used when rebuilding a span from cached data.\n */\n spanId?: string;\n /**\n * Parent span ID to use for this span (1-16 hexadecimal characters).\n * Only used for root spans without a parent.\n */\n parentSpanId?: string;\n /**\n * Start time for this span.\n * Only used when rebuilding a span from cached data.\n */\n startTime?: Date;\n /** Trace-level state shared across all spans in this trace */\n traceState?: TraceState;\n}\n\n/**\n * Options for starting new spans\n */\nexport interface StartSpanOptions<TType extends SpanType> extends CreateSpanOptions<TType> {\n /**\n * Options passed when using a custom sampler strategy\n */\n customSamplerOptions?: CustomSamplerOptions;\n /** Tracing options for this execution */\n tracingOptions?: TracingOptions;\n}\n\n/**\n * Options for new child spans\n */\nexport interface ChildSpanOptions<TType extends SpanType> extends CreateBaseOptions<TType> {\n /** Input data */\n input?: any;\n}\n\n/**\n * Options for new child events\n * Event spans have no input, and no endTime\n */\nexport interface ChildEventOptions<TType extends SpanType> extends CreateBaseOptions<TType> {\n /** Output data */\n output?: any;\n}\n\ninterface UpdateBaseOptions<TType extends SpanType> {\n /** Span attributes */\n attributes?: Partial<SpanTypeMap[TType]>;\n /** Span metadata */\n metadata?: Record<string, any>;\n}\n\n/** Options for ending a span, with optional final attributes and output. */\nexport interface EndSpanOptions<TType extends SpanType> extends UpdateBaseOptions<TType> {\n /** Output data */\n output?: any;\n}\n\n/** Options for updating a span's attributes, input, or output mid-flight. */\nexport interface UpdateSpanOptions<TType extends SpanType> extends UpdateBaseOptions<TType> {\n /** Span name override */\n name?: string;\n /** Input data */\n input?: any;\n /** Output data */\n output?: any;\n}\n\n/** Options for recording an error on a span. */\nexport interface ErrorSpanOptions<TType extends SpanType> extends UpdateBaseOptions<TType> {\n /** The error associated with the issue */\n error: MastraError | Error;\n /** End the span when true */\n endSpan?: boolean;\n}\n\n/** Options for retrieving an existing span or creating a new one from a tracing context. */\nexport interface GetOrCreateSpanOptions<TType extends SpanType> {\n type: TType;\n name: string;\n entityType?: EntityType;\n entityId?: string;\n entityName?: string;\n input?: any;\n attributes?: SpanTypeMap[TType];\n metadata?: Record<string, any>;\n tracingPolicy?: TracingPolicy;\n tracingOptions?: TracingOptions;\n tracingContext?: TracingContext;\n requestContext?: RequestContext;\n mastra?: Mastra;\n}\n\n/**\n * Bitwise options to set different types of spans as internal in\n * a workflow or agent execution.\n */\nexport enum InternalSpans {\n /** No spans are marked internal */\n NONE = 0,\n /** Workflow spans are marked internal */\n WORKFLOW = 1 << 0, // 0001\n /** Agent spans are marked internal */\n AGENT = 1 << 1, // 0010\n /** Tool spans are marked internal */\n TOOL = 1 << 2, // 0100\n /** Model spans are marked internal */\n MODEL = 1 << 3, // 1000\n\n /** All spans are marked internal */\n ALL = (1 << 4) - 1, // 1111 (all bits set up to 3)\n}\n\n/**\n * Policy-level tracing configuration applied when creating\n * a workflow or agent. Unlike TracingOptions, which are\n * provided at execution time, policies define persistent rules\n * for how spans are treated across all executions of the\n * workflow/agent.\n */\nexport interface TracingPolicy {\n /**\n * Bitwise options to set different types of spans as Internal in\n * a workflow or agent execution. Internal spans are hidden by\n * default in exported traces.\n */\n internal?: InternalSpans;\n}\n\n/**\n * Trace-level state computed once at the start of a trace\n * and shared by all spans within that trace.\n */\nexport interface TraceState {\n /**\n * RequestContext keys to extract as metadata for all spans in this trace.\n * Computed by merging the tracing config's requestContextKeys\n * with the per-request requestContextKeys.\n */\n requestContextKeys: string[];\n /**\n * When true, input data will be hidden from all spans in this trace.\n */\n hideInput?: boolean;\n /**\n * When true, output data will be hidden from all spans in this trace.\n */\n hideOutput?: boolean;\n}\n\n/**\n * Options passed when starting a new agent or workflow execution\n */\nexport interface TracingOptions {\n /** Metadata to add to the root trace span */\n metadata?: Record<string, any>;\n /**\n * Additional RequestContext keys to extract as metadata for this trace.\n * These keys are added to the requestContextKeys config.\n * Supports dot notation for nested values (e.g., 'user.id', 'session.data.experimentId').\n */\n requestContextKeys?: string[];\n /**\n * Trace ID to use for this execution (1-32 hexadecimal characters).\n * If provided, this trace will be part of the specified trace rather than starting a new one.\n */\n traceId?: string;\n /**\n * Parent span ID to use for this execution (1-16 hexadecimal characters).\n * If provided, the root span will be created as a child of this span.\n */\n parentSpanId?: string;\n /**\n * Tags to apply to this trace.\n * Tags are string labels that can be used to categorize and filter traces\n * Note: Tags are only applied to the root span of a trace.\n */\n tags?: string[];\n /**\n * When true, input data will be hidden from all spans in this trace.\n * Useful for protecting sensitive data from being logged.\n */\n hideInput?: boolean;\n /**\n * When true, output data will be hidden from all spans in this trace.\n * Useful for protecting sensitive data from being logged.\n */\n hideOutput?: boolean;\n}\n\n/** Trace and span identifiers for correlating spans across systems. */\nexport interface SpanIds {\n traceId: string;\n spanId: string;\n parentSpanId?: string;\n}\n\n/**\n * Context for tracing that flows through workflow and agent execution\n */\nexport interface TracingContext {\n /** Current Span for creating child spans and adding metadata */\n currentSpan?: AnySpan;\n}\n\n/**\n * Properties returned to the user for working with traces externally.\n */\nexport type TracingProperties = {\n /** Trace ID used on the execution (if the execution was traced). */\n traceId?: string;\n /** Root span ID used on the execution (if the execution was traced). */\n spanId?: string;\n};\n\n// ============================================================================\n// Exporter and Processor Interfaces\n// ============================================================================\n\n/**\n * Tracing event types\n */\nexport enum TracingEventType {\n SPAN_STARTED = 'span_started',\n SPAN_UPDATED = 'span_updated',\n SPAN_ENDED = 'span_ended',\n}\n\n/**\n * Tracing events that can be exported\n */\nexport type TracingEvent =\n | { type: TracingEventType.SPAN_STARTED; exportedSpan: AnyExportedSpan }\n | { type: TracingEventType.SPAN_UPDATED; exportedSpan: AnyExportedSpan }\n | { type: TracingEventType.SPAN_ENDED; exportedSpan: AnyExportedSpan };\n\n/**\n * Interface for span processors\n */\nexport interface SpanOutputProcessor {\n /** Processor name */\n name: string;\n /** Process span before export */\n process(span?: AnySpan): AnySpan | undefined;\n /** Shutdown processor */\n shutdown(): Promise<void>;\n}\n\n/**\n * Function type for formatting exported spans at the exporter level.\n *\n * This allows customization of how spans appear in vendor-specific observability platforms\n * (e.g., Langfuse, Braintrust). Unlike SpanOutputProcessor which operates on the internal\n * Span object before export, this formatter operates on the ExportedSpan data structure\n * after the span has been prepared for export.\n *\n * Formatters can be synchronous or asynchronous, enabling use cases like:\n * - Extract plain text from structured AI SDK messages for better readability\n * - Transform input/output format for specific vendor requirements\n * - Add or remove fields based on the target platform\n * - Redact or transform sensitive data in a vendor-specific way\n * - Enrich spans with data from external APIs (async)\n * - Perform database lookups to add context (async)\n *\n * @param span - The exported span to format\n * @returns The formatted span (sync) or a Promise resolving to the formatted span (async)\n *\n * @example\n * ```typescript\n * // Synchronous formatter that extracts plain text from AI messages\n * const plainTextFormatter: CustomSpanFormatter = (span) => {\n * if (span.type === SpanType.AGENT_RUN && Array.isArray(span.input)) {\n * const userMessage = span.input.find(m => m.role === 'user');\n * return {\n * ...span,\n * input: userMessage?.content ?? span.input,\n * };\n * }\n * return span;\n * };\n *\n * // Async formatter that enriches spans with external data\n * const enrichmentFormatter: CustomSpanFormatter = async (span) => {\n * const userData = await fetchUserData(span.metadata?.userId);\n * return {\n * ...span,\n * metadata: { ...span.metadata, userName: userData.name },\n * };\n * };\n *\n * // Use with an exporter\n * new BraintrustExporter({\n * customSpanFormatter: plainTextFormatter,\n * });\n * ```\n */\nexport type CustomSpanFormatter = (span: AnyExportedSpan) => AnyExportedSpan | Promise<AnyExportedSpan>;\n","import type { CorrelationContext } from './core';\n\n// ============================================================================\n// Metric Type\n// ============================================================================\n\n/**\n * @deprecated MetricType is no longer stored. All metrics are raw events\n * with aggregation determined at query time.\n */\nexport type MetricType = 'counter' | 'gauge' | 'histogram';\n\n// ============================================================================\n// MetricsContext (API Interface)\n// ============================================================================\n\n/**\n * MetricsContext - API for emitting metrics.\n * Use `emit()` to record a metric observation.\n */\nexport interface MetricEmitOptions {\n /** Canonical model/cost context for this specific metric row */\n costContext?: CostContext;\n}\n\nexport interface MetricsContext {\n /** Emit a metric observation. */\n emit(name: string, value: number, labels?: Record<string, string>, options?: MetricEmitOptions): void;\n\n /** @deprecated Use `emit()` instead. */\n counter(name: string): Counter;\n /** @deprecated Use `emit()` instead. */\n gauge(name: string): Gauge;\n /** @deprecated Use `emit()` instead. */\n histogram(name: string): Histogram;\n}\n\n/** @deprecated Use MetricsContext.emit() instead. */\nexport interface Counter {\n add(value: number, additionalLabels?: Record<string, string>): void;\n}\n\n/** @deprecated Use MetricsContext.emit() instead. */\nexport interface Gauge {\n set(value: number, additionalLabels?: Record<string, string>): void;\n}\n\n/** @deprecated Use MetricsContext.emit() instead. */\nexport interface Histogram {\n record(value: number, additionalLabels?: Record<string, string>): void;\n}\n\n// ============================================================================\n// ExportedMetric (Event Bus Transport)\n// ============================================================================\n\n/**\n * Typed context used for cost estimations.\n */\nexport interface CostContext {\n provider?: string;\n model?: string;\n estimatedCost?: number;\n costUnit?: string;\n costMetadata?: Record<string, unknown>;\n}\n\n/**\n * Metric data transported via the event bus.\n * Represents a single metric observation.\n * Must be JSON-serializable (Date serializes via toJSON()).\n *\n * Canonical correlation fields travel in `correlationContext` and canonical\n * pricing/model fields travel in `costContext`.\n *\n * Note: Histogram aggregation (bucket counts, sum, count) is computed at\n * the storage layer, not in the individual metric event.\n */\nexport interface ExportedMetric {\n /** When the metric was recorded */\n timestamp: Date;\n\n /** Metric name (e.g., mastra_agent_duration_ms) */\n name: string;\n\n /** Metric value (single observation) */\n value: number;\n\n /** Metric labels for dimensional filtering */\n labels: Record<string, string>;\n\n /** Context for correlation to traces */\n correlationContext?: CorrelationContext;\n\n /** Context for cost estimation */\n costContext?: CostContext;\n\n /**\n * User-defined metadata.\n * This is reserved for non-canonical metadata that does not belong\n * in record context or cost context.\n */\n metadata?: Record<string, unknown>;\n}\n\n// ============================================================================\n// MetricEvent (Event Bus Event)\n// ============================================================================\n\n/** Metric event emitted to the ObservabilityBus */\nexport interface MetricEvent {\n type: 'metric';\n metric: ExportedMetric;\n}\n\n// ============================================================================\n// Cardinality Protection\n// ============================================================================\n\n/**\n * Default labels to block from metrics to prevent cardinality explosion.\n * These are high-cardinality fields that should not be used as metric labels.\n */\nexport const DEFAULT_BLOCKED_LABELS = [\n 'trace_id',\n 'span_id',\n 'run_id',\n 'request_id',\n 'user_id',\n 'resource_id',\n 'session_id',\n 'thread_id',\n] as const;\n\n/** Cardinality protection configuration */\nexport interface CardinalityConfig {\n /**\n * Labels to block from metrics. **Replaces** the default list entirely —\n * DEFAULT_BLOCKED_LABELS are NOT merged in when this is set.\n *\n * - `undefined` (default) → uses DEFAULT_BLOCKED_LABELS\n * - `[]` → disables label blocking (allows all labels through)\n * - `['x', 'y']` → blocks only x and y; defaults like trace_id are allowed\n *\n * To extend the defaults, spread them into your list:\n * ```ts\n * blockedLabels: [...DEFAULT_BLOCKED_LABELS, 'my_custom_label']\n * ```\n */\n blockedLabels?: string[];\n\n /**\n * Whether to block UUID-like values in labels.\n * @default true\n */\n blockUUIDs?: boolean;\n}\n\n/** Metrics-specific configuration */\nexport interface MetricsConfig {\n /** Whether metrics are enabled */\n enabled?: boolean;\n /** Cardinality protection settings */\n cardinality?: CardinalityConfig;\n}\n","import type { Mastra } from '..';\nimport type { IMastraLogger } from '../logger';\nimport type {\n ConfigSelector,\n ConfigSelectorOptions,\n Counter,\n Gauge,\n Histogram,\n LoggerContext,\n MetricsContext,\n ObservabilityEntrypoint,\n ObservabilityInstance,\n TracingContext,\n} from './types';\n\n// ============================================================================\n// No-Op Metric Instruments\n// ============================================================================\n\nconst noOpCounter: Counter = {\n add() {},\n};\n\nconst noOpGauge: Gauge = {\n set() {},\n};\n\nconst noOpHistogram: Histogram = {\n record() {},\n};\n\n// ============================================================================\n// No-Op TracingContext\n// ============================================================================\n\n/**\n * No-op tracing context used when observability is not configured.\n */\nexport const noOpTracingContext: TracingContext = {\n currentSpan: undefined,\n};\n\n// ============================================================================\n// No-Op LoggerContext\n// ============================================================================\n\n/**\n * No-op logger context that silently discards all log calls.\n * Used when observability is not configured.\n */\nexport const noOpLoggerContext: LoggerContext = {\n debug() {},\n info() {},\n warn() {},\n error() {},\n fatal() {},\n};\n\n// ============================================================================\n// No-Op MetricsContext\n// ============================================================================\n\n/**\n * No-op metrics context that silently discards all metric operations.\n * Used when observability is not configured.\n */\nexport const noOpMetricsContext: MetricsContext = {\n emit() {},\n counter() {\n return noOpCounter;\n },\n gauge() {\n return noOpGauge;\n },\n histogram() {\n return noOpHistogram;\n },\n};\n\n// ============================================================================\n// No-Op Observability\n// ============================================================================\n\n/** No-op observability entrypoint that silently discards all operations. */\nexport class NoOpObservability implements ObservabilityEntrypoint {\n setMastraContext(_options: { mastra: Mastra }): void {\n return;\n }\n\n setLogger(_options: { logger: IMastraLogger }): void {\n return;\n }\n\n getSelectedInstance(_options: ConfigSelectorOptions): ObservabilityInstance | undefined {\n return;\n }\n\n registerInstance(_name: string, _instance: ObservabilityInstance, _isDefault = false): void {\n return;\n }\n\n getInstance(_name: string): ObservabilityInstance | undefined {\n return;\n }\n\n getDefaultInstance(): ObservabilityInstance | undefined {\n return;\n }\n\n listInstances(): ReadonlyMap<string, ObservabilityInstance> {\n return new Map();\n }\n\n unregisterInstance(_name: string): boolean {\n return false;\n }\n\n hasInstance(_name: string): boolean {\n return false;\n }\n\n setConfigSelector(_selector: ConfigSelector): void {\n return;\n }\n\n clear(): void {\n return;\n }\n\n async shutdown(): Promise<void> {\n return;\n }\n}\n","import type { Span, SpanType, GetOrCreateSpanOptions, AnySpan } from './types';\n\n/**\n * Creates or gets a child span from existing tracing context or starts a new trace.\n * This helper consolidates the common pattern of creating spans that can either be:\n * 1. Children of an existing span (when tracingContext.currentSpan exists)\n * 2. New root spans (when no current span exists)\n *\n * @param options - Configuration object for span creation\n * @returns The created Span or undefined if tracing is disabled\n */\nexport function getOrCreateSpan<T extends SpanType>(options: GetOrCreateSpanOptions<T>): Span<T> | undefined {\n const { type, attributes, tracingContext, requestContext, tracingOptions, ...rest } = options;\n\n const metadata = {\n ...(rest.metadata ?? {}),\n ...(tracingOptions?.metadata ?? {}),\n };\n\n // If we have a current span, create a child span\n if (tracingContext?.currentSpan) {\n return tracingContext.currentSpan.createChildSpan({\n type,\n attributes,\n ...rest,\n metadata,\n requestContext,\n });\n }\n\n // Otherwise, try to create a new root span\n const instance = options.mastra?.observability?.getSelectedInstance({ requestContext });\n\n return instance?.startSpan<T>({\n type,\n attributes,\n ...rest,\n metadata,\n requestContext,\n tracingOptions,\n traceId: tracingOptions?.traceId,\n parentSpanId: tracingOptions?.parentSpanId,\n customSamplerOptions: {\n requestContext,\n metadata,\n },\n });\n}\n\n/**\n * Execute an async function within the span's tracing context if available.\n * Falls back to direct execution if no span exists.\n *\n * When a bridge is configured, this enables auto-instrumented operations\n * (HTTP requests, database queries, etc.) to be properly nested under the\n * current span in the external tracing system.\n *\n * @param span - The span to use as context (or undefined to execute without context)\n * @param fn - The async function to execute\n * @returns The result of the function execution\n *\n * @example\n * ```typescript\n * const result = await executeWithContext(llmSpan, async () =>\n * model.generateText(args)\n * );\n * ```\n */\nexport async function executeWithContext<T>(params: { span?: AnySpan; fn: () => Promise<T> }): Promise<T> {\n const { span, fn } = params;\n\n if (span?.executeInContext) {\n return span.executeInContext(fn);\n }\n\n return fn();\n}\n\n/**\n * Execute a synchronous function within the span's tracing context if available.\n * Falls back to direct execution if no span exists.\n *\n * When a bridge is configured, this enables auto-instrumented operations\n * (HTTP requests, database queries, etc.) to be properly nested under the\n * current span in the external tracing system.\n *\n * @param span - The span to use as context (or undefined to execute without context)\n * @param fn - The synchronous function to execute\n * @returns The result of the function execution\n *\n * @example\n * ```typescript\n * const result = executeWithContextSync(llmSpan, () =>\n * model.streamText(args)\n * );\n * ```\n */\nexport function executeWithContextSync<T>(params: { span?: AnySpan; fn: () => T }): T {\n const { span, fn } = params;\n\n if (span?.executeInContextSync) {\n return span.executeInContextSync(fn);\n }\n\n return fn();\n}\n\n/**\n * Returns the top-most non-internal span that would appear in exported tracing output.\n *\n * Public API results should use this span for trace/span correlation because internal Mastra\n * workflow spans are omitted from external exporters.\n */\nexport function getRootExportSpan(span?: AnySpan): AnySpan | undefined {\n if (!span?.isValid) {\n return undefined;\n }\n\n let current: AnySpan | undefined = span;\n let rootExportSpan: AnySpan | undefined = span.isInternal ? undefined : span;\n\n while (current?.parent) {\n current = current.parent;\n\n if (!current.isInternal) {\n rootExportSpan = current;\n }\n }\n\n return rootExportSpan;\n}\n","// packages/core/src/observability/context-factory.ts\n\nimport { noOpLoggerContext, noOpMetricsContext, noOpTracingContext } from './no-op';\nimport type { LoggerContext, MetricsContext, ObservabilityContext, TracingContext } from './types';\n\n// ============================================================================\n// Context Derivation\n// ============================================================================\n\n/**\n * Derives a LoggerContext from the current span's ObservabilityInstance.\n * Falls back to no-op when there is no span or the instance doesn't support logging.\n */\nfunction deriveLoggerContext(tracing: TracingContext): LoggerContext {\n const span = tracing.currentSpan;\n return span?.observabilityInstance?.getLoggerContext?.(span) ?? noOpLoggerContext;\n}\n\n/**\n * Derives a MetricsContext from the current span's ObservabilityInstance.\n * Falls back to no-op when there is no span or the instance doesn't support metrics.\n */\nfunction deriveMetricsContext(tracing: TracingContext): MetricsContext {\n const span = tracing.currentSpan;\n return span?.observabilityInstance?.getMetricsContext?.(span) ?? noOpMetricsContext;\n}\n\n// ============================================================================\n// Context Factory\n// ============================================================================\n\n/**\n * Creates an observability context with real or no-op implementations for\n * tracing, logging, and metrics.\n *\n * When a TracingContext with a current span is provided, the logger and metrics\n * contexts are derived from the span's ObservabilityInstance so that log entries\n * and metric data points are automatically correlated to the active trace.\n *\n * @param tracingContext - TracingContext with current span, or undefined for no-op\n * @returns ObservabilityContext with all three signals (tracing, logger, metrics)\n */\nexport function createObservabilityContext(tracingContext?: TracingContext): ObservabilityContext {\n const tracing = tracingContext ?? noOpTracingContext;\n\n return {\n tracing,\n loggerVNext: deriveLoggerContext(tracing),\n metrics: deriveMetricsContext(tracing),\n tracingContext: tracing, // alias — preferred at forwarding sites\n };\n}\n\n/**\n * Resolves a partial observability context (from execute params) into a\n * complete ObservabilityContext with no-op defaults for any missing fields.\n *\n * Explicitly provided logger/metrics contexts are preserved (e.g. when set\n * upstream). When missing, they are derived from the tracing context's span,\n * following the same derivation logic as createObservabilityContext().\n *\n * @param partial - Partial context from ExecuteFunctionParams\n * @returns Complete ObservabilityContext\n */\nexport function resolveObservabilityContext(partial: Partial<ObservabilityContext>): ObservabilityContext {\n const tracing = partial.tracing ?? partial.tracingContext ?? noOpTracingContext;\n\n return {\n tracing,\n loggerVNext: partial.loggerVNext ?? deriveLoggerContext(tracing),\n metrics: partial.metrics ?? deriveMetricsContext(tracing),\n tracingContext: tracing, // alias — preferred at forwarding sites\n };\n}\n","/**\n * Tracing Context Integration\n *\n * This module provides automatic tracing context propagation throughout Mastra's execution contexts.\n * It uses JavaScript Proxies to transparently wrap Mastra, Agent, and Workflow instances so that\n * tracing context is automatically injected without requiring manual passing by users.\n */\n\nimport type { MastraPrimitives } from '../action';\nimport type { Agent } from '../agent';\nimport type { Mastra } from '../mastra';\nimport type { Workflow } from '../workflows';\nimport { createObservabilityContext } from './context-factory';\nimport type { TracingContext, AnySpan } from './types';\n\nconst AGENT_GETTERS = ['getAgent', 'getAgentById'];\nconst AGENT_METHODS_TO_WRAP = ['generate', 'stream', 'generateLegacy', 'streamLegacy'];\n\nconst WORKFLOW_GETTERS = ['getWorkflow', 'getWorkflowById'];\nconst WORKFLOW_METHODS_TO_WRAP = ['execute', 'createRun', 'createRun'];\n\n/**\n * Helper function to detect NoOp spans to avoid unnecessary wrapping\n */\nfunction isNoOpSpan(span: AnySpan): boolean {\n // Check if this is a NoOp span implementation\n return span.constructor.name === 'NoOpSpan' || (span as any).__isNoOp === true;\n}\n\n/**\n * Checks to see if a passed object is an actual instance of Mastra\n * (for the purposes of wrapping it for Tracing)\n */\nexport function isMastra<T extends Mastra | (Mastra & MastraPrimitives) | MastraPrimitives>(mastra: T): boolean {\n const hasAgentGetters = AGENT_GETTERS.every(method => typeof (mastra as any)?.[method] === 'function');\n const hasWorkflowGetters = WORKFLOW_GETTERS.every(method => typeof (mastra as any)?.[method] === 'function');\n\n return hasAgentGetters && hasWorkflowGetters;\n}\n\n/**\n * Creates a tracing-aware Mastra proxy that automatically injects\n * tracing context into agent and workflow method calls\n */\nexport function wrapMastra<T extends Mastra | (Mastra & MastraPrimitives) | MastraPrimitives>(\n mastra: T,\n tracingContext: TracingContext,\n): T {\n // Don't wrap if no current span or if using NoOp span\n if (!tracingContext.currentSpan || isNoOpSpan(tracingContext.currentSpan)) {\n return mastra;\n }\n\n // Check if this object has the methods we want to wrap - if not, return as is\n if (!isMastra(mastra)) {\n return mastra;\n }\n\n try {\n return new Proxy(mastra, {\n get(target, prop) {\n try {\n if (AGENT_GETTERS.includes(prop as string)) {\n return (...args: any[]) => {\n const agent = (target as any)[prop](...args);\n return wrapAgent(agent, tracingContext);\n };\n }\n\n // Wrap workflow getters\n if (WORKFLOW_GETTERS.includes(prop as string)) {\n return (...args: any[]) => {\n const workflow = (target as any)[prop](...args);\n return wrapWorkflow(workflow, tracingContext);\n };\n }\n\n // Pass through all other methods unchanged - bind functions to preserve 'this' context\n const value = (target as any)[prop];\n return typeof value === 'function' ? value.bind(target) : value;\n } catch (error) {\n console.warn('Tracing: Failed to wrap method, falling back to original', error);\n const value = (target as any)[prop];\n return typeof value === 'function' ? value.bind(target) : value;\n }\n },\n });\n } catch (error) {\n console.warn('Tracing: Failed to create proxy, using original Mastra instance', error);\n return mastra;\n }\n}\n\n/**\n * Creates a tracing-aware Agent proxy that automatically injects\n * tracing context into generation method calls\n */\nfunction wrapAgent<T extends Agent>(agent: T, tracingContext: TracingContext): T {\n // Don't wrap if no current span or if using NoOp span\n if (!tracingContext.currentSpan || isNoOpSpan(tracingContext.currentSpan)) {\n return agent;\n }\n\n try {\n return new Proxy(agent, {\n get(target, prop) {\n try {\n if (AGENT_METHODS_TO_WRAP.includes(prop as string)) {\n return (input: any, options: any = {}) => {\n return (target as any)[prop](input, {\n ...options,\n ...createObservabilityContext(tracingContext),\n });\n };\n }\n\n // Bind functions to preserve 'this' context for private member access\n const value = (target as any)[prop];\n return typeof value === 'function' ? value.bind(target) : value;\n } catch (error) {\n console.warn('Tracing: Failed to wrap agent method, falling back to original', error);\n const value = (target as any)[prop];\n return typeof value === 'function' ? value.bind(target) : value;\n }\n },\n });\n } catch (error) {\n console.warn('Tracing: Failed to create agent proxy, using original instance', error);\n return agent;\n }\n}\n\n/**\n * Creates a tracing-aware Workflow proxy that automatically injects\n * tracing context into execution method calls\n */\nfunction wrapWorkflow<T extends Workflow>(workflow: T, tracingContext: TracingContext): T {\n // Don't wrap if no current span or if using NoOp span\n if (!tracingContext.currentSpan || isNoOpSpan(tracingContext.currentSpan)) {\n return workflow;\n }\n\n try {\n return new Proxy(workflow, {\n get(target, prop) {\n try {\n // Wrap workflow execution methods with tracing context\n if (WORKFLOW_METHODS_TO_WRAP.includes(prop as string)) {\n // Handle createRun and createRun methods differently\n if (prop === 'createRun' || prop === 'createRun') {\n return async (options: any = {}) => {\n const run = await (target as any)[prop](options);\n return run ? wrapRun(run, tracingContext) : run;\n };\n }\n\n // Handle other methods like execute\n return (input: any, options: any = {}) => {\n return (target as any)[prop](input, {\n ...options,\n ...createObservabilityContext(tracingContext),\n });\n };\n }\n\n // Bind functions to preserve 'this' context for private member access\n const value = (target as any)[prop];\n return typeof value === 'function' ? value.bind(target) : value;\n } catch (error) {\n console.warn('Tracing: Failed to wrap workflow method, falling back to original', error);\n const value = (target as any)[prop];\n return typeof value === 'function' ? value.bind(target) : value;\n }\n },\n });\n } catch (error) {\n console.warn('Tracing: Failed to create workflow proxy, using original instance', error);\n return workflow;\n }\n}\n\n/**\n * Creates a tracing-aware Run proxy that automatically injects\n * tracing context into start method calls\n */\nfunction wrapRun<T extends object>(run: T, tracingContext: TracingContext): T {\n // Don't wrap if no current span or if using NoOp span\n if (!tracingContext.currentSpan || isNoOpSpan(tracingContext.currentSpan)) {\n return run;\n }\n\n try {\n return new Proxy(run, {\n get(target, prop) {\n try {\n if (prop === 'start') {\n return (startOptions: any = {}) => {\n return (target as any).start({\n ...startOptions,\n ...createObservabilityContext(startOptions.tracingContext ?? tracingContext),\n });\n };\n }\n\n // Pass through all other properties and methods unchanged\n const value = (target as any)[prop];\n return typeof value === 'function' ? value.bind(target) : value;\n } catch (error) {\n console.warn('Tracing: Failed to wrap run method, falling back to original', error);\n const value = (target as any)[prop];\n return typeof value === 'function' ? value.bind(target) : value;\n }\n },\n });\n } catch (error) {\n console.warn('Tracing: Failed to create run proxy, using original instance', error);\n return run;\n }\n}\n"]}
@@ -1,3 +0,0 @@
1
-
2
- //# sourceMappingURL=chunk-DMX7MC4N.js.map
3
- //# sourceMappingURL=chunk-DMX7MC4N.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/tools/validation.ts","../src/tools/tool.ts","../src/tools/toolchecks.ts"],"names":["resumeData"],"mappings":";;;;;AAaA,SAAS,YAAA,CACP,QACA,IAAA,EAC2D;AAC3D,EAAA,IAAI;AACF,IAAA,MAAM,MAAA,GAAS,MAAA,CAAO,WAAW,CAAA,CAAE,SAAS,IAAI,CAAA;AAChD,IAAA,IAAI,kBAAkB,OAAA,EAAS;AAC7B,MAAA,MAAM,IAAI,MAAM,yEAAyE,CAAA;AAAA,IAC3F;AACA,IAAA,OAAO,MAAA;AAAA,EACT,SAAS,GAAA,EAAK;AAGZ,IAAA,IAAI,eAAe,SAAA,IAAa,GAAA,CAAI,OAAA,CAAQ,QAAA,CAAS,qCAAqC,CAAA,EAAG;AAC3F,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,yNAAA,EAEgF,IAAI,OAAO,CAAA;AAAA,OAC7F;AAAA,IACF;AACA,IAAA,MAAM,GAAA;AAAA,EACR;AACF;AAmBA,SAAS,WAAW,OAAA,EAAqD;AACvE,EAAA,IAAI,OAAO,OAAA,KAAY,QAAA,IAAY,OAAA,KAAY,IAAA,IAAQ,SAAS,OAAA,EAAS;AACvE,IAAA,OAAO,MAAA,CAAO,QAAQ,GAAG,CAAA;AAAA,EAC3B;AACA,EAAA,OAAO,OAAO,OAAO,CAAA;AACvB;AAKA,SAAS,iBAAA,GAA2E;AAClF,EAAA,OAAO,EAAE,MAAA,EAAQ,EAAC,EAAG,MAAA,EAAQ,EAAC,EAAE;AAClC;AAQA,SAAS,qBAAwB,MAAA,EAAsE;AACrG,EAAA,MAAM,SAAS,iBAAA,EAAkB;AAEj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,OAAO,gBAAA,CAAiB,IAAA;AAAA,MAC1B,CAAA;AAAA,IACF;AAAA,EACF;AACF;AA0GO,SAAS,WAUd,IAAA,EASA;AACA,EAAA,OAAO,IAAI,KAAK,IAAI,CAAA;AACtB;;;AC9gBO,SAAS,aAAa,IAAA,EAAwB;AACnD,EAAA,OAAO,gBAAgB,IAAA,IAAS,OAAO,SAAS,QAAA,IAAY,IAAA,KAAS,QAAQ,kBAAA,IAAsB,IAAA;AACrG;AAOO,SAAS,aAAa,IAAA,EAA0C;AAKrE,EAAA,OAAO,CAAC,EACN,IAAA,IACA,CAAC,aAAa,IAAI,CAAA,KACjB,YAAA,IAAgB,IAAA,IAAS,aAAa,IAAA,IAAQ,OAAO,IAAA,CAAK,OAAA,KAAY,cAAc,aAAA,IAAiB,IAAA,CAAA,CAAA;AAE1G;AAoBO,SAAS,sBAAsB,IAAA,EAAqC;AACzE,EAAA,IAAI,OAAO,IAAA,KAAS,QAAA,IAAY,IAAA,KAAS,MAAM,OAAO,KAAA;AACtD,EAAA,MAAM,CAAA,GAAI,IAAA;AACV,EAAA,MAAM,cAAA,GAAiB,CAAA,CAAE,IAAA,KAAS,kBAAA,IAAsB,EAAE,IAAA,KAAS,UAAA;AACnE,EAAA,OAAO,cAAA,IAAkB,OAAO,CAAA,CAAE,EAAA,KAAO,QAAA;AAC3C;AAKO,IAAM,cAAA,GAAiB;AAMvB,SAAS,oBAAoB,UAAA,EAA4B;AAC9D,EAAA,OAAO,UAAA,CAAW,MAAM,GAAG,CAAA,CAAE,MAAM,CAAC,CAAA,CAAE,KAAK,GAAG,CAAA;AAChD","file":"chunk-GRMC2OYN.js","sourcesContent":["import type { RequestContext } from '../request-context';\nimport { toStandardSchema, standardSchemaToJSONSchema } from '../schema';\nimport type { PublicSchema, StandardSchemaWithJSON, StandardSchemaIssue } from '../schema';\nimport { getZodTypeName, isZodArray, isZodObject, unwrapZodType } from '../utils/zod-utils';\n\n/**\n * Safely validates data against a Standard Schema.\n * Catches internal Zod errors (like undefined union options) and provides better error messages.\n *\n * @param schema The Standard Schema to validate against\n * @param data The data to validate\n * @returns The validation result or throws with a descriptive error\n */\nfunction safeValidate<T>(\n schema: StandardSchemaWithJSON<T>,\n data: unknown,\n): { value: T } | { issues: readonly StandardSchemaIssue[] } {\n try {\n const result = schema['~standard'].validate(data);\n if (result instanceof Promise) {\n throw new Error('Your schema is async, which is not supported. Please use a sync schema.');\n }\n return result as { value: T } | { issues: readonly StandardSchemaIssue[] };\n } catch (err) {\n // Catch Zod internal errors like \"Cannot read properties of undefined (reading 'run')\"\n // This happens when a union schema has undefined options\n if (err instanceof TypeError && err.message.includes('Cannot read properties of undefined')) {\n throw new Error(\n `Schema validation failed due to an invalid schema definition. ` +\n `This often happens when a union schema (z.union or z.or) has undefined options. ` +\n `Please check that all schema options are properly defined. Original error: ${err.message}`,\n );\n }\n throw err;\n }\n}\n\n/**\n * Formatted validation errors structure.\n * Contains `errors` array for messages at this level, and `fields` for nested field errors.\n */\nexport type FormattedValidationErrors<T = unknown> = {\n errors: string[];\n fields: T extends object ? { [K in keyof T]?: FormattedValidationErrors<T[K]> } : unknown;\n};\n\nexport interface ValidationError<T = unknown> {\n error: true;\n message: string;\n validationErrors: FormattedValidationErrors<T>;\n}\n/**\n * Extracts a string key from a path segment (handles both PropertyKey and PathSegment objects).\n */\nfunction getPathKey(segment: PropertyKey | { key: PropertyKey }): string {\n if (typeof segment === 'object' && segment !== null && 'key' in segment) {\n return String(segment.key);\n }\n return String(segment);\n}\n\n/**\n * Creates an empty FormattedValidationErrors object.\n */\nfunction createEmptyErrors(): { errors: string[]; fields: Record<string, unknown> } {\n return { errors: [], fields: {} };\n}\n\n/**\n * Builds a formatted errors object from standard schema validation issues.\n *\n * @param issues Array of validation issues from standard schema validation\n * @returns Formatted errors object with nested structure based on paths\n */\nfunction buildFormattedErrors<T>(issues: readonly StandardSchemaIssue[]): FormattedValidationErrors<T> {\n const result = createEmptyErrors();\n\n for (const issue of issues) {\n if (!issue.path || issue.path.length === 0) {\n // Root-level error\n result.errors.push(issue.message);\n } else {\n // Nested error - build path through fields\n let current = result;\n for (let i = 0; i < issue.path.length; i++) {\n const key = getPathKey(issue.path[i]!);\n if (i === issue.path.length - 1) {\n // Last segment - add the error message\n if (!current.fields[key]) {\n current.fields[key] = createEmptyErrors();\n }\n (current.fields[key] as { errors: string[]; fields: Record<string, unknown> }).errors.push(issue.message);\n } else {\n // Intermediate segment - ensure object exists\n if (!current.fields[key]) {\n current.fields[key] = createEmptyErrors();\n }\n current = current.fields[key] as { errors: string[]; fields: Record<string, unknown> };\n }\n }\n }\n }\n\n return result as FormattedValidationErrors<T>;\n}\n\n/**\n * Safely truncates data for error messages to avoid exposing sensitive information.\n * @param data The data to truncate\n * @param maxLength Maximum length of the truncated string (default: 200)\n * @returns Truncated string representation\n */\nfunction truncateForLogging(data: unknown, maxLength: number = 200): string {\n try {\n const stringified = JSON.stringify(data, null, 2);\n if (stringified.length <= maxLength) {\n return stringified;\n }\n return stringified.slice(0, maxLength) + '... (truncated)';\n } catch {\n return '[Unable to serialize data]';\n }\n}\n\n/**\n * Validates raw suspend data against a schema.\n *\n * @param schema The schema to validate against\n * @param suspendData The raw suspend data to validate\n * @param toolId Optional tool ID for better error messages\n * @returns The validated data or a validation error\n */\nexport function validateToolSuspendData<T = unknown>(\n schema: StandardSchemaWithJSON<T> | undefined,\n suspendData: unknown,\n toolId?: string,\n): { data: T; error?: undefined } | { data?: undefined; error: ValidationError<T> } {\n // If no schema, or schema is not a Standard Schema, return suspend data as-is\n if (!schema || !('~standard' in schema)) {\n return { data: suspendData as T };\n }\n\n // Validate the input using standard schema interface\n const validation = safeValidate(schema, suspendData);\n\n if ('value' in validation) {\n return { data: validation.value };\n }\n\n // Validation failed, return error\n const errorMessages = validation.issues.map(e => `- ${e.path?.join('.') || 'root'}: ${e.message}`).join('\\n');\n\n const error: ValidationError<T> = {\n error: true,\n message: `Tool suspension data validation failed${toolId ? ` for ${toolId}` : ''}. Please fix the following errors and try again:\\n${errorMessages}\\n\\nProvided arguments: ${truncateForLogging(suspendData)}`,\n validationErrors: buildFormattedErrors<T>(validation.issues),\n };\n\n return { error };\n}\n\n/**\n * Normalizes undefined/null input to an appropriate default value based on schema type.\n * This handles LLMs (Claude Sonnet 4.5, Gemini 2.4, etc.) that send undefined/null\n * instead of {} or [] when all parameters are optional.\n *\n * @param schema The Zod schema to check\n * @param input The input to normalize\n * @returns The normalized input (original value, {}, or [])\n */\nfunction normalizeNullishInput(schema: StandardSchemaWithJSON<any>, input: unknown): unknown {\n if (typeof input !== 'undefined' && input !== null) {\n return input;\n }\n\n const jsonSchema = standardSchemaToJSONSchema(schema, { io: 'input' });\n\n // Check if schema is an array type (using typeName to avoid dual-package hazard)\n if (jsonSchema.type === 'array') {\n return [];\n }\n\n // Check if schema is an object type (using typeName to avoid dual-package hazard)\n if (jsonSchema.type === 'object') {\n return {};\n }\n\n // For other schema types, return the original input and let Zod validate\n return input;\n}\n\n/**\n * Checks if a value is a plain object (created by {} or new Object()).\n * This excludes class instances, built-in objects like Date/Map/URL, etc.\n *\n * @param value The value to check\n * @returns true if the value is a plain object\n */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== 'object') {\n return false;\n }\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * Recursively converts undefined values to null in an object.\n * This is needed for OpenAI compat layers which convert .optional() to .nullable()\n * for strict mode compliance. When fields are omitted (undefined), we convert them\n * to null so the schema validation passes, and the transform then converts null back\n * to undefined. (GitHub #11457)\n *\n * Only recurses into plain objects to preserve class instances and built-in objects\n * like Date, Map, URL, etc. (GitHub #11502)\n *\n * @param input The input to process\n * @returns The processed input with undefined values converted to null\n */\nfunction convertUndefinedToNull(input: unknown): unknown {\n if (input === undefined) {\n return null;\n }\n\n if (input === null || typeof input !== 'object') {\n return input;\n }\n\n if (Array.isArray(input)) {\n return input.map(convertUndefinedToNull);\n }\n\n // Only recurse into plain objects - preserve class instances, built-in objects\n // (Date, Map, Set, URL, etc.) and any other non-plain objects\n if (!isPlainObject(input)) {\n return input;\n }\n\n // It's a plain object - recursively process all properties\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(input)) {\n result[key] = convertUndefinedToNull(value);\n }\n return result;\n}\n\n/**\n * Recursively strips null/undefined values from object properties.\n * This handles LLMs (e.g. Gemini) that send null for .optional() fields,\n * where Zod expects undefined, not null. By stripping nullish values,\n * we let Zod treat them as \"not provided\" which matches .optional() semantics.\n * (GitHub #12362)\n *\n * @param input The input to process\n * @returns The processed input with null/undefined values stripped from objects\n */\nfunction stripNullishValues(input: unknown): unknown {\n // Top-level null/undefined becomes undefined\n if (input === null || input === undefined) {\n return undefined;\n }\n\n if (typeof input !== 'object') {\n return input;\n }\n\n if (Array.isArray(input)) {\n // For arrays, recursively process elements but keep nulls in arrays\n // (array elements with null may be intentional)\n return input.map(item => (item === null ? null : stripNullishValues(item)));\n }\n\n // Only recurse into plain objects - preserve class instances, built-in objects\n if (!isPlainObject(input)) {\n return input;\n }\n\n // It's a plain object - recursively process all properties, omitting null/undefined values\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(input)) {\n if (value === null || value === undefined) {\n // Omit null/undefined values - equivalent to \"not provided\" for optional fields\n continue;\n }\n result[key] = stripNullishValues(value);\n }\n return result;\n}\n\n/**\n * Strip null/undefined values only at specific paths that caused validation errors.\n * Preserves null for .nullable() fields that are valid.\n */\nfunction stripNullishValuesAtPaths(input: unknown, paths: Set<string>, currentPath = ''): unknown {\n if (input === null || input === undefined) {\n return paths.has(currentPath) ? undefined : input;\n }\n\n if (typeof input !== 'object') {\n return input;\n }\n\n if (Array.isArray(input)) {\n return input.map((item, i) =>\n stripNullishValuesAtPaths(item, paths, currentPath ? `${currentPath}.${i}` : String(i)),\n );\n }\n\n if (!isPlainObject(input)) {\n return input;\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(input)) {\n const fieldPath = currentPath ? `${currentPath}.${key}` : key;\n if ((value === null || value === undefined) && paths.has(fieldPath)) {\n // Only omit null/undefined for fields that caused validation errors\n continue;\n }\n result[key] = stripNullishValuesAtPaths(value, paths, fieldPath);\n }\n return result;\n}\n\n/**\n * Gets the value at a path in a nested object, using the same path segment format\n * as Standard Schema validation issues.\n *\n * @param obj The object to traverse\n * @param pathSegments Array of path segments from a validation issue\n * @returns The value at the path, or a sentinel symbol if the path doesn't exist\n */\nconst PATH_NOT_FOUND = Symbol('PATH_NOT_FOUND');\nfunction getValueAtPath(obj: unknown, pathSegments: ReadonlyArray<PropertyKey | { key: PropertyKey }>): unknown {\n let current: unknown = obj;\n for (const segment of pathSegments) {\n if (current === null || current === undefined || typeof current !== 'object') {\n return PATH_NOT_FOUND;\n }\n const key =\n typeof segment === 'object' && segment !== null && 'key' in segment ? String(segment.key) : String(segment);\n current = (current as Record<string, unknown>)[key];\n }\n return current;\n}\n\n/**\n * Coerces stringified JSON values in object properties when the schema expects\n * an array or object but the LLM returned a JSON string.\n *\n * Some LLMs (e.g., GLM4.7) return stringified JSON for array/object parameters:\n * { \"args\": \"[\\\"parse_excel.py\\\"]\" }\n * instead of:\n * { \"args\": [\"parse_excel.py\"] }\n *\n * This function walks the top-level properties of a plain object and attempts\n * to JSON.parse string values when the schema expects a non-string type.\n * (GitHub #12757)\n *\n * @param schema The Zod schema to check field types against\n * @param input The input to process\n * @returns The input with stringified JSON values coerced, or the original input\n */\nfunction coerceStringifiedJsonValues(schema: StandardSchemaWithJSON<unknown>, input: unknown): unknown {\n // Only process plain objects with object schemas\n if (!isPlainObject(input)) {\n return input;\n }\n\n const unwrapped = unwrapZodType(schema as any);\n if (!isZodObject(unwrapped)) {\n return input;\n }\n\n const shape = (unwrapped as any).shape;\n if (!shape || typeof shape !== 'object') {\n return input;\n }\n\n let changed = false;\n const result: Record<string, unknown> = { ...input };\n\n for (const [key, value] of Object.entries(input)) {\n if (typeof value !== 'string') {\n continue;\n }\n\n const fieldSchema = shape[key];\n if (!fieldSchema) {\n continue;\n }\n\n // Unwrap the field schema to find the base type\n const baseFieldSchema = unwrapZodType(fieldSchema);\n\n // Only attempt coercion if the schema expects a non-string type\n // and the string looks like it could be JSON (starts with [ or {)\n if (getZodTypeName(baseFieldSchema) === 'ZodString') {\n continue;\n }\n\n const trimmed = value.trim();\n if (\n (isZodArray(baseFieldSchema) && trimmed.startsWith('[')) ||\n (isZodObject(baseFieldSchema) && trimmed.startsWith('{'))\n ) {\n try {\n const parsed = JSON.parse(value);\n if (\n (isZodArray(baseFieldSchema) && Array.isArray(parsed)) ||\n (isZodObject(baseFieldSchema) && isPlainObject(parsed))\n ) {\n result[key] = parsed;\n changed = true;\n }\n } catch {\n // Not valid JSON, leave as-is\n }\n }\n }\n\n return changed ? result : input;\n}\n\n/**\n * Validates raw input data against a schema.\n *\n * @param schema The schema to validate against (or undefined to skip validation)\n * @param input The raw input data to validate\n * @param toolId Optional tool ID for better error messages\n * @returns The validated data or a validation error\n */\nexport function validateToolInput<T = unknown>(\n schema: StandardSchemaWithJSON<T> | undefined,\n input: unknown,\n toolId?: string,\n): { data: T; error?: undefined } | { data?: undefined; error: ValidationError<T> } {\n // If no schema, or schema is not a Standard Schema (e.g. plain JSON Schema from Vercel tools),\n // return input as-is. Only validate when we have a proper Standard Schema with ~standard.validate.\n if (!schema || !('~standard' in schema)) {\n return { data: input as T };\n }\n\n // Validation pipeline:\n //\n // 1. normalizeNullishInput: Convert top-level null/undefined to {} or [] based on schema type.\n // Handles LLMs that send undefined instead of {} or [] for all-optional parameters.\n //\n // 2. convertUndefinedToNull: Convert undefined values to null in object properties.\n // Needed for OpenAI compat layers that convert .optional() to .nullable() for\n // strict mode compliance. The schema's transform converts null back to undefined.\n // (GitHub #11457)\n //\n // 3. First validation attempt with null values preserved. This handles .nullable()\n // schemas correctly (where null is a valid value).\n //\n // 4. If validation fails, retry with stringified JSON values coerced to their\n // proper types. Some LLMs (e.g. GLM4.7) return JSON arrays/objects as strings.\n // (GitHub #12757)\n //\n // 5. If validation still fails, retry with null values stripped from object properties.\n // This handles LLMs (e.g. Gemini) that send null for .optional() fields, where\n // Zod expects undefined, not null. (GitHub #12362)\n\n // Step 1: Normalize top-level null/undefined to appropriate default\n let normalizedInput = normalizeNullishInput(schema, input);\n\n // Step 2: Convert undefined values to null recursively (GitHub #11457)\n normalizedInput = convertUndefinedToNull(normalizedInput);\n\n // Step 3: Validate the normalized input\n const validation = safeValidate(schema, normalizedInput);\n\n if ('value' in validation) {\n return { data: validation.value };\n }\n\n // Step 4: Retry with stringified JSON values coerced (GitHub #12757)\n // LLMs like GLM4.7 send stringified JSON for array/object parameters, e.g.\n // { \"args\": \"[\\\"file.py\\\"]\" } instead of { \"args\": [\"file.py\"] }.\n const coercedInput = coerceStringifiedJsonValues(schema, normalizedInput);\n if (coercedInput !== normalizedInput) {\n const coercedValidation = safeValidate(schema, coercedInput);\n if ('value' in coercedValidation) {\n return { data: coercedValidation.value };\n }\n }\n\n // Step 5: Retry with null values stripped only for failing fields (GitHub #12362)\n // LLMs like Gemini send null for optional fields, but Zod's .optional() only\n // accepts undefined, not null. We only strip nulls for fields that caused\n // validation errors, preserving null for .nullable() schemas that need it.\n //\n // We detect null-related failures by checking the actual value at the failing\n // path rather than relying on error message string matching (GitHub #14476).\n // This ensures we catch null values regardless of the validator's error message\n // format (e.g., \"must be string\", \"must be object\", etc.).\n const failingNullPaths = new Set(\n validation.issues\n .filter(issue => {\n if (!issue.path || issue.path.length === 0) return false;\n const value = getValueAtPath(normalizedInput, issue.path);\n return value === null || value === undefined;\n })\n .map(issue => issue.path?.map(p => (typeof p === 'object' && 'key' in p ? String(p.key) : String(p))).join('.'))\n .filter((p): p is string => !!p),\n );\n const strippedInput =\n failingNullPaths.size > 0 ? stripNullishValuesAtPaths(input, failingNullPaths) : stripNullishValues(input);\n const normalizedStripped = normalizeNullishInput(schema, strippedInput);\n const retryValidation = safeValidate(schema, normalizedStripped);\n\n if ('value' in retryValidation) {\n return { data: retryValidation.value };\n }\n\n // All attempts failed - return the original (non-stripped) error since it's\n // more informative about what the schema actually expects\n const errorMessages = validation.issues.map(e => `- ${e.path?.join('.') || 'root'}: ${e.message}`).join('\\n');\n\n const error: ValidationError<T> = {\n error: true,\n message: `Tool input validation failed${toolId ? ` for ${toolId}` : ''}. Please fix the following errors and try again:\\n${errorMessages}\\n\\nProvided arguments: ${truncateForLogging(input)}`,\n validationErrors: buildFormattedErrors<T>(validation.issues),\n };\n\n return { error };\n}\n\n/**\n * Validates tool output data against a schema.\n *\n * @param schema The schema to validate against\n * @param output The output data to validate\n * @param toolId Optional tool ID for better error messages\n * @returns The validated data or a validation error\n */\nexport function validateToolOutput<T = unknown>(\n schema: StandardSchemaWithJSON<T> | undefined,\n output: unknown,\n toolId?: string,\n suspendCalled?: boolean,\n): { data: T; error?: undefined } | { data?: undefined; error: ValidationError<T> } {\n // If no schema, not a Standard Schema, or suspend was called, return output as-is\n if (!schema || !('~standard' in schema) || suspendCalled) {\n return { data: output as T };\n }\n\n // Validate the output using standard schema interface\n const validation = safeValidate(schema, output);\n\n if ('value' in validation) {\n return { data: validation.value };\n }\n\n // Validation failed, return error\n const errorMessages = validation.issues.map(e => `- ${e.path?.join('.') || 'root'}: ${e.message}`).join('\\n');\n\n const error: ValidationError<T> = {\n error: true,\n message: `Tool output validation failed${toolId ? ` for ${toolId}` : ''}. The tool returned invalid output:\\n${errorMessages}\\n\\nReturned output: ${truncateForLogging(output)}`,\n validationErrors: buildFormattedErrors<T>(validation.issues),\n };\n\n return { error };\n}\n\n/**\n * Keys that are considered sensitive and should be redacted in error messages.\n */\nconst SENSITIVE_KEYS = ['password', 'secret', 'token', 'apiKey', 'api_key', 'auth', 'credential'];\n\n/**\n * Redacts sensitive keys from an object for safe logging.\n * @param obj The object to redact\n * @returns A new object with sensitive values replaced with '[REDACTED]'\n */\nfunction redactSensitiveKeys(obj: unknown): unknown {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map(redactSensitiveKeys);\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (SENSITIVE_KEYS.some(sensitive => key.toLowerCase().includes(sensitive.toLowerCase()))) {\n result[key] = '[REDACTED]';\n } else if (typeof value === 'object' && value !== null) {\n result[key] = redactSensitiveKeys(value);\n } else {\n result[key] = value;\n }\n }\n return result;\n}\n\n/**\n * Validates request context data against a schema.\n * This is used to validate the request context before tool execution.\n *\n * @param schema The schema to validate against (PublicSchema which accepts Zod, JSONSchema, etc.)\n * @param requestContext The request context to validate\n * @param identifier Optional identifier (tool/step ID) for better error messages\n * @returns The validated data or a validation error\n */\nexport function validateRequestContext<T = any>(\n schema: PublicSchema<T> | undefined,\n requestContext: RequestContext | undefined,\n identifier?: string,\n): { data: T | Record<string, any>; error?: ValidationError<T> } {\n // If no schema, return request context values as-is\n if (!schema) {\n return { data: (requestContext?.all ?? {}) as T };\n }\n\n // Get the values from request context\n const contextValues = requestContext?.all ?? {};\n\n // Convert PublicSchema to StandardSchemaWithJSON for validation\n const standardSchema = toStandardSchema(schema);\n\n // Validate using standard schema interface\n const validation = standardSchema['~standard'].validate(contextValues);\n\n if (validation instanceof Promise) {\n throw new Error('Your schema is async, which is not supported. Please use a sync schema.');\n }\n\n if ('value' in validation) {\n return { data: validation.value };\n }\n\n // Validation failed, return error\n const errorMessages = validation.issues.map(e => `- ${e.path?.join('.') || 'root'}: ${e.message}`).join('\\n');\n\n // Redact sensitive keys before including in error message\n const redactedContext = redactSensitiveKeys(contextValues);\n\n const error: ValidationError<T> = {\n error: true,\n message: `Request context validation failed${identifier ? ` for ${identifier}` : ''}. Please fix the following errors and try again:\\n${errorMessages}\\n\\nProvided request context: ${truncateForLogging(redactedContext)}`,\n validationErrors: buildFormattedErrors<T>(validation.issues),\n };\n\n return { data: contextValues as T, error };\n}\n","import type { Mastra } from '../mastra';\nimport { RequestContext } from '../request-context';\nimport { toStandardSchema } from '../schema';\nimport type { PublicSchema, StandardSchemaWithJSON, InferPublicSchema } from '../schema';\nimport type { SuspendOptions } from '../workflows';\nimport type { McpMetadata, MCPToolProperties, ToolAction, ToolExecutionContext } from './types';\nimport { validateToolInput, validateToolOutput, validateToolSuspendData, validateRequestContext } from './validation';\n\n/**\n * Marker to identify Mastra tools even when `instanceof` fails.\n * This can happen in environments like Vite SSR where the same module\n * may be loaded multiple times, creating different class instances.\n * Uses Symbol.for() so the same symbol is shared across module copies.\n * Follows the naming convention: <org>.<product>.<category>.<className>\n */\nexport const MASTRA_TOOL_MARKER = Symbol.for('mastra.core.tool.Tool');\n\n/**\n * A type-safe tool that agents and workflows can call to perform specific actions.\n *\n * @template TSchemaIn - Input schema type\n * @template TSchemaOut - Output schema type\n * @template TSuspendSchema - Suspend operation schema type\n * @template TResumeSchema - Resume operation schema type\n * @template TContext - Execution context type\n *\n * @example Basic tool with validation\n * ```typescript\n * const weatherTool = createTool({\n * id: 'get-weather',\n * description: 'Get weather for a location',\n * inputSchema: z.object({\n * location: z.string(),\n * units: z.enum(['celsius', 'fahrenheit']).optional()\n * }),\n * execute: async (inputData) => {\n * return await fetchWeather(inputData.location, inputData.units);\n * }\n * });\n * ```\n *\n * @example Tool requiring approval\n * ```typescript\n * const deleteFileTool = createTool({\n * id: 'delete-file',\n * description: 'Delete a file',\n * requireApproval: true,\n * inputSchema: z.object({ filepath: z.string() }),\n * execute: async (inputData) => {\n * await fs.unlink(inputData.filepath);\n * return { deleted: true };\n * }\n * });\n * ```\n *\n * @example Tool with Mastra integration\n * ```typescript\n * const saveTool = createTool({\n * id: 'save-data',\n * description: 'Save data to storage',\n * inputSchema: z.object({ key: z.string(), value: z.any() }),\n * execute: async (inputData, context) => {\n * const storage = context?.mastra?.getStorage();\n * await storage?.set(inputData.key, inputData.value);\n * return { saved: true };\n * }\n * });\n * ```\n */\nexport class Tool<\n TSchemaIn = unknown,\n TSchemaOut = unknown,\n TSuspendSchema = unknown,\n TResumeSchema = unknown,\n TContext extends ToolExecutionContext<TSuspendSchema, TResumeSchema, any> = ToolExecutionContext<\n TSuspendSchema,\n TResumeSchema\n >,\n TId extends string = string,\n TRequestContext extends Record<string, any> | unknown = unknown,\n> implements ToolAction<TSchemaIn, TSchemaOut, TSuspendSchema, TResumeSchema, TContext, TId, TRequestContext> {\n /** Unique identifier for the tool */\n id: TId;\n\n /** Description of what the tool does */\n description: string;\n\n /** Schema for validating input parameters */\n inputSchema?: StandardSchemaWithJSON<TSchemaIn>;\n\n /** Schema for validating output structure */\n outputSchema?: StandardSchemaWithJSON<TSchemaOut>;\n\n /** Schema for suspend operation data */\n suspendSchema?: StandardSchemaWithJSON<TSuspendSchema>;\n\n /** Schema for resume operation data */\n resumeSchema?: StandardSchemaWithJSON<TResumeSchema>;\n\n /**\n * Schema for validating request context values.\n * When provided, the request context will be validated against this schema before tool execution.\n */\n requestContextSchema?: PublicSchema<TRequestContext>;\n\n /**\n * Tool execution function\n * @param inputData - The raw, validated input data\n * @param context - Optional execution context with metadata\n * @returns Promise resolving to tool output or a ValidationError if input validation fails\n */\n execute?: ToolAction<TSchemaIn, TSchemaOut, TSuspendSchema, TResumeSchema, TContext, TId, TRequestContext>['execute'];\n\n /** Parent Mastra instance for accessing shared resources */\n mastra?: Mastra;\n\n /**\n * Whether the tool requires explicit user approval before execution\n * @example\n * ```typescript\n * // For destructive operations\n * requireApproval: true\n * ```\n */\n requireApproval?: boolean;\n\n /**\n * Provider-specific options passed to the model when this tool is used.\n * Keys are provider names (e.g., 'anthropic', 'openai'), values are provider-specific configs.\n * @example\n * ```typescript\n * providerOptions: {\n * anthropic: {\n * cacheControl: { type: 'ephemeral' }\n * }\n * }\n * ```\n */\n providerOptions?: Record<string, Record<string, unknown>>;\n\n /**\n * Optional function to transform the tool's raw output before sending it to the model.\n * The raw result is still available for application logic; only the model sees the transformed version.\n */\n toModelOutput?: (output: TSchemaOut) => unknown;\n\n /**\n * Optional MCP-specific properties including annotations and metadata.\n * Only relevant when the tool is being used in an MCP context.\n * @example\n * ```typescript\n * mcp: {\n * annotations: {\n * title: 'Weather Lookup',\n * readOnlyHint: true,\n * destructiveHint: false\n * },\n * _meta: {\n * version: '1.0.0',\n * author: 'team@example.com'\n * }\n * }\n * ```\n */\n mcp?: MCPToolProperties;\n\n onInputStart?: ToolAction<\n TSchemaIn,\n TSchemaOut,\n TSuspendSchema,\n TResumeSchema,\n TContext,\n TId,\n TRequestContext\n >['onInputStart'];\n onInputDelta?: ToolAction<\n TSchemaIn,\n TSchemaOut,\n TSuspendSchema,\n TResumeSchema,\n TContext,\n TId,\n TRequestContext\n >['onInputDelta'];\n onInputAvailable?: ToolAction<\n TSchemaIn,\n TSchemaOut,\n TSuspendSchema,\n TResumeSchema,\n TContext,\n TId,\n TRequestContext\n >['onInputAvailable'];\n onOutput?: ToolAction<\n TSchemaIn,\n TSchemaOut,\n TSuspendSchema,\n TResumeSchema,\n TContext,\n TId,\n TRequestContext\n >['onOutput'];\n\n /**\n * Examples of valid tool inputs passed through to the AI SDK.\n */\n inputExamples?: Array<{ input: Record<string, unknown> }>;\n\n /**\n * Metadata identifying this tool as originating from an MCP server.\n * Set automatically by the MCP client when creating tools.\n */\n mcpMetadata?: McpMetadata;\n\n /**\n * Creates a new Tool instance with input validation wrapper.\n *\n * @param opts - Tool configuration and execute function\n * @example\n * ```typescript\n * const tool = new Tool({\n * id: 'my-tool',\n * description: 'Does something useful',\n * inputSchema: z.object({ name: z.string() }),\n * execute: async (inputData) => ({ greeting: `Hello ${inputData.name}` })\n * });\n * ```\n */\n constructor(opts: ToolAction<TSchemaIn, TSchemaOut, TSuspendSchema, TResumeSchema, TContext, TId, TRequestContext>) {\n (this as any)[MASTRA_TOOL_MARKER] = true;\n this.id = opts.id;\n this.description = opts.description;\n this.inputSchema = opts.inputSchema ? toStandardSchema(opts.inputSchema) : undefined;\n this.outputSchema = opts.outputSchema ? toStandardSchema(opts.outputSchema) : undefined;\n this.suspendSchema = opts.suspendSchema ? toStandardSchema(opts.suspendSchema) : undefined;\n this.resumeSchema = opts.resumeSchema ? toStandardSchema(opts.resumeSchema) : undefined;\n this.requestContextSchema = opts.requestContextSchema;\n this.mastra = opts.mastra;\n this.requireApproval = opts.requireApproval || false;\n this.providerOptions = opts.providerOptions;\n this.toModelOutput = opts.toModelOutput;\n this.inputExamples = opts.inputExamples;\n this.mcp = opts.mcp;\n this.mcpMetadata = opts.mcpMetadata;\n this.onInputStart = opts.onInputStart;\n this.onInputDelta = opts.onInputDelta;\n this.onInputAvailable = opts.onInputAvailable;\n this.onOutput = opts.onOutput;\n\n // Tools receive two parameters:\n // 1. input - The raw, validated input data\n // 2. context - Execution metadata (mastra, suspend, etc.)\n if (opts.execute) {\n const originalExecute = opts.execute;\n this.execute = async (inputData: TSchemaIn, context?: any) => {\n // Validate input if schema exists\n const { data, error } = validateToolInput(this.inputSchema, inputData, this.id);\n if (error) {\n return error;\n }\n\n // Validate request context if schema exists\n const { error: requestContextError } = validateRequestContext(\n this.requestContextSchema,\n context?.requestContext,\n this.id,\n );\n if (requestContextError) {\n return requestContextError as any;\n }\n\n let suspendData = null;\n\n const baseContext = context\n ? {\n ...context,\n ...(context.suspend\n ? {\n suspend: (args: any, suspendOptions?: SuspendOptions) => {\n suspendData = args;\n return context.suspend?.(args, suspendOptions);\n },\n }\n : {}),\n }\n : {};\n\n // Organize context based on execution source\n let organizedContext = baseContext;\n if (!context) {\n // No context provided - create a minimal context with requestContext\n organizedContext = {\n requestContext: new RequestContext(),\n mastra: undefined,\n };\n } else {\n // Check if this is agent execution (has toolCallId and messages)\n const isAgentExecution = baseContext.toolCallId && baseContext.messages;\n\n // Check if this is workflow execution (has workflow properties)\n // Agent execution takes precedence - don't treat as workflow if it's an agent call\n const isWorkflowExecution = !isAgentExecution && (baseContext.workflow || baseContext.workflowId);\n\n if (isAgentExecution && !baseContext.agent) {\n // Reorganize agent context - nest agent-specific properties under 'agent' key\n const {\n agentId,\n toolCallId,\n messages,\n suspend,\n resumeData,\n threadId,\n resourceId,\n writableStream,\n ...rest\n } = baseContext;\n organizedContext = {\n ...rest,\n agent: {\n agentId: agentId || '',\n toolCallId,\n messages,\n suspend,\n resumeData,\n threadId,\n resourceId,\n writableStream,\n },\n // Ensure requestContext is always present\n requestContext: rest.requestContext || new RequestContext(),\n };\n } else if (isWorkflowExecution && !baseContext.workflow) {\n // Reorganize workflow context - nest workflow-specific properties under 'workflow' key\n const { workflowId, runId, state, setState, suspend, resumeData, ...rest } = baseContext;\n organizedContext = {\n ...rest,\n workflow: {\n workflowId,\n runId,\n state,\n setState,\n suspend,\n resumeData,\n },\n // Ensure requestContext is always present\n requestContext: rest.requestContext || new RequestContext(),\n };\n } else {\n // Ensure requestContext is always present even for direct execution\n organizedContext = {\n ...baseContext,\n agent: baseContext.agent\n ? {\n ...baseContext.agent,\n agentId: baseContext.agent.agentId ?? '',\n suspend: (args: any, suspendOptions?: SuspendOptions) => {\n suspendData = args;\n return baseContext.agent?.suspend?.(args, suspendOptions);\n },\n }\n : baseContext.agent,\n workflow: baseContext.workflow\n ? {\n ...baseContext.workflow,\n suspend: (args: any, suspendOptions?: SuspendOptions) => {\n suspendData = args;\n return baseContext.workflow?.suspend?.(args, suspendOptions);\n },\n }\n : baseContext.workflow,\n requestContext: baseContext.requestContext || new RequestContext(),\n };\n }\n }\n\n const resumeData =\n organizedContext.agent?.resumeData ?? organizedContext.workflow?.resumeData ?? organizedContext?.resumeData;\n\n if (resumeData) {\n const resumeValidation = validateToolInput(this.resumeSchema, resumeData, this.id);\n if (resumeValidation.error) {\n return resumeValidation.error as any;\n }\n }\n\n // Call the original execute with validated input and organized context\n const output = await originalExecute(data as any, organizedContext);\n\n if (suspendData) {\n const suspendValidation = validateToolSuspendData(this.suspendSchema, suspendData, this.id);\n if (suspendValidation.error) {\n return suspendValidation.error as any;\n }\n }\n\n const skiptOutputValidation = !!(typeof output === 'undefined' && suspendData);\n\n // Validate output if schema exists\n const outputValidation = validateToolOutput(this.outputSchema, output, this.id, skiptOutputValidation);\n\n if (outputValidation.error) {\n return outputValidation.error as any;\n }\n\n return outputValidation.data;\n };\n }\n }\n}\n\n/**\n * Creates a type-safe tool with automatic input validation.\n *\n * @template TSchemaIn - Input schema type\n * @template TSchemaOut - Output schema type\n * @template TSuspendSchema - Suspend operation schema type\n * @template TResumeSchema - Resume operation schema type\n * @template TContext - Execution context type\n * @template TExecute - Execute function type\n *\n * @param opts - Tool configuration including schemas and execute function\n * @returns Type-safe Tool instance with conditional typing based on schemas\n *\n * @example Simple tool\n * ```typescript\n * const greetTool = createTool({\n * id: 'greet',\n * description: 'Say hello',\n * execute: async () => ({ message: 'Hello!' })\n * });\n * ```\n *\n * @example Tool with input validation\n * ```typescript\n * const calculateTool = createTool({\n * id: 'calculate',\n * description: 'Perform calculations',\n * inputSchema: z.object({\n * operation: z.enum(['add', 'subtract']),\n * a: z.number(),\n * b: z.number()\n * }),\n * execute: async (inputData) => {\n * const result = inputData.operation === 'add'\n * ? inputData.a + inputData.b\n * : inputData.a - inputData.b;\n * return { result };\n * }\n * });\n * ```\n *\n * @example Tool with output schema\n * ```typescript\n * const userTool = createTool({\n * id: 'get-user',\n * description: 'Get user data',\n * inputSchema: z.object({ userId: z.string() }),\n * outputSchema: z.object({\n * id: z.string(),\n * name: z.string(),\n * email: z.string()\n * }),\n * execute: async (inputData) => {\n * return await fetchUser(inputData.userId);\n * }\n * });\n * ```\n *\n * @example Tool with external API\n * ```typescript\n * const weatherTool = createTool({\n * id: 'weather',\n * description: 'Get weather data',\n * inputSchema: z.object({\n * city: z.string(),\n * units: z.enum(['metric', 'imperial']).default('metric')\n * }),\n * execute: async (inputData) => {\n * const response = await fetch(\n * `https://api.weather.com/v1/weather?q=${inputData.city}&units=${inputData.units}`\n * );\n * return response.json();\n * }\n * });\n * ```\n */\ntype SchemaLike = PublicSchema<any> | undefined;\ntype InferSchema<T extends SchemaLike> = T extends PublicSchema<any> ? InferPublicSchema<T> : unknown;\n\ntype CreateToolOpts<\n TId extends string,\n TInputSchema extends SchemaLike,\n TOutputSchema extends SchemaLike,\n TSuspendSchema extends SchemaLike,\n TResumeSchema extends SchemaLike,\n TRequestContext,\n TContext extends ToolExecutionContext<InferSchema<TSuspendSchema>, InferSchema<TResumeSchema>, TRequestContext>,\n> = Omit<\n ToolAction<\n InferSchema<TInputSchema>,\n InferSchema<TOutputSchema>,\n InferSchema<TSuspendSchema>,\n InferSchema<TResumeSchema>,\n TContext,\n TId,\n TRequestContext\n >,\n 'inputSchema' | 'outputSchema' | 'suspendSchema' | 'resumeSchema'\n> & {\n inputSchema?: TInputSchema;\n outputSchema?: TOutputSchema;\n suspendSchema?: TSuspendSchema;\n resumeSchema?: TResumeSchema;\n};\nexport function createTool<\n TId extends string = string,\n TInputSchema extends SchemaLike = undefined,\n TOutputSchema extends SchemaLike = undefined,\n TSuspendSchema extends SchemaLike = undefined,\n TResumeSchema extends SchemaLike = undefined,\n TRequestContext extends Record<string, any> | unknown = unknown,\n TContext extends ToolExecutionContext<InferSchema<TSuspendSchema>, InferSchema<TResumeSchema>, TRequestContext> =\n ToolExecutionContext<InferSchema<TSuspendSchema>, InferSchema<TResumeSchema>, TRequestContext>,\n>(\n opts: CreateToolOpts<TId, TInputSchema, TOutputSchema, TSuspendSchema, TResumeSchema, TRequestContext, TContext>,\n): Tool<\n InferSchema<TInputSchema>,\n InferSchema<TOutputSchema>,\n InferSchema<TSuspendSchema>,\n InferSchema<TResumeSchema>,\n TContext,\n TId,\n TRequestContext\n> {\n return new Tool(opts);\n}\n","import { Tool, MASTRA_TOOL_MARKER } from './tool';\nimport type { ToolToConvert } from './tool-builder/builder';\nimport type { VercelTool } from './types';\n\n/**\n * Checks if a tool is a Mastra Tool, using both instanceof and marker.\n * The marker fallback handles environments like Vite SSR where the same\n * module may be loaded multiple times, causing instanceof to fail.\n */\nexport function isMastraTool(tool: unknown): boolean {\n return tool instanceof Tool || (typeof tool === 'object' && tool !== null && MASTRA_TOOL_MARKER in tool);\n}\n\n/**\n * Checks if a tool is a Vercel Tool (AI SDK tool)\n * @param tool - The tool to check\n * @returns True if the tool is a Vercel Tool, false otherwise\n */\nexport function isVercelTool(tool?: ToolToConvert): tool is VercelTool {\n // Checks if this tool is not an instance of Mastra's Tool class\n // AI SDK tools must have an execute function and either:\n // - 'parameters' (v4) or 'inputSchema' (v5/v6)\n // This prevents plain objects with inputSchema (like client tools) from being treated as VercelTools\n return !!(\n tool &&\n !isMastraTool(tool) &&\n ('parameters' in tool || ('execute' in tool && typeof tool.execute === 'function' && 'inputSchema' in tool))\n );\n}\n\ntype ProviderTool = {\n type: 'provider-defined' | 'provider';\n id: string;\n args?: Record<string, unknown>;\n inputSchema?: unknown;\n outputSchema?: unknown;\n requestContextSchema?: unknown;\n};\n\n/**\n * Checks if a tool is a provider-defined tool from the AI SDK.\n * Provider tools (like google.tools.googleSearch(), openai.tools.webSearch()) have:\n * - type: \"provider-defined\" (AI SDK v5) or \"provider\" (AI SDK v6)\n * - id: in format 'provider.tool_name' (e.g., 'google.google_search')\n *\n * These tools have a lazy `inputSchema` function that returns an AI SDK Schema\n * (not a Zod schema), so they require special handling during serialization.\n */\nexport function isProviderDefinedTool(tool: unknown): tool is ProviderTool {\n if (typeof tool !== 'object' || tool === null) return false;\n const t = tool as Record<string, unknown>;\n const isProviderType = t.type === 'provider-defined' || t.type === 'provider';\n return isProviderType && typeof t.id === 'string';\n}\n\n/**\n * Alias for callers that prefer the shorter provider-tool terminology.\n */\nexport const isProviderTool = isProviderDefinedTool;\n\n/**\n * Extracts the model-facing tool name from a provider tool id.\n * e.g. 'openai.web_search' -> 'web_search'\n */\nexport function getProviderToolName(providerId: string): string {\n return providerId.split('.').slice(1).join('.');\n}\n"]}