@mastra/core 1.0.0-beta.1 → 1.0.0-beta.11
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.
- package/CHANGELOG.md +1218 -0
- package/dist/agent/agent-legacy.d.ts +35 -30
- package/dist/agent/agent-legacy.d.ts.map +1 -1
- package/dist/agent/agent-types.test-d.d.ts +2 -0
- package/dist/agent/agent-types.test-d.d.ts.map +1 -0
- package/dist/agent/agent.d.ts +24 -9
- package/dist/agent/agent.d.ts.map +1 -1
- package/dist/agent/agent.types.d.ts +17 -9
- package/dist/agent/agent.types.d.ts.map +1 -1
- package/dist/agent/index.cjs +9 -9
- package/dist/agent/index.js +2 -2
- package/dist/agent/message-list/index.cjs +3 -3
- package/dist/agent/message-list/index.d.ts +61 -3
- package/dist/agent/message-list/index.d.ts.map +1 -1
- package/dist/agent/message-list/index.js +1 -1
- package/dist/agent/message-list/prompt/attachments-to-parts.d.ts.map +1 -1
- package/dist/agent/message-list/prompt/convert-file.d.ts +1 -1
- package/dist/agent/message-list/prompt/convert-file.d.ts.map +1 -1
- package/dist/agent/message-list/prompt/download-assets.d.ts.map +1 -1
- package/dist/agent/save-queue/index.d.ts +3 -1
- package/dist/agent/save-queue/index.d.ts.map +1 -1
- package/dist/agent/test-utils.d.ts +37 -0
- package/dist/agent/test-utils.d.ts.map +1 -1
- package/dist/agent/trip-wire.d.ts +38 -4
- package/dist/agent/trip-wire.d.ts.map +1 -1
- package/dist/agent/types.d.ts +46 -14
- package/dist/agent/types.d.ts.map +1 -1
- package/dist/agent/utils.d.ts +4 -5
- package/dist/agent/utils.d.ts.map +1 -1
- package/dist/agent/workflows/prepare-stream/index.d.ts +37 -13
- package/dist/agent/workflows/prepare-stream/index.d.ts.map +1 -1
- package/dist/agent/workflows/prepare-stream/map-results-step.d.ts +3 -3
- package/dist/agent/workflows/prepare-stream/map-results-step.d.ts.map +1 -1
- package/dist/agent/workflows/prepare-stream/prepare-memory-step.d.ts +34 -11
- package/dist/agent/workflows/prepare-stream/prepare-memory-step.d.ts.map +1 -1
- package/dist/agent/workflows/prepare-stream/prepare-tools-step.d.ts +2 -1
- package/dist/agent/workflows/prepare-stream/prepare-tools-step.d.ts.map +1 -1
- package/dist/agent/workflows/prepare-stream/schema.d.ts +38 -15
- package/dist/agent/workflows/prepare-stream/schema.d.ts.map +1 -1
- package/dist/agent/workflows/prepare-stream/stream-step.d.ts +11 -1
- package/dist/agent/workflows/prepare-stream/stream-step.d.ts.map +1 -1
- package/dist/base.cjs +2 -2
- package/dist/base.js +1 -1
- package/dist/bundler/index.cjs +2 -2
- package/dist/bundler/index.js +1 -1
- package/dist/cache/index.cjs +3 -3
- package/dist/cache/index.js +1 -1
- package/dist/{chunk-JUBFO5J3.js → chunk-2ULLRN4Y.js} +16333 -11839
- package/dist/chunk-2ULLRN4Y.js.map +1 -0
- package/dist/{chunk-OJNJA5ZI.js → chunk-3CKZSDTQ.js} +3 -3
- package/dist/{chunk-OJNJA5ZI.js.map → chunk-3CKZSDTQ.js.map} +1 -1
- package/dist/chunk-3E3ILV6T.cjs +518 -0
- package/dist/chunk-3E3ILV6T.cjs.map +1 -0
- package/dist/{chunk-TQTAMPSC.js → chunk-3N3QE4ZK.js} +3 -3
- package/dist/chunk-3N3QE4ZK.js.map +1 -0
- package/dist/{chunk-QUKUN6NR.cjs → chunk-4JKEUSCC.cjs} +107 -7
- package/dist/chunk-4JKEUSCC.cjs.map +1 -0
- package/dist/{chunk-MSWTA73A.cjs → chunk-52RSUALV.cjs} +16490 -11957
- package/dist/chunk-52RSUALV.cjs.map +1 -0
- package/dist/chunk-5PAEYE3Q.js +513 -0
- package/dist/chunk-5PAEYE3Q.js.map +1 -0
- package/dist/{chunk-ECFXGXWO.cjs → chunk-5Q6WAYEY.cjs} +695 -375
- package/dist/chunk-5Q6WAYEY.cjs.map +1 -0
- package/dist/{chunk-CBAB7GOD.cjs → chunk-6BJ7XHRH.cjs} +2 -2
- package/dist/{chunk-CBAB7GOD.cjs.map → chunk-6BJ7XHRH.cjs.map} +1 -1
- package/dist/{chunk-GRBGQ2GE.js → chunk-6TBWJV35.js} +5 -3
- package/dist/chunk-6TBWJV35.js.map +1 -0
- package/dist/chunk-6XCINXZ7.cjs +194 -0
- package/dist/chunk-6XCINXZ7.cjs.map +1 -0
- package/dist/{chunk-E7K4FTLN.cjs → chunk-72YCRTEX.cjs} +18 -2
- package/dist/chunk-72YCRTEX.cjs.map +1 -0
- package/dist/{chunk-W7UH2PWL.js → chunk-7P6BNIJH.js} +1142 -331
- package/dist/chunk-7P6BNIJH.js.map +1 -0
- package/dist/{chunk-76K3IYWM.js → chunk-ADADLFDR.js} +3 -3
- package/dist/{chunk-76K3IYWM.js.map → chunk-ADADLFDR.js.map} +1 -1
- package/dist/{chunk-DSNPWVIG.cjs → chunk-AF74UXR5.cjs} +4 -3
- package/dist/chunk-AF74UXR5.cjs.map +1 -0
- package/dist/{chunk-GGYKYORQ.cjs → chunk-BJXKH4LG.cjs} +407 -22
- package/dist/chunk-BJXKH4LG.cjs.map +1 -0
- package/dist/{chunk-2ZVKF4HP.cjs → chunk-BUKY6CTR.cjs} +1147 -334
- package/dist/chunk-BUKY6CTR.cjs.map +1 -0
- package/dist/chunk-BWYU7D33.js +192 -0
- package/dist/chunk-BWYU7D33.js.map +1 -0
- package/dist/{chunk-XEVG546F.js → chunk-C36YRTZ6.js} +178 -12
- package/dist/chunk-C36YRTZ6.js.map +1 -0
- package/dist/{chunk-CB575O6L.cjs → chunk-CZEJQSWB.cjs} +473 -124
- package/dist/chunk-CZEJQSWB.cjs.map +1 -0
- package/dist/chunk-DD2VNRQM.js +62 -0
- package/dist/chunk-DD2VNRQM.js.map +1 -0
- package/dist/{chunk-KEXGB7FK.cjs → chunk-DGV2FWB4.cjs} +7 -7
- package/dist/{chunk-KEXGB7FK.cjs.map → chunk-DGV2FWB4.cjs.map} +1 -1
- package/dist/{chunk-Y63IFHEZ.cjs → chunk-EOPEDKLG.cjs} +4 -4
- package/dist/chunk-EOPEDKLG.cjs.map +1 -0
- package/dist/{chunk-UIZSWUKP.js → chunk-F2GAJSBI.js} +105 -7
- package/dist/chunk-F2GAJSBI.js.map +1 -0
- package/dist/{chunk-4CDL2QJT.js → chunk-IVV5TOMD.js} +122 -37
- package/dist/chunk-IVV5TOMD.js.map +1 -0
- package/dist/{chunk-MV7KHWUT.js → chunk-JIGDJK2O.js} +391 -15
- package/dist/chunk-JIGDJK2O.js.map +1 -0
- package/dist/chunk-KJBMTK5B.cjs +64 -0
- package/dist/chunk-KJBMTK5B.cjs.map +1 -0
- package/dist/{chunk-S6URFGCZ.js → chunk-LSHPJWM5.js} +3 -3
- package/dist/{chunk-S6URFGCZ.js.map → chunk-LSHPJWM5.js.map} +1 -1
- package/dist/chunk-MGCGWPQJ.cjs +275 -0
- package/dist/chunk-MGCGWPQJ.cjs.map +1 -0
- package/dist/chunk-MRFUISXC.cjs +4981 -0
- package/dist/chunk-MRFUISXC.cjs.map +1 -0
- package/dist/{chunk-KJ2SW6VA.js → chunk-NRUZYMHE.js} +4 -3
- package/dist/chunk-NRUZYMHE.js.map +1 -0
- package/dist/{chunk-CINNK34N.js → chunk-O2BJW7YA.js} +26 -11
- package/dist/chunk-O2BJW7YA.js.map +1 -0
- package/dist/chunk-OEIVMCWX.js +4959 -0
- package/dist/chunk-OEIVMCWX.js.map +1 -0
- package/dist/{chunk-WM6CK2F3.cjs → chunk-PG5H6QIO.cjs} +131 -49
- package/dist/chunk-PG5H6QIO.cjs.map +1 -0
- package/dist/{chunk-JPGVRWWL.js → chunk-PK2A5WBG.js} +472 -125
- package/dist/chunk-PK2A5WBG.js.map +1 -0
- package/dist/{chunk-X7JMA3IY.js → chunk-PSCMWPLC.js} +2 -2
- package/dist/{chunk-X7JMA3IY.js.map → chunk-PSCMWPLC.js.map} +1 -1
- package/dist/{chunk-VOY2RXOC.cjs → chunk-S73Z3PBJ.cjs} +182 -15
- package/dist/chunk-S73Z3PBJ.cjs.map +1 -0
- package/dist/{chunk-MA7TEM62.cjs → chunk-SCUWP4II.cjs} +769 -27
- package/dist/chunk-SCUWP4II.cjs.map +1 -0
- package/dist/{chunk-JV2KH24V.js → chunk-SXNQRJQD.js} +695 -375
- package/dist/chunk-SXNQRJQD.js.map +1 -0
- package/dist/{chunk-BMAFVZ2D.cjs → chunk-T2VLUFGG.cjs} +4 -4
- package/dist/{chunk-BMAFVZ2D.cjs.map → chunk-T2VLUFGG.cjs.map} +1 -1
- package/dist/chunk-THZTRBFS.js +268 -0
- package/dist/chunk-THZTRBFS.js.map +1 -0
- package/dist/{chunk-VOQ3ULMT.js → chunk-U3XOLEPX.js} +759 -17
- package/dist/chunk-U3XOLEPX.js.map +1 -0
- package/dist/{chunk-Y6ROD72V.cjs → chunk-UIGRFDO6.cjs} +4 -4
- package/dist/{chunk-Y6ROD72V.cjs.map → chunk-UIGRFDO6.cjs.map} +1 -1
- package/dist/{chunk-H6CZGPZD.js → chunk-US2U7ECW.js} +179 -38
- package/dist/chunk-US2U7ECW.js.map +1 -0
- package/dist/{chunk-J7O6WENZ.cjs → chunk-UVHSM2GU.cjs} +6 -2
- package/dist/chunk-UVHSM2GU.cjs.map +1 -0
- package/dist/{chunk-CD56CXVE.cjs → chunk-WTSZBHIZ.cjs} +32 -17
- package/dist/chunk-WTSZBHIZ.cjs.map +1 -0
- package/dist/{chunk-KIZIOFZC.js → chunk-Y36Y5MTD.js} +17 -3
- package/dist/chunk-Y36Y5MTD.js.map +1 -0
- package/dist/{chunk-DNEURYF3.cjs → chunk-YC6PJEPH.cjs} +206 -65
- package/dist/chunk-YC6PJEPH.cjs.map +1 -0
- package/dist/{chunk-IQO7ANVS.cjs → chunk-YWMMBIOM.cjs} +21 -20
- package/dist/chunk-YWMMBIOM.cjs.map +1 -0
- package/dist/{chunk-I4CXL4SR.js → chunk-Z57R5WS4.js} +16 -15
- package/dist/chunk-Z57R5WS4.js.map +1 -0
- package/dist/deployer/index.cjs +2 -2
- package/dist/deployer/index.js +1 -1
- package/dist/di/index.cjs +10 -2
- package/dist/di/index.d.ts +1 -1
- package/dist/di/index.d.ts.map +1 -1
- package/dist/di/index.js +1 -1
- package/dist/evals/base.d.ts +10 -2
- package/dist/evals/base.d.ts.map +1 -1
- package/dist/evals/base.test-utils.d.ts +25 -25
- package/dist/evals/index.cjs +9 -9
- package/dist/evals/index.js +2 -2
- package/dist/evals/scoreTraces/index.cjs +7 -6
- package/dist/evals/scoreTraces/index.cjs.map +1 -1
- package/dist/evals/scoreTraces/index.js +4 -3
- package/dist/evals/scoreTraces/index.js.map +1 -1
- package/dist/evals/scoreTraces/scoreTracesWorkflow.d.ts.map +1 -1
- package/dist/evals/types.d.ts +25 -24
- package/dist/evals/types.d.ts.map +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.js +1 -1
- package/dist/integration/index.cjs +2 -2
- package/dist/integration/index.js +1 -1
- package/dist/llm/index.cjs +30 -10
- package/dist/llm/index.d.ts +2 -0
- package/dist/llm/index.d.ts.map +1 -1
- package/dist/llm/index.js +5 -1
- package/dist/llm/model/aisdk/v5/model.d.ts +47 -0
- package/dist/llm/model/aisdk/v5/model.d.ts.map +1 -0
- package/dist/llm/model/base.types.d.ts +2 -2
- package/dist/llm/model/base.types.d.ts.map +1 -1
- package/dist/llm/model/gateway-resolver.d.ts.map +1 -1
- package/dist/llm/model/gateways/azure.d.ts +36 -0
- package/dist/llm/model/gateways/azure.d.ts.map +1 -0
- package/dist/llm/model/gateways/base.d.ts +9 -4
- package/dist/llm/model/gateways/base.d.ts.map +1 -1
- package/dist/llm/model/gateways/constants.d.ts.map +1 -1
- package/dist/llm/model/gateways/index.d.ts +4 -1
- package/dist/llm/model/gateways/index.d.ts.map +1 -1
- package/dist/llm/model/gateways/models-dev.d.ts +3 -2
- package/dist/llm/model/gateways/models-dev.d.ts.map +1 -1
- package/dist/llm/model/gateways/netlify.d.ts +4 -3
- package/dist/llm/model/gateways/netlify.d.ts.map +1 -1
- package/dist/llm/model/is-v2-model.d.ts +3 -0
- package/dist/llm/model/is-v2-model.d.ts.map +1 -0
- package/dist/llm/model/model-method-from-agent.d.ts +4 -0
- package/dist/llm/model/model-method-from-agent.d.ts.map +1 -0
- package/dist/llm/model/model.d.ts.map +1 -1
- package/dist/llm/model/model.loop.d.ts +2 -2
- package/dist/llm/model/model.loop.d.ts.map +1 -1
- package/dist/llm/model/model.loop.types.d.ts +4 -2
- package/dist/llm/model/model.loop.types.d.ts.map +1 -1
- package/dist/llm/model/provider-options.d.ts +4 -1
- package/dist/llm/model/provider-options.d.ts.map +1 -1
- package/dist/llm/model/provider-registry.d.ts +11 -1
- package/dist/llm/model/provider-registry.d.ts.map +1 -1
- package/dist/llm/model/provider-types.generated.d.ts +489 -27
- package/dist/llm/model/registry-generator.d.ts +12 -0
- package/dist/llm/model/registry-generator.d.ts.map +1 -1
- package/dist/llm/model/resolve-model.d.ts +1 -1
- package/dist/llm/model/resolve-model.d.ts.map +1 -1
- package/dist/llm/model/router.d.ts +12 -5
- package/dist/llm/model/router.d.ts.map +1 -1
- package/dist/llm/model/shared.types.d.ts +17 -6
- package/dist/llm/model/shared.types.d.ts.map +1 -1
- package/dist/logger/constants.d.ts +1 -0
- package/dist/logger/constants.d.ts.map +1 -1
- package/dist/logger/index.cjs +11 -11
- package/dist/logger/index.js +2 -2
- package/dist/logger/transport.d.ts +1 -1
- package/dist/logger/transport.d.ts.map +1 -1
- package/dist/loop/index.cjs +2 -2
- package/dist/loop/index.js +1 -1
- package/dist/loop/loop.d.ts.map +1 -1
- package/dist/loop/network/index.d.ts.map +1 -1
- package/dist/loop/test-utils/MastraLanguageModelV2Mock.d.ts +37 -0
- package/dist/loop/test-utils/MastraLanguageModelV2Mock.d.ts.map +1 -0
- package/dist/loop/test-utils/fullStream.d.ts.map +1 -1
- package/dist/loop/test-utils/generateText.d.ts.map +1 -1
- package/dist/loop/test-utils/options.d.ts.map +1 -1
- package/dist/loop/test-utils/resultObject.d.ts.map +1 -1
- package/dist/loop/test-utils/streamObject.d.ts.map +1 -1
- package/dist/loop/test-utils/textStream.d.ts.map +1 -1
- package/dist/loop/test-utils/toUIMessageStream.d.ts.map +1 -1
- package/dist/loop/test-utils/tools.d.ts.map +1 -1
- package/dist/loop/test-utils/utils.d.ts +1 -1
- package/dist/loop/test-utils/utils.d.ts.map +1 -1
- package/dist/loop/types.d.ts +42 -20
- package/dist/loop/types.d.ts.map +1 -1
- package/dist/loop/workflows/agentic-execution/index.d.ts +60 -42
- package/dist/loop/workflows/agentic-execution/index.d.ts.map +1 -1
- package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts +41 -29
- package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts.map +1 -1
- package/dist/loop/workflows/agentic-execution/llm-mapping-step.d.ts +20 -14
- package/dist/loop/workflows/agentic-execution/llm-mapping-step.d.ts.map +1 -1
- package/dist/loop/workflows/agentic-execution/tool-call-step.d.ts +1 -1
- package/dist/loop/workflows/agentic-execution/tool-call-step.d.ts.map +1 -1
- package/dist/loop/workflows/agentic-loop/index.d.ts +62 -43
- package/dist/loop/workflows/agentic-loop/index.d.ts.map +1 -1
- package/dist/loop/workflows/run-state.d.ts +2 -2
- package/dist/loop/workflows/run-state.d.ts.map +1 -1
- package/dist/loop/workflows/schema.d.ts +32 -15
- package/dist/loop/workflows/schema.d.ts.map +1 -1
- package/dist/loop/workflows/stream.d.ts +1 -1
- package/dist/loop/workflows/stream.d.ts.map +1 -1
- package/dist/mastra/index.cjs +2 -2
- package/dist/mastra/index.d.ts +377 -12
- package/dist/mastra/index.d.ts.map +1 -1
- package/dist/mastra/index.js +1 -1
- package/dist/mcp/index.cjs +4 -4
- package/dist/mcp/index.cjs.map +1 -1
- package/dist/mcp/index.d.ts +4 -4
- package/dist/mcp/index.d.ts.map +1 -1
- package/dist/mcp/index.js +2 -2
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/types.d.ts +2 -2
- package/dist/mcp/types.d.ts.map +1 -1
- package/dist/memory/index.cjs +21 -327
- package/dist/memory/index.cjs.map +1 -1
- package/dist/memory/index.js +1 -327
- package/dist/memory/index.js.map +1 -1
- package/dist/memory/memory.d.ts +28 -18
- package/dist/memory/memory.d.ts.map +1 -1
- package/dist/memory/mock.d.ts +15 -14
- package/dist/memory/mock.d.ts.map +1 -1
- package/dist/memory/types.d.ts +69 -11
- package/dist/memory/types.d.ts.map +1 -1
- package/dist/models-dev-23RN2WHG.js +3 -0
- package/dist/{models-dev-DNBKXHT4.js.map → models-dev-23RN2WHG.js.map} +1 -1
- package/dist/models-dev-EO3SUIY2.cjs +12 -0
- package/dist/{models-dev-YBEEQIX6.cjs.map → models-dev-EO3SUIY2.cjs.map} +1 -1
- package/dist/netlify-GXJ5D5DD.js +3 -0
- package/dist/{netlify-7G2L5VSH.js.map → netlify-GXJ5D5DD.js.map} +1 -1
- package/dist/netlify-KJLY3GFS.cjs +12 -0
- package/dist/{netlify-GWNGSIRZ.cjs.map → netlify-KJLY3GFS.cjs.map} +1 -1
- package/dist/observability/index.cjs +16 -8
- package/dist/observability/index.js +1 -1
- package/dist/observability/types/tracing.d.ts +236 -13
- package/dist/observability/types/tracing.d.ts.map +1 -1
- package/dist/observability/utils.d.ts +47 -1
- package/dist/observability/utils.d.ts.map +1 -1
- package/dist/processors/index.cjs +115 -11
- package/dist/processors/index.d.ts +246 -26
- package/dist/processors/index.d.ts.map +1 -1
- package/dist/processors/index.js +1 -1
- package/dist/processors/memory/index.d.ts +7 -0
- package/dist/processors/memory/index.d.ts.map +1 -0
- package/dist/processors/memory/message-history.d.ts +43 -0
- package/dist/processors/memory/message-history.d.ts.map +1 -0
- package/dist/processors/memory/semantic-recall.d.ts +152 -0
- package/dist/processors/memory/semantic-recall.d.ts.map +1 -0
- package/dist/processors/memory/working-memory.d.ts +65 -0
- package/dist/processors/memory/working-memory.d.ts.map +1 -0
- package/dist/processors/processors/batch-parts.d.ts +1 -1
- package/dist/processors/processors/batch-parts.d.ts.map +1 -1
- package/dist/processors/processors/index.d.ts +2 -1
- package/dist/processors/processors/index.d.ts.map +1 -1
- package/dist/processors/processors/language-detector.d.ts +15 -1
- package/dist/processors/processors/language-detector.d.ts.map +1 -1
- package/dist/processors/processors/moderation.d.ts +15 -1
- package/dist/processors/processors/moderation.d.ts.map +1 -1
- package/dist/processors/processors/pii-detector.d.ts +15 -1
- package/dist/processors/processors/pii-detector.d.ts.map +1 -1
- package/dist/processors/processors/prepare-step.d.ts +12 -0
- package/dist/processors/processors/prepare-step.d.ts.map +1 -0
- package/dist/processors/processors/prompt-injection-detector.d.ts +15 -1
- package/dist/processors/processors/prompt-injection-detector.d.ts.map +1 -1
- package/dist/processors/processors/structured-output.d.ts +7 -5
- package/dist/processors/processors/structured-output.d.ts.map +1 -1
- package/dist/processors/processors/system-prompt-scrubber.d.ts +1 -1
- package/dist/processors/processors/system-prompt-scrubber.d.ts.map +1 -1
- package/dist/processors/processors/token-limiter.d.ts +22 -12
- package/dist/processors/processors/token-limiter.d.ts.map +1 -1
- package/dist/processors/processors/tool-call-filter.d.ts +28 -0
- package/dist/processors/processors/tool-call-filter.d.ts.map +1 -0
- package/dist/processors/processors/unicode-normalizer.d.ts +1 -1
- package/dist/processors/processors/unicode-normalizer.d.ts.map +1 -1
- package/dist/processors/runner.d.ts +83 -9
- package/dist/processors/runner.d.ts.map +1 -1
- package/dist/processors/step-schema.d.ts +49731 -0
- package/dist/processors/step-schema.d.ts.map +1 -0
- package/dist/provider-registry-3TG2KUD2.cjs +40 -0
- package/dist/provider-registry-3TG2KUD2.cjs.map +1 -0
- package/dist/provider-registry-F67Y6OF2.js +3 -0
- package/dist/provider-registry-F67Y6OF2.js.map +1 -0
- package/dist/provider-registry.json +1056 -61
- package/dist/{registry-generator-MK63POJO.cjs → registry-generator-34SC4TAU.cjs} +23 -6
- package/dist/registry-generator-34SC4TAU.cjs.map +1 -0
- package/dist/{registry-generator-H4YNODDH.js → registry-generator-UMTNPBJX.js} +23 -7
- package/dist/registry-generator-UMTNPBJX.js.map +1 -0
- package/dist/relevance/index.cjs +2 -2
- package/dist/relevance/index.js +1 -1
- package/dist/request-context/index.cjs +10 -2
- package/dist/request-context/index.d.ts +26 -0
- package/dist/request-context/index.d.ts.map +1 -1
- package/dist/request-context/index.js +1 -1
- package/dist/server/auth.d.ts +11 -0
- package/dist/server/auth.d.ts.map +1 -1
- package/dist/server/base.d.ts +51 -0
- package/dist/server/base.d.ts.map +1 -0
- package/dist/server/composite-auth.d.ts +9 -0
- package/dist/server/composite-auth.d.ts.map +1 -0
- package/dist/server/index.cjs +124 -3
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.d.ts +8 -0
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +121 -3
- package/dist/server/index.js.map +1 -1
- package/dist/server/simple-auth.d.ts +27 -0
- package/dist/server/simple-auth.d.ts.map +1 -0
- package/dist/server/types.d.ts +6 -0
- package/dist/server/types.d.ts.map +1 -1
- package/dist/storage/base.d.ts +76 -3
- package/dist/storage/base.d.ts.map +1 -1
- package/dist/storage/constants.d.ts +3 -1
- package/dist/storage/constants.d.ts.map +1 -1
- package/dist/storage/domains/agents/base.d.ts +49 -0
- package/dist/storage/domains/agents/base.d.ts.map +1 -0
- package/dist/storage/domains/agents/index.d.ts +3 -0
- package/dist/storage/domains/agents/index.d.ts.map +1 -0
- package/dist/storage/domains/agents/inmemory.d.ts +22 -0
- package/dist/storage/domains/agents/inmemory.d.ts.map +1 -0
- package/dist/storage/domains/index.d.ts +1 -0
- package/dist/storage/domains/index.d.ts.map +1 -1
- package/dist/storage/domains/memory/inmemory.d.ts.map +1 -1
- package/dist/storage/domains/operations/inmemory.d.ts.map +1 -1
- package/dist/storage/domains/scores/base.d.ts +2 -2
- package/dist/storage/domains/scores/base.d.ts.map +1 -1
- package/dist/storage/domains/scores/inmemory.d.ts +2 -2
- package/dist/storage/domains/scores/inmemory.d.ts.map +1 -1
- package/dist/storage/domains/workflows/base.d.ts +4 -0
- package/dist/storage/domains/workflows/base.d.ts.map +1 -1
- package/dist/storage/domains/workflows/inmemory.d.ts +5 -1
- package/dist/storage/domains/workflows/inmemory.d.ts.map +1 -1
- package/dist/storage/index.cjs +65 -29
- package/dist/storage/index.js +1 -1
- package/dist/storage/mock.d.ts +7 -2
- package/dist/storage/mock.d.ts.map +1 -1
- package/dist/storage/storageWithInit.d.ts.map +1 -1
- package/dist/storage/types.d.ts +88 -5
- package/dist/storage/types.d.ts.map +1 -1
- package/dist/storage/utils.d.ts +82 -0
- package/dist/storage/utils.d.ts.map +1 -1
- package/dist/stream/MastraAgentNetworkStream.d.ts +2 -2
- package/dist/stream/MastraAgentNetworkStream.d.ts.map +1 -1
- package/dist/stream/MastraWorkflowStream.d.ts +2 -2
- package/dist/stream/MastraWorkflowStream.d.ts.map +1 -1
- package/dist/stream/RunOutput.d.ts +2 -2
- package/dist/stream/RunOutput.d.ts.map +1 -1
- package/dist/stream/aisdk/v4/transform.d.ts.map +1 -1
- package/dist/stream/aisdk/v4/usage.d.ts +19 -0
- package/dist/stream/aisdk/v4/usage.d.ts.map +1 -0
- package/dist/stream/aisdk/v5/compat/prepare-tools.d.ts.map +1 -1
- package/dist/stream/aisdk/v5/execute.d.ts +9 -5
- package/dist/stream/aisdk/v5/execute.d.ts.map +1 -1
- package/dist/stream/aisdk/v5/input.d.ts +4 -1
- package/dist/stream/aisdk/v5/input.d.ts.map +1 -1
- package/dist/stream/aisdk/v5/output-helpers.d.ts +5 -1
- package/dist/stream/aisdk/v5/output-helpers.d.ts.map +1 -1
- package/dist/stream/aisdk/v5/output.d.ts +11 -13
- package/dist/stream/aisdk/v5/output.d.ts.map +1 -1
- package/dist/stream/aisdk/v5/transform.d.ts +2 -1
- package/dist/stream/aisdk/v5/transform.d.ts.map +1 -1
- package/dist/stream/base/base.d.ts +1 -1
- package/dist/stream/base/base.d.ts.map +1 -1
- package/dist/stream/base/input.d.ts +1 -1
- package/dist/stream/base/output-format-handlers.d.ts +14 -1
- package/dist/stream/base/output-format-handlers.d.ts.map +1 -1
- package/dist/stream/base/output.d.ts +9 -14
- package/dist/stream/base/output.d.ts.map +1 -1
- package/dist/stream/index.cjs +15 -11
- package/dist/stream/index.d.ts +2 -2
- package/dist/stream/index.d.ts.map +1 -1
- package/dist/stream/index.js +2 -2
- package/dist/stream/types.d.ts +97 -32
- package/dist/stream/types.d.ts.map +1 -1
- package/dist/test-utils/llm-mock.cjs +101 -30
- package/dist/test-utils/llm-mock.cjs.map +1 -1
- package/dist/test-utils/llm-mock.d.ts +7 -2
- package/dist/test-utils/llm-mock.d.ts.map +1 -1
- package/dist/test-utils/llm-mock.js +97 -30
- package/dist/test-utils/llm-mock.js.map +1 -1
- package/dist/tools/index.cjs +6 -6
- package/dist/tools/index.js +2 -2
- package/dist/tools/is-vercel-tool.cjs +2 -2
- package/dist/tools/is-vercel-tool.js +1 -1
- package/dist/tools/stream.d.ts +10 -4
- package/dist/tools/stream.d.ts.map +1 -1
- package/dist/tools/tool-builder/builder.d.ts +2 -0
- package/dist/tools/tool-builder/builder.d.ts.map +1 -1
- package/dist/tools/tool-stream-types.test-d.d.ts +2 -0
- package/dist/tools/tool-stream-types.test-d.d.ts.map +1 -0
- package/dist/tools/tool.d.ts +21 -8
- package/dist/tools/tool.d.ts.map +1 -1
- package/dist/tools/types.d.ts +33 -6
- package/dist/tools/types.d.ts.map +1 -1
- package/dist/tools/validation.d.ts +25 -1
- package/dist/tools/validation.d.ts.map +1 -1
- package/dist/tts/index.cjs +2 -2
- package/dist/tts/index.js +1 -1
- package/dist/types/zod-compat.d.ts +14 -1
- package/dist/types/zod-compat.d.ts.map +1 -1
- package/dist/utils.cjs +25 -21
- package/dist/utils.d.ts +9 -4
- package/dist/utils.d.ts.map +1 -1
- package/dist/utils.js +1 -1
- package/dist/vector/filter/index.cjs +7 -189
- package/dist/vector/filter/index.cjs.map +1 -1
- package/dist/vector/filter/index.js +1 -190
- package/dist/vector/filter/index.js.map +1 -1
- package/dist/vector/index.cjs +7 -2
- package/dist/vector/index.cjs.map +1 -1
- package/dist/vector/index.d.ts +1 -0
- package/dist/vector/index.d.ts.map +1 -1
- package/dist/vector/index.js +2 -1
- package/dist/vector/index.js.map +1 -1
- package/dist/vector/types.d.ts +86 -3
- package/dist/vector/types.d.ts.map +1 -1
- package/dist/vector/vector.d.ts +39 -2
- package/dist/vector/vector.d.ts.map +1 -1
- package/dist/voice/aisdk/index.d.ts +3 -0
- package/dist/voice/aisdk/index.d.ts.map +1 -0
- package/dist/voice/aisdk/speech.d.ts +23 -0
- package/dist/voice/aisdk/speech.d.ts.map +1 -0
- package/dist/voice/aisdk/transcription.d.ts +22 -0
- package/dist/voice/aisdk/transcription.d.ts.map +1 -0
- package/dist/voice/composite-voice.d.ts +4 -3
- package/dist/voice/composite-voice.d.ts.map +1 -1
- package/dist/voice/index.cjs +12 -4
- package/dist/voice/index.d.ts +1 -0
- package/dist/voice/index.d.ts.map +1 -1
- package/dist/voice/index.js +1 -1
- package/dist/workflows/default.d.ts +180 -270
- package/dist/workflows/default.d.ts.map +1 -1
- package/dist/workflows/evented/execution-engine.d.ts +3 -1
- package/dist/workflows/evented/execution-engine.d.ts.map +1 -1
- package/dist/workflows/evented/index.cjs +10 -10
- package/dist/workflows/evented/index.js +1 -1
- package/dist/workflows/evented/step-executor.d.ts +1 -1
- package/dist/workflows/evented/step-executor.d.ts.map +1 -1
- package/dist/workflows/evented/workflow-event-processor/index.d.ts +5 -4
- package/dist/workflows/evented/workflow-event-processor/index.d.ts.map +1 -1
- package/dist/workflows/evented/workflow-event-processor/loop.d.ts +1 -1
- package/dist/workflows/evented/workflow-event-processor/loop.d.ts.map +1 -1
- package/dist/workflows/evented/workflow-event-processor/parallel.d.ts +2 -2
- package/dist/workflows/evented/workflow-event-processor/parallel.d.ts.map +1 -1
- package/dist/workflows/evented/workflow-event-processor/sleep.d.ts +2 -2
- package/dist/workflows/evented/workflow-event-processor/sleep.d.ts.map +1 -1
- package/dist/workflows/evented/workflow.d.ts +2 -1
- package/dist/workflows/evented/workflow.d.ts.map +1 -1
- package/dist/workflows/execution-engine.d.ts +8 -6
- package/dist/workflows/execution-engine.d.ts.map +1 -1
- package/dist/workflows/handlers/control-flow.d.ts +133 -0
- package/dist/workflows/handlers/control-flow.d.ts.map +1 -0
- package/dist/workflows/handlers/entry.d.ts +43 -0
- package/dist/workflows/handlers/entry.d.ts.map +1 -0
- package/dist/workflows/handlers/sleep.d.ts +60 -0
- package/dist/workflows/handlers/sleep.d.ts.map +1 -0
- package/dist/workflows/handlers/step.d.ts +58 -0
- package/dist/workflows/handlers/step.d.ts.map +1 -0
- package/dist/workflows/index.cjs +40 -16
- package/dist/workflows/index.js +1 -1
- package/dist/workflows/step.d.ts +8 -6
- package/dist/workflows/step.d.ts.map +1 -1
- package/dist/workflows/types.d.ts +257 -10
- package/dist/workflows/types.d.ts.map +1 -1
- package/dist/workflows/utils.d.ts +36 -0
- package/dist/workflows/utils.d.ts.map +1 -1
- package/dist/workflows/workflow.d.ts +146 -55
- package/dist/workflows/workflow.d.ts.map +1 -1
- package/package.json +26 -30
- package/src/llm/model/provider-types.generated.d.ts +489 -27
- package/dist/chunk-2ZVKF4HP.cjs.map +0 -1
- package/dist/chunk-436FFEF6.js +0 -34
- package/dist/chunk-436FFEF6.js.map +0 -1
- package/dist/chunk-4CDL2QJT.js.map +0 -1
- package/dist/chunk-7AHYOMHJ.js +0 -149
- package/dist/chunk-7AHYOMHJ.js.map +0 -1
- package/dist/chunk-CB575O6L.cjs.map +0 -1
- package/dist/chunk-CD56CXVE.cjs.map +0 -1
- package/dist/chunk-CINNK34N.js.map +0 -1
- package/dist/chunk-DNEURYF3.cjs.map +0 -1
- package/dist/chunk-DSNPWVIG.cjs.map +0 -1
- package/dist/chunk-E7K4FTLN.cjs.map +0 -1
- package/dist/chunk-ECFXGXWO.cjs.map +0 -1
- package/dist/chunk-ET6UOTTU.cjs +0 -154
- package/dist/chunk-ET6UOTTU.cjs.map +0 -1
- package/dist/chunk-GGYKYORQ.cjs.map +0 -1
- package/dist/chunk-GRBGQ2GE.js.map +0 -1
- package/dist/chunk-H6CZGPZD.js.map +0 -1
- package/dist/chunk-HDJFSJCK.js +0 -2237
- package/dist/chunk-HDJFSJCK.js.map +0 -1
- package/dist/chunk-HGNRQ3OG.js +0 -58
- package/dist/chunk-HGNRQ3OG.js.map +0 -1
- package/dist/chunk-I4CXL4SR.js.map +0 -1
- package/dist/chunk-IQO7ANVS.cjs.map +0 -1
- package/dist/chunk-J7O6WENZ.cjs.map +0 -1
- package/dist/chunk-JPGVRWWL.js.map +0 -1
- package/dist/chunk-JUBFO5J3.js.map +0 -1
- package/dist/chunk-JV2KH24V.js.map +0 -1
- package/dist/chunk-KIZIOFZC.js.map +0 -1
- package/dist/chunk-KJ2SW6VA.js.map +0 -1
- package/dist/chunk-LJFJTTZQ.cjs +0 -4
- package/dist/chunk-LJFJTTZQ.cjs.map +0 -1
- package/dist/chunk-LRSB62Z6.cjs +0 -60
- package/dist/chunk-LRSB62Z6.cjs.map +0 -1
- package/dist/chunk-LWBQ4P4N.cjs +0 -2240
- package/dist/chunk-LWBQ4P4N.cjs.map +0 -1
- package/dist/chunk-MA7TEM62.cjs.map +0 -1
- package/dist/chunk-MSWTA73A.cjs.map +0 -1
- package/dist/chunk-MV7KHWUT.js.map +0 -1
- package/dist/chunk-QUKUN6NR.cjs.map +0 -1
- package/dist/chunk-TQTAMPSC.js.map +0 -1
- package/dist/chunk-UIZSWUKP.js.map +0 -1
- package/dist/chunk-V3VLOOSW.cjs +0 -36
- package/dist/chunk-V3VLOOSW.cjs.map +0 -1
- package/dist/chunk-VOQ3ULMT.js.map +0 -1
- package/dist/chunk-VOY2RXOC.cjs.map +0 -1
- package/dist/chunk-W7UH2PWL.js.map +0 -1
- package/dist/chunk-WM6CK2F3.cjs.map +0 -1
- package/dist/chunk-XEVG546F.js.map +0 -1
- package/dist/chunk-Y63IFHEZ.cjs.map +0 -1
- package/dist/chunk-ZV5CC35D.js +0 -3
- package/dist/chunk-ZV5CC35D.js.map +0 -1
- package/dist/models-dev-DNBKXHT4.js +0 -3
- package/dist/models-dev-YBEEQIX6.cjs +0 -12
- package/dist/netlify-7G2L5VSH.js +0 -3
- package/dist/netlify-GWNGSIRZ.cjs +0 -12
- package/dist/registry-generator-H4YNODDH.js.map +0 -1
- package/dist/registry-generator-MK63POJO.cjs.map +0 -1
|
@@ -92,5 +92,5 @@ exports.LoggerTransport = LoggerTransport;
|
|
|
92
92
|
exports.MultiLogger = MultiLogger;
|
|
93
93
|
exports.createCustomTransport = createCustomTransport;
|
|
94
94
|
exports.noopLogger = noopLogger;
|
|
95
|
-
//# sourceMappingURL=chunk-
|
|
96
|
-
//# sourceMappingURL=chunk-
|
|
95
|
+
//# sourceMappingURL=chunk-6BJ7XHRH.cjs.map
|
|
96
|
+
//# sourceMappingURL=chunk-6BJ7XHRH.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/logger/multi-logger.ts","../src/logger/noop-logger.ts","../src/logger/transport.ts"],"names":["Transform"],"mappings":";;;;;AAKO,IAAM,cAAN,MAA2C;AAAA,EACxC,OAAA;AAAA,EAER,YAAY,OAAA,EAA0B;AACpC,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AAAA,EACjB;AAAA,EAEA,KAAA,CAAM,YAAoB,IAAA,EAAmB;AAC3C,IAAA,IAAA,CAAK,OAAA,CAAQ,QAAQ,CAAA,MAAA,KAAU,MAAA,CAAO,MAAM,OAAA,EAAS,GAAG,IAAI,CAAC,CAAA;AAAA,EAC/D;AAAA,EAEA,IAAA,CAAK,YAAoB,IAAA,EAAmB;AAC1C,IAAA,IAAA,CAAK,OAAA,CAAQ,QAAQ,CAAA,MAAA,KAAU,MAAA,CAAO,KAAK,OAAA,EAAS,GAAG,IAAI,CAAC,CAAA;AAAA,EAC9D;AAAA,EAEA,IAAA,CAAK,YAAoB,IAAA,EAAmB;AAC1C,IAAA,IAAA,CAAK,OAAA,CAAQ,QAAQ,CAAA,MAAA,KAAU,MAAA,CAAO,KAAK,OAAA,EA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AAO,CAAA,EAAG,IAAA,EAAM,KAAA,EAAO,IAAA,IAAQ,GAAG,OAAA,EAAS,KAAA,EAAO,OAAA,IAAW,GAAA,EAAK,SAAS,KAAA,EAAM;AAAA,EACtG;AAAA,EACA,MAAM,SAAS,KAAA,EAcZ;AACD,IAAA,OAAO,EAAE,IAAA,EAAM,EAAC,EAAG,OAAO,CAAA,EAAG,IAAA,EAAM,KAAA,EAAO,IAAA,IAAQ,GAAG,OAAA,EAAS,KAAA,EAAO,OAAA,IAAW,GAAA,EAAK,SAAS,KAAA,EAAM;AAAA,EACtG;AACF;AAEO,IAAM,qBAAA,GAAwB,CACnC,MAAA,EACA,QAAA,EACA,eAAA,KACG;AACH,EAAA,IAAI,SAAA,GAAY,MAAA;AAChB,EAAA,IAAI,QAAA,EAAU;AACZ,IAAA,SAAA,CAAU,QAAA,GAAW,QAAA;AAAA,EACvB;AACA,EAAA,IAAI,eAAA,EAAiB;AACnB,IAAA,SAAA,CAAU,eAAA,GAAkB,eAAA;AAAA,EAC9B;AACA,EAAA,OAAO,SAAA;AACT","file":"chunk-
|
|
1
|
+
{"version":3,"sources":["../src/logger/multi-logger.ts","../src/logger/noop-logger.ts","../src/logger/transport.ts"],"names":["Transform"],"mappings":";;;;;AAKO,IAAM,cAAN,MAA2C;AAAA,EACxC,OAAA;AAAA,EAER,YAAY,OAAA,EAA0B;AACpC,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AAAA,EACjB;AAAA,EAEA,KAAA,CAAM,YAAoB,IAAA,EAAmB;AAC3C,IAAA,IAAA,CAAK,OAAA,CAAQ,QAAQ,CAAA,MAAA,KAAU,MAAA,CAAO,MAAM,OAAA,EAAS,GAAG,IAAI,CAAC,CAAA;AAAA,EAC/D;AAAA,EAEA,IAAA,CAAK,YAAoB,IAAA,EAAmB;AAC1C,IAAA,IAAA,CAAK,OAAA,CAAQ,QAAQ,CAAA,MAAA,KAAU,MAAA,CAAO,KAAK,OAAA,EAAS,GAAG,IAAI,CAAC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,CAAM,EAAE,GAAG,IAAA,EAAM,UAAA,EAAY,MAAM,CAAA;AAAA,EACrC;AAAA,EAEA,MAAM,gBAAgB,KAAA,EAcnB;AACD,IAAA,OAAO,EAAE,IAAA,EAAM,EAAC,EAAG,OAAO,CAAA,EAAG,IAAA,EAAM,KAAA,EAAO,IAAA,IAAQ,GAAG,OAAA,EAAS,KAAA,EAAO,OAAA,IAAW,GAAA,EAAK,SAAS,KAAA,EAAM;AAAA,EACtG;AAAA,EACA,MAAM,SAAS,KAAA,EAcZ;AACD,IAAA,OAAO,EAAE,IAAA,EAAM,EAAC,EAAG,OAAO,CAAA,EAAG,IAAA,EAAM,KAAA,EAAO,IAAA,IAAQ,GAAG,OAAA,EAAS,KAAA,EAAO,OAAA,IAAW,GAAA,EAAK,SAAS,KAAA,EAAM;AAAA,EACtG;AACF;AAEO,IAAM,qBAAA,GAAwB,CACnC,MAAA,EACA,QAAA,EACA,eAAA,KACG;AACH,EAAA,IAAI,SAAA,GAAY,MAAA;AAChB,EAAA,IAAI,QAAA,EAAU;AACZ,IAAA,SAAA,CAAU,QAAA,GAAW,QAAA;AAAA,EACvB;AACA,EAAA,IAAI,eAAA,EAAiB;AACnB,IAAA,SAAA,CAAU,eAAA,GAAkB,eAAA;AAAA,EAC9B;AACA,EAAA,OAAO,SAAA;AACT","file":"chunk-6BJ7XHRH.cjs","sourcesContent":["import type { MastraError } from '../error';\nimport type { LogLevel } from './constants';\nimport type { IMastraLogger } from './logger';\nimport type { LoggerTransport } from './transport';\n\nexport class MultiLogger implements IMastraLogger {\n private loggers: IMastraLogger[];\n\n constructor(loggers: IMastraLogger[]) {\n this.loggers = loggers;\n }\n\n debug(message: string, ...args: any[]): void {\n this.loggers.forEach(logger => logger.debug(message, ...args));\n }\n\n info(message: string, ...args: any[]): void {\n this.loggers.forEach(logger => logger.info(message, ...args));\n }\n\n warn(message: string, ...args: any[]): void {\n this.loggers.forEach(logger => logger.warn(message, ...args));\n }\n\n error(message: string, ...args: any[]): void {\n this.loggers.forEach(logger => logger.error(message, ...args));\n }\n\n trackException(error: MastraError): void {\n this.loggers.forEach(logger => logger.trackException(error));\n }\n\n getTransports(): Map<string, LoggerTransport> {\n const transports: [string, LoggerTransport][] = [];\n this.loggers.forEach(logger => transports.push(...logger.getTransports().entries()));\n return new Map(transports);\n }\n\n async listLogs(\n transportId: string,\n params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean;\n page?: number;\n perPage?: number;\n },\n ) {\n for (const logger of this.loggers) {\n const logs = await logger.listLogs(transportId, params);\n if (logs.total > 0) {\n return logs;\n }\n }\n\n return { logs: [], total: 0, page: params?.page ?? 1, perPage: params?.perPage ?? 100, hasMore: false };\n }\n\n async listLogsByRunId(args: {\n transportId: string;\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }) {\n for (const logger of this.loggers) {\n const logs = await logger.listLogsByRunId(args);\n if (logs.total > 0) {\n return logs;\n }\n }\n\n return { logs: [], total: 0, page: args.page ?? 1, perPage: args.perPage ?? 100, hasMore: false };\n }\n}\n","import type { IMastraLogger } from './logger';\n\nexport const noopLogger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n cleanup: async () => {},\n getTransports: () => new Map(),\n trackException: () => {},\n listLogs: async () => ({ logs: [], total: 0, page: 1, perPage: 100, hasMore: false }),\n listLogsByRunId: async () => ({ logs: [], total: 0, page: 1, perPage: 100, hasMore: false }),\n} as IMastraLogger;\n","import { Transform } from 'node:stream';\nimport type { LogLevel } from './constants';\n\nexport interface BaseLogMessage {\n runId?: string;\n msg: string;\n level: LogLevel;\n time: Date;\n pid: number;\n hostname: string;\n name: string;\n}\n\nexport abstract class LoggerTransport extends Transform {\n constructor(opts: any = {}) {\n super({ ...opts, objectMode: true });\n }\n\n async listLogsByRunId(_args: {\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n return { logs: [], total: 0, page: _args?.page ?? 1, perPage: _args?.perPage ?? 100, hasMore: false };\n }\n async listLogs(_args?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean;\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n return { logs: [], total: 0, page: _args?.page ?? 1, perPage: _args?.perPage ?? 100, hasMore: false };\n }\n}\n\nexport const createCustomTransport = (\n stream: Transform,\n listLogs?: LoggerTransport['listLogs'],\n listLogsByRunId?: LoggerTransport['listLogsByRunId'],\n) => {\n let transport = stream as LoggerTransport;\n if (listLogs) {\n transport.listLogs = listLogs;\n }\n if (listLogsByRunId) {\n transport.listLogsByRunId = listLogsByRunId;\n }\n return transport as LoggerTransport;\n};\n"]}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
// src/request-context/index.ts
|
|
2
|
+
var MASTRA_RESOURCE_ID_KEY = "mastra__resourceId";
|
|
3
|
+
var MASTRA_THREAD_ID_KEY = "mastra__threadId";
|
|
2
4
|
var RequestContext = class {
|
|
3
5
|
registry = /* @__PURE__ */ new Map();
|
|
4
6
|
constructor(iterable) {
|
|
@@ -73,6 +75,6 @@ var RequestContext = class {
|
|
|
73
75
|
}
|
|
74
76
|
};
|
|
75
77
|
|
|
76
|
-
export { RequestContext };
|
|
77
|
-
//# sourceMappingURL=chunk-
|
|
78
|
-
//# sourceMappingURL=chunk-
|
|
78
|
+
export { MASTRA_RESOURCE_ID_KEY, MASTRA_THREAD_ID_KEY, RequestContext };
|
|
79
|
+
//# sourceMappingURL=chunk-6TBWJV35.js.map
|
|
80
|
+
//# sourceMappingURL=chunk-6TBWJV35.js.map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AAAA,EAC/B;AAAA;AAAA;AAAA;AAAA,EAKO,IAAA,GAAe;AACpB,IAAA,OAAO,KAAK,QAAA,CAAS,IAAA;AAAA,EACvB;AAAA;AAAA;AAAA;AAAA,EAKO,QAAiB,UAAA,EAA0E;AAChG,IAAA,IAAA,CAAK,QAAA,CAAS,QAAQ,UAAiB,CAAA;AAAA,EACzC;AAAA;AAAA;AAAA;AAAA;AAAA,EAMO,MAAA,GAA8B;AACnC,IAAA,OAAO,MAAA,CAAO,WAAA,CAAY,IAAA,CAAK,QAAQ,CAAA;AAAA,EACzC;AACF","file":"chunk-6TBWJV35.js","sourcesContent":["type RecordToTuple<T> = {\n [K in keyof T]: [K, T[K]];\n}[keyof T][];\n\n/**\n * Reserved key for setting resourceId from middleware.\n * When set in RequestContext, this takes precedence over client-provided values\n * for security (prevents attackers from hijacking another user's memory).\n *\n * @example\n * ```typescript\n * // In your auth middleware:\n * const requestContext = c.get('requestContext');\n * requestContext.set(MASTRA_RESOURCE_ID_KEY, authenticatedUser.id);\n * ```\n */\nexport const MASTRA_RESOURCE_ID_KEY = 'mastra__resourceId';\n\n/**\n * Reserved key for setting threadId from middleware.\n * When set in RequestContext, this takes precedence over client-provided values\n * for security (prevents attackers from hijacking another user's memory).\n *\n * @example\n * ```typescript\n * // In your auth middleware:\n * const requestContext = c.get('requestContext');\n * requestContext.set(MASTRA_THREAD_ID_KEY, threadId);\n * ```\n */\nexport const MASTRA_THREAD_ID_KEY = 'mastra__threadId';\n\nexport class RequestContext<Values extends Record<string, any> | unknown = unknown> {\n private registry = new Map<string, unknown>();\n\n constructor(\n iterable?: Values extends Record<string, any>\n ? RecordToTuple<Partial<Values>>\n : Iterable<readonly [string, unknown]>,\n ) {\n this.registry = new Map(iterable);\n }\n\n /**\n * set a value with strict typing if `Values` is a Record and the key exists in it.\n */\n public set<K extends Values extends Record<string, any> ? keyof Values : string>(\n key: K,\n value: Values extends Record<string, any> ? (K extends keyof Values ? Values[K] : never) : unknown,\n ): void {\n // The type assertion `key as string` is safe because K always extends string ultimately.\n this.registry.set(key as string, value);\n }\n\n /**\n * Get a value with its type\n */\n public get<\n K extends Values extends Record<string, any> ? keyof Values : string,\n R = Values extends Record<string, any> ? (K extends keyof Values ? Values[K] : never) : unknown,\n >(key: K): R {\n return this.registry.get(key as string) as R;\n }\n\n /**\n * Check if a key exists in the container\n */\n public has<K extends Values extends Record<string, any> ? keyof Values : string>(key: K): boolean {\n return this.registry.has(key);\n }\n\n /**\n * Delete a value by key\n */\n public delete<K extends Values extends Record<string, any> ? keyof Values : string>(key: K): boolean {\n return this.registry.delete(key);\n }\n\n /**\n * Clear all values from the container\n */\n public clear(): void {\n this.registry.clear();\n }\n\n /**\n * Get all keys in the container\n */\n public keys<R = Values extends Record<string, any> ? keyof Values : string>(): IterableIterator<R> {\n return this.registry.keys() as IterableIterator<R>;\n }\n\n /**\n * Get all values in the container\n */\n public values<R = Values extends Record<string, any> ? Values[keyof Values] : unknown>(): IterableIterator<R> {\n return this.registry.values() as IterableIterator<R>;\n }\n\n /**\n * Get all entries in the container\n */\n public entries<R = Values extends Record<string, any> ? Values[keyof Values] : unknown>(): IterableIterator<\n [string, R]\n > {\n return this.registry.entries() as IterableIterator<[string, R]>;\n }\n\n /**\n * Get the size of the container\n */\n public size(): number {\n return this.registry.size;\n }\n\n /**\n * Execute a function for each entry in the container\n */\n public forEach<T = any>(callbackfn: (value: T, key: string, map: Map<string, any>) => void): void {\n this.registry.forEach(callbackfn as any);\n }\n\n /**\n * Custom JSON serialization method\n * Converts the internal Map to a plain object for proper JSON serialization\n */\n public toJSON(): Record<string, any> {\n return Object.fromEntries(this.registry);\n }\n}\n"]}
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/vector/filter/base.ts
|
|
4
|
+
var BaseFilterTranslator = class _BaseFilterTranslator {
|
|
5
|
+
/**
|
|
6
|
+
* Operator type checks
|
|
7
|
+
*/
|
|
8
|
+
isOperator(key) {
|
|
9
|
+
return key.startsWith("$");
|
|
10
|
+
}
|
|
11
|
+
static BASIC_OPERATORS = ["$eq", "$ne"];
|
|
12
|
+
static NUMERIC_OPERATORS = ["$gt", "$gte", "$lt", "$lte"];
|
|
13
|
+
static ARRAY_OPERATORS = ["$in", "$nin", "$all", "$elemMatch"];
|
|
14
|
+
static LOGICAL_OPERATORS = ["$and", "$or", "$not", "$nor"];
|
|
15
|
+
static ELEMENT_OPERATORS = ["$exists"];
|
|
16
|
+
static REGEX_OPERATORS = ["$regex", "$options"];
|
|
17
|
+
static DEFAULT_OPERATORS = {
|
|
18
|
+
logical: _BaseFilterTranslator.LOGICAL_OPERATORS,
|
|
19
|
+
basic: _BaseFilterTranslator.BASIC_OPERATORS,
|
|
20
|
+
numeric: _BaseFilterTranslator.NUMERIC_OPERATORS,
|
|
21
|
+
array: _BaseFilterTranslator.ARRAY_OPERATORS,
|
|
22
|
+
element: _BaseFilterTranslator.ELEMENT_OPERATORS,
|
|
23
|
+
regex: _BaseFilterTranslator.REGEX_OPERATORS
|
|
24
|
+
};
|
|
25
|
+
isLogicalOperator(key) {
|
|
26
|
+
return _BaseFilterTranslator.DEFAULT_OPERATORS.logical.includes(key);
|
|
27
|
+
}
|
|
28
|
+
isBasicOperator(key) {
|
|
29
|
+
return _BaseFilterTranslator.DEFAULT_OPERATORS.basic.includes(key);
|
|
30
|
+
}
|
|
31
|
+
isNumericOperator(key) {
|
|
32
|
+
return _BaseFilterTranslator.DEFAULT_OPERATORS.numeric.includes(key);
|
|
33
|
+
}
|
|
34
|
+
isArrayOperator(key) {
|
|
35
|
+
return _BaseFilterTranslator.DEFAULT_OPERATORS.array.includes(key);
|
|
36
|
+
}
|
|
37
|
+
isElementOperator(key) {
|
|
38
|
+
return _BaseFilterTranslator.DEFAULT_OPERATORS.element.includes(key);
|
|
39
|
+
}
|
|
40
|
+
isRegexOperator(key) {
|
|
41
|
+
return _BaseFilterTranslator.DEFAULT_OPERATORS.regex.includes(key);
|
|
42
|
+
}
|
|
43
|
+
isFieldOperator(key) {
|
|
44
|
+
return this.isOperator(key) && !this.isLogicalOperator(key);
|
|
45
|
+
}
|
|
46
|
+
isCustomOperator(key) {
|
|
47
|
+
const support = this.getSupportedOperators();
|
|
48
|
+
return support.custom?.includes(key) ?? false;
|
|
49
|
+
}
|
|
50
|
+
getSupportedOperators() {
|
|
51
|
+
return _BaseFilterTranslator.DEFAULT_OPERATORS;
|
|
52
|
+
}
|
|
53
|
+
isValidOperator(key) {
|
|
54
|
+
const support = this.getSupportedOperators();
|
|
55
|
+
const allSupported = Object.values(support).flat();
|
|
56
|
+
return allSupported.includes(key);
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Value normalization for comparison operators
|
|
60
|
+
*/
|
|
61
|
+
normalizeComparisonValue(value) {
|
|
62
|
+
if (value instanceof Date) {
|
|
63
|
+
return value.toISOString();
|
|
64
|
+
}
|
|
65
|
+
if (typeof value === "number" && Object.is(value, -0)) {
|
|
66
|
+
return 0;
|
|
67
|
+
}
|
|
68
|
+
return value;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Helper method to simulate $all operator using $and + $eq when needed.
|
|
72
|
+
* Some vector stores don't support $all natively.
|
|
73
|
+
*/
|
|
74
|
+
simulateAllOperator(field, values) {
|
|
75
|
+
return {
|
|
76
|
+
$and: values.map((value) => ({
|
|
77
|
+
[field]: { $in: [this.normalizeComparisonValue(value)] }
|
|
78
|
+
}))
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Utility functions for type checking
|
|
83
|
+
*/
|
|
84
|
+
isPrimitive(value) {
|
|
85
|
+
return value === null || value === void 0 || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
|
|
86
|
+
}
|
|
87
|
+
isRegex(value) {
|
|
88
|
+
return value instanceof RegExp;
|
|
89
|
+
}
|
|
90
|
+
isEmpty(obj) {
|
|
91
|
+
return obj === null || obj === void 0 || typeof obj === "object" && Object.keys(obj).length === 0;
|
|
92
|
+
}
|
|
93
|
+
static ErrorMessages = {
|
|
94
|
+
UNSUPPORTED_OPERATOR: (op) => `Unsupported operator: ${op}`,
|
|
95
|
+
INVALID_LOGICAL_OPERATOR_LOCATION: (op, path) => `Logical operator ${op} cannot be used at field level: ${path}`,
|
|
96
|
+
NOT_REQUIRES_OBJECT: `$not operator requires an object`,
|
|
97
|
+
NOT_CANNOT_BE_EMPTY: `$not operator cannot be empty`,
|
|
98
|
+
INVALID_LOGICAL_OPERATOR_CONTENT: (path) => `Logical operators must contain field conditions, not direct operators: ${path}`,
|
|
99
|
+
INVALID_TOP_LEVEL_OPERATOR: (op) => `Invalid top-level operator: ${op}`,
|
|
100
|
+
ELEM_MATCH_REQUIRES_OBJECT: `$elemMatch requires an object with conditions`
|
|
101
|
+
};
|
|
102
|
+
/**
|
|
103
|
+
* Helper to handle array value normalization consistently
|
|
104
|
+
*/
|
|
105
|
+
normalizeArrayValues(values) {
|
|
106
|
+
return values.map((value) => this.normalizeComparisonValue(value));
|
|
107
|
+
}
|
|
108
|
+
validateFilter(filter) {
|
|
109
|
+
const validation = this.validateFilterSupport(filter);
|
|
110
|
+
if (!validation.supported) {
|
|
111
|
+
throw new Error(validation.messages.join(", "));
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Validates if a filter structure is supported by the specific vector DB
|
|
116
|
+
* and returns detailed validation information.
|
|
117
|
+
*/
|
|
118
|
+
validateFilterSupport(node, path = "") {
|
|
119
|
+
const messages = [];
|
|
120
|
+
if (this.isPrimitive(node) || this.isEmpty(node)) {
|
|
121
|
+
return { supported: true, messages: [] };
|
|
122
|
+
}
|
|
123
|
+
if (Array.isArray(node)) {
|
|
124
|
+
const arrayResults = node.map((item) => this.validateFilterSupport(item, path));
|
|
125
|
+
const arrayMessages = arrayResults.flatMap((r) => r.messages);
|
|
126
|
+
return {
|
|
127
|
+
supported: arrayResults.every((r) => r.supported),
|
|
128
|
+
messages: arrayMessages
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
const nodeObj = node;
|
|
132
|
+
let isSupported = true;
|
|
133
|
+
for (const [key, value] of Object.entries(nodeObj)) {
|
|
134
|
+
const newPath = path ? `${path}.${key}` : key;
|
|
135
|
+
if (this.isOperator(key)) {
|
|
136
|
+
if (!this.isValidOperator(key)) {
|
|
137
|
+
isSupported = false;
|
|
138
|
+
messages.push(_BaseFilterTranslator.ErrorMessages.UNSUPPORTED_OPERATOR(key));
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
if (!path && !this.isLogicalOperator(key)) {
|
|
142
|
+
isSupported = false;
|
|
143
|
+
messages.push(_BaseFilterTranslator.ErrorMessages.INVALID_TOP_LEVEL_OPERATOR(key));
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
if (key === "$elemMatch" && (typeof value !== "object" || Array.isArray(value))) {
|
|
147
|
+
isSupported = false;
|
|
148
|
+
messages.push(_BaseFilterTranslator.ErrorMessages.ELEM_MATCH_REQUIRES_OBJECT);
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
if (this.isLogicalOperator(key)) {
|
|
152
|
+
if (key === "$not") {
|
|
153
|
+
if (Array.isArray(value) || typeof value !== "object") {
|
|
154
|
+
isSupported = false;
|
|
155
|
+
messages.push(_BaseFilterTranslator.ErrorMessages.NOT_REQUIRES_OBJECT);
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
if (this.isEmpty(value)) {
|
|
159
|
+
isSupported = false;
|
|
160
|
+
messages.push(_BaseFilterTranslator.ErrorMessages.NOT_CANNOT_BE_EMPTY);
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
if (path && !this.isLogicalOperator(path.split(".").pop())) {
|
|
166
|
+
isSupported = false;
|
|
167
|
+
messages.push(_BaseFilterTranslator.ErrorMessages.INVALID_LOGICAL_OPERATOR_LOCATION(key, newPath));
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
if (Array.isArray(value)) {
|
|
171
|
+
const hasDirectOperators = value.some(
|
|
172
|
+
(item) => typeof item === "object" && Object.keys(item).length === 1 && this.isFieldOperator(Object.keys(item)[0])
|
|
173
|
+
);
|
|
174
|
+
if (hasDirectOperators) {
|
|
175
|
+
isSupported = false;
|
|
176
|
+
messages.push(_BaseFilterTranslator.ErrorMessages.INVALID_LOGICAL_OPERATOR_CONTENT(newPath));
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
const nestedValidation = this.validateFilterSupport(value, newPath);
|
|
183
|
+
if (!nestedValidation.supported) {
|
|
184
|
+
isSupported = false;
|
|
185
|
+
messages.push(...nestedValidation.messages);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
return { supported: isSupported, messages };
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
exports.BaseFilterTranslator = BaseFilterTranslator;
|
|
193
|
+
//# sourceMappingURL=chunk-6XCINXZ7.cjs.map
|
|
194
|
+
//# sourceMappingURL=chunk-6XCINXZ7.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/vector/filter/base.ts"],"names":[],"mappings":";;;AAyJA,IAAe,oBAAA,GAAf,MAAe,qBAAA,CAA6D;AAAA;AAAA;AAAA;AAAA,EAMhE,WAAW,GAAA,EAAmC;AACtD,IAAA,OAAO,GAAA,CAAI,WAAW,GAAG,CAAA;AAAA,EAC3B;AAAA,EAEA,OAA0B,eAAA,GAAmC,CAAC,KAAA,EAAO,KAAK,CAAA;AAAA,EAC1E,OAA0B,iBAAA,GAAuC,CAAC,KAAA,EAAO,MAAA,EAAQ,OAAO,MAAM,CAAA;AAAA,EAC9F,OAA0B,eAAA,GAAmC,CAAC,KAAA,EAAO,MAAA,EAAQ,QAAQ,YAAY,CAAA;AAAA,EACjG,OAA0B,iBAAA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AA;AAAA,UACF;AAEA,UAAA,IAAI,IAAA,IAAQ,CAAC,IAAA,CAAK,iBAAA,CAAkB,IAAA,CAAK,MAAM,GAAG,CAAA,CAAE,GAAA,EAAM,CAAA,EAAG;AAC3D,YAAA,WAAA,GAAc,KAAA;AACd,YAAA,QAAA,CAAS,KAAK,qBAAA,CAAqB,aAAA,CAAc,iCAAA,CAAkC,GAAA,EAAK,OAAO,CAAC,CAAA;AAChG,YAAA;AAAA,UACF;AAEA,UAAA,IAAI,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA,EAAG;AACxB,YAAA,MAAM,qBAAqB,KAAA,CAAM,IAAA;AAAA,cAC/B,UACE,OAAO,IAAA,KAAS,QAAA,IAChB,MAAA,CAAO,KAAK,IAAI,CAAA,CAAE,MAAA,KAAW,CAAA,IAC7B,KAAK,eAAA,CAAgB,MAAA,CAAO,KAAK,IAAI,CAAA,CAAE,CAAC,CAAE;AAAA,aAC9C;AAEA,YAAA,IAAI,kBAAA,EAAoB;AACtB,cAAA,WAAA,GAAc,KAAA;AACd,cAAA,QAAA,CAAS,IAAA,CAAK,qBAAA,CAAqB,aAAA,CAAc,gCAAA,CAAiC,OAAO,CAAC,CAAA;AAC1F,cAAA;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAGA,MAAA,MAAM,gBAAA,GAAmB,IAAA,CAAK,qBAAA,CAAsB,KAAA,EAAO,OAAO,CAAA;AAClE,MAAA,IAAI,CAAC,iBAAiB,SAAA,EAAW;AAC/B,QAAA,WAAA,GAAc,KAAA;AACd,QAAA,QAAA,CAAS,IAAA,CAAK,GAAG,gBAAA,CAAiB,QAAQ,CAAA;AAAA,MAC5C;AAAA,IACF;AAEA,IAAA,OAAO,EAAE,SAAA,EAAW,WAAA,EAAa,QAAA,EAAS;AAAA,EAC5C;AACF","file":"chunk-6XCINXZ7.cjs","sourcesContent":["type BasicOperator =\n | '$eq' // Matches values equal to specified value\n | '$ne'; // Matches values not equal\n\ntype NumericOperator =\n | '$gt' // Greater than\n | '$gte' // Greater than or equal\n | '$lt' // Less than\n | '$lte'; // Less than or equal\n\ntype LogicalOperator =\n | '$and' // Joins query clauses with logical AND\n | '$not' // Inverts the effect of a query expression\n | '$nor' // Joins query clauses with logical NOR\n | '$or'; // Joins query clauses with logical OR\n\ntype ArrayOperator =\n | '$all' // Matches arrays containing all elements\n | '$in' // Matches any value in array\n | '$nin' // Matches none of the values in array\n | '$elemMatch'; // Matches documents that contain an array field with at least one element that matches all the specified query criteria\n\ntype ElementOperator = '$exists'; // Matches documents that have the specified field\n\ntype RegexOperator = '$regex' | '$options'; // Matches documents that have the specified field\n\n// Union of all supported operators\ntype QueryOperator =\n | BasicOperator\n | NumericOperator\n | LogicalOperator\n | ArrayOperator\n | ElementOperator\n | RegexOperator;\n\ntype EmptyObject = Record<string, never>;\n\ntype FilterValue = string | number | boolean | Date | null | undefined | EmptyObject;\n\n// Logical operators are handled at the top level as objects, not as values here\n// $and, $or, $nor, $not are handled in LogicalCondition\ntype OperatorValueMap<Op extends string = string, ValueMap extends Record<string, any> = any> = {\n $eq: FilterValue;\n $ne: FilterValue;\n $gt: number | string | Date;\n $gte: number | string | Date;\n $lt: number | string | Date;\n $lte: number | string | Date;\n $all: FilterValue[];\n $in: FilterValue[];\n $nin: FilterValue[];\n $elemMatch: Record<string, unknown>;\n $exists: boolean;\n $regex: string | RegExp;\n $options: string;\n $not: OperatorCondition<Op, ValueMap> | RegExp;\n};\n\ntype LogicalOperatorValueMap = {\n $and: 'array';\n $or: 'array';\n $nor: 'array';\n $not: 'object';\n};\n\ntype BlacklistedRootOperators =\n | '$eq'\n | '$ne'\n | '$gt'\n | '$gte'\n | '$lt'\n | '$lte'\n | '$in'\n | '$nin'\n | '$all'\n | '$exists'\n | '$regex'\n | '$options'\n | '$elemMatch';\n\ntype VectorFieldValue = FilterValue | FilterValue[];\n\n// Vector filter parameterized by operator set\ntype VectorFilter<\n Op extends keyof ValueMap = keyof OperatorValueMap,\n ValueMap extends Record<string, any> = OperatorValueMap,\n LogicalValueMap extends Record<string, any> = LogicalOperatorValueMap,\n Blacklisted extends string = BlacklistedRootOperators,\n FieldValue = VectorFieldValue,\n> = FilterCondition<Op, ValueMap, LogicalValueMap, Blacklisted, FieldValue> | null | undefined;\n\ntype FilterCondition<\n Op extends keyof ValueMap = keyof OperatorValueMap,\n ValueMap extends Record<string, any> = OperatorValueMap,\n LogicalValueMap extends Record<string, any> = LogicalOperatorValueMap,\n Blacklisted extends string = BlacklistedRootOperators,\n FieldValue = VectorFieldValue,\n> = (FieldCondition<Op, ValueMap, FieldValue> | LogicalCondition<Op, ValueMap, LogicalValueMap>) &\n ForbiddenRootOperators<Blacklisted>;\n\n// Field condition can be a value or an operator condition\ntype FieldCondition<\n Op extends keyof ValueMap = keyof OperatorValueMap,\n ValueMap extends Record<string, any> = OperatorValueMap,\n FieldValue = VectorFieldValue,\n> = {\n [field: string]: OperatorCondition<Op, ValueMap> | FieldValue;\n};\n\ntype ForbiddenRootOperators<Blacklisted extends string> = {\n [K in Blacklisted]?: never;\n};\n\n// Logical conditions\ntype LogicalCondition<\n Op extends keyof ValueMap = keyof OperatorValueMap,\n ValueMap extends Record<string, any> = OperatorValueMap,\n LogicalValueMap extends Record<string, any> = LogicalOperatorValueMap,\n> = {\n [K in keyof LogicalValueMap]: LogicalValueMap[K] extends 'array'\n ? {\n [P in K]: Array<LogicalBranch<Op, ValueMap, LogicalValueMap>>;\n }\n : {\n [P in K]: LogicalBranch<Op, ValueMap, LogicalValueMap>;\n };\n}[keyof LogicalValueMap];\n\ntype LogicalBranch<\n Op extends keyof ValueMap = keyof OperatorValueMap,\n ValueMap extends Record<string, any> = OperatorValueMap,\n LogicalValueMap extends Record<string, any> = LogicalOperatorValueMap,\n> = FieldCondition<Op, ValueMap> | LogicalCondition<Op, ValueMap, LogicalValueMap>;\n\n// Base operator condition, parameterized by operator set\ntype OperatorCondition<\n Op extends keyof ValueMap = keyof OperatorValueMap,\n ValueMap extends Record<string, any> = OperatorValueMap,\n> = {\n [K in Exclude<Op, '$and' | '$or' | '$nor'>]?: ValueMap[K];\n};\n\ntype OperatorSupport = {\n logical?: LogicalOperator[];\n array?: ArrayOperator[];\n basic?: BasicOperator[];\n numeric?: NumericOperator[];\n element?: ElementOperator[];\n regex?: RegexOperator[];\n custom?: string[];\n};\n\n// Base abstract class for filter translators\nabstract class BaseFilterTranslator<Filter = VectorFilter, Result = Filter> {\n abstract translate(filter: Filter): Result;\n\n /**\n * Operator type checks\n */\n protected isOperator(key: string): key is QueryOperator {\n return key.startsWith('$');\n }\n\n protected static readonly BASIC_OPERATORS: BasicOperator[] = ['$eq', '$ne'];\n protected static readonly NUMERIC_OPERATORS: NumericOperator[] = ['$gt', '$gte', '$lt', '$lte'];\n protected static readonly ARRAY_OPERATORS: ArrayOperator[] = ['$in', '$nin', '$all', '$elemMatch'];\n protected static readonly LOGICAL_OPERATORS: LogicalOperator[] = ['$and', '$or', '$not', '$nor'];\n protected static readonly ELEMENT_OPERATORS: ElementOperator[] = ['$exists'];\n protected static readonly REGEX_OPERATORS: RegexOperator[] = ['$regex', '$options'];\n\n public static readonly DEFAULT_OPERATORS = {\n logical: BaseFilterTranslator.LOGICAL_OPERATORS,\n basic: BaseFilterTranslator.BASIC_OPERATORS,\n numeric: BaseFilterTranslator.NUMERIC_OPERATORS,\n array: BaseFilterTranslator.ARRAY_OPERATORS,\n element: BaseFilterTranslator.ELEMENT_OPERATORS,\n regex: BaseFilterTranslator.REGEX_OPERATORS,\n };\n\n protected isLogicalOperator(key: string): key is LogicalOperator {\n return BaseFilterTranslator.DEFAULT_OPERATORS.logical.includes(key as LogicalOperator);\n }\n\n protected isBasicOperator(key: string): key is BasicOperator {\n return BaseFilterTranslator.DEFAULT_OPERATORS.basic.includes(key as BasicOperator);\n }\n\n protected isNumericOperator(key: string): key is NumericOperator {\n return BaseFilterTranslator.DEFAULT_OPERATORS.numeric.includes(key as NumericOperator);\n }\n\n protected isArrayOperator(key: string): key is ArrayOperator {\n return BaseFilterTranslator.DEFAULT_OPERATORS.array.includes(key as ArrayOperator);\n }\n\n protected isElementOperator(key: string): key is ElementOperator {\n return BaseFilterTranslator.DEFAULT_OPERATORS.element.includes(key as ElementOperator);\n }\n\n protected isRegexOperator(key: string): key is RegexOperator {\n return BaseFilterTranslator.DEFAULT_OPERATORS.regex.includes(key as RegexOperator);\n }\n\n protected isFieldOperator(key: string): key is QueryOperator {\n return this.isOperator(key) && !this.isLogicalOperator(key);\n }\n\n protected isCustomOperator(key: string): boolean {\n const support = this.getSupportedOperators();\n return support.custom?.includes(key) ?? false;\n }\n\n protected getSupportedOperators(): OperatorSupport {\n return BaseFilterTranslator.DEFAULT_OPERATORS;\n }\n\n protected isValidOperator(key: string): boolean {\n const support = this.getSupportedOperators();\n const allSupported = Object.values(support).flat();\n return allSupported.includes(key as QueryOperator);\n }\n\n /**\n * Value normalization for comparison operators\n */\n protected normalizeComparisonValue(value: any): any {\n if (value instanceof Date) {\n return value.toISOString();\n }\n\n // Handle -0 case\n if (typeof value === 'number' && Object.is(value, -0)) {\n return 0;\n }\n return value;\n }\n\n /**\n * Helper method to simulate $all operator using $and + $eq when needed.\n * Some vector stores don't support $all natively.\n */\n protected simulateAllOperator(field: string, values: any[]): VectorFilter<keyof OperatorValueMap, OperatorValueMap> {\n return {\n $and: values.map(value => ({\n [field]: { $in: [this.normalizeComparisonValue(value)] },\n })),\n };\n }\n\n /**\n * Utility functions for type checking\n */\n protected isPrimitive(value: any): boolean {\n return (\n value === null ||\n value === undefined ||\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n );\n }\n\n protected isRegex(value: any): boolean {\n return value instanceof RegExp;\n }\n\n protected isEmpty(obj: any): boolean {\n return obj === null || obj === undefined || (typeof obj === 'object' && Object.keys(obj).length === 0);\n }\n\n protected static readonly ErrorMessages = {\n UNSUPPORTED_OPERATOR: (op: string) => `Unsupported operator: ${op}`,\n INVALID_LOGICAL_OPERATOR_LOCATION: (op: string, path: string) =>\n `Logical operator ${op} cannot be used at field level: ${path}`,\n NOT_REQUIRES_OBJECT: `$not operator requires an object`,\n NOT_CANNOT_BE_EMPTY: `$not operator cannot be empty`,\n INVALID_LOGICAL_OPERATOR_CONTENT: (path: string) =>\n `Logical operators must contain field conditions, not direct operators: ${path}`,\n INVALID_TOP_LEVEL_OPERATOR: (op: string) => `Invalid top-level operator: ${op}`,\n ELEM_MATCH_REQUIRES_OBJECT: `$elemMatch requires an object with conditions`,\n } as const;\n\n /**\n * Helper to handle array value normalization consistently\n */\n protected normalizeArrayValues(values: any[]): any[] {\n return values.map(value => this.normalizeComparisonValue(value));\n }\n\n protected validateFilter(filter: Filter): void {\n const validation = this.validateFilterSupport(filter);\n if (!validation.supported) {\n throw new Error(validation.messages.join(', '));\n }\n }\n\n /**\n * Validates if a filter structure is supported by the specific vector DB\n * and returns detailed validation information.\n */\n private validateFilterSupport(\n node: Filter,\n path: string = '',\n ): {\n supported: boolean;\n messages: string[];\n } {\n const messages: string[] = [];\n\n // Handle primitives and empty values\n if (this.isPrimitive(node) || this.isEmpty(node)) {\n return { supported: true, messages: [] };\n }\n\n // Handle arrays\n if (Array.isArray(node)) {\n const arrayResults = node.map(item => this.validateFilterSupport(item, path));\n const arrayMessages = arrayResults.flatMap(r => r.messages);\n return {\n supported: arrayResults.every(r => r.supported),\n messages: arrayMessages,\n };\n }\n\n // Process object entries\n const nodeObj = node as Record<string, any>;\n let isSupported = true;\n\n for (const [key, value] of Object.entries(nodeObj)) {\n const newPath = path ? `${path}.${key}` : key;\n // Check if the key is an operator\n if (this.isOperator(key)) {\n if (!this.isValidOperator(key)) {\n isSupported = false;\n messages.push(BaseFilterTranslator.ErrorMessages.UNSUPPORTED_OPERATOR(key));\n continue;\n }\n\n // Add check for non-logical operators at top level\n if (!path && !this.isLogicalOperator(key)) {\n isSupported = false;\n messages.push(BaseFilterTranslator.ErrorMessages.INVALID_TOP_LEVEL_OPERATOR(key));\n continue;\n }\n\n // In the translate method or wherever operators are handled\n if (key === '$elemMatch' && (typeof value !== 'object' || Array.isArray(value))) {\n isSupported = false;\n messages.push(BaseFilterTranslator.ErrorMessages.ELEM_MATCH_REQUIRES_OBJECT);\n continue;\n }\n\n // Special validation for logical operators\n if (this.isLogicalOperator(key)) {\n if (key === '$not') {\n if (Array.isArray(value) || typeof value !== 'object') {\n isSupported = false;\n messages.push(BaseFilterTranslator.ErrorMessages.NOT_REQUIRES_OBJECT);\n continue;\n }\n if (this.isEmpty(value)) {\n isSupported = false;\n messages.push(BaseFilterTranslator.ErrorMessages.NOT_CANNOT_BE_EMPTY);\n continue;\n }\n // $not can be used at field level or top level\n continue;\n }\n // Other logical operators can only be at top level or nested in logical operators\n if (path && !this.isLogicalOperator(path.split('.').pop()!)) {\n isSupported = false;\n messages.push(BaseFilterTranslator.ErrorMessages.INVALID_LOGICAL_OPERATOR_LOCATION(key, newPath));\n continue;\n }\n\n if (Array.isArray(value)) {\n const hasDirectOperators = value.some(\n item =>\n typeof item === 'object' &&\n Object.keys(item).length === 1 &&\n this.isFieldOperator(Object.keys(item)[0]!),\n );\n\n if (hasDirectOperators) {\n isSupported = false;\n messages.push(BaseFilterTranslator.ErrorMessages.INVALID_LOGICAL_OPERATOR_CONTENT(newPath));\n continue;\n }\n }\n }\n }\n\n // Recursively validate nested value\n const nestedValidation = this.validateFilterSupport(value, newPath);\n if (!nestedValidation.supported) {\n isSupported = false;\n messages.push(...nestedValidation.messages);\n }\n }\n\n return { supported: isSupported, messages };\n }\n}\n\n// Export types and base class\nexport {\n type QueryOperator,\n type BasicOperator,\n type NumericOperator,\n type LogicalOperator,\n type ArrayOperator,\n type RegexOperator,\n type ElementOperator,\n type VectorFilter,\n type FilterValue,\n type VectorFieldValue,\n type FieldCondition,\n type OperatorCondition,\n type OperatorSupport,\n type OperatorValueMap,\n type LogicalOperatorValueMap,\n type BlacklistedRootOperators,\n BaseFilterTranslator,\n};\n"]}
|
|
@@ -114,6 +114,20 @@ function getOrCreateSpan(options) {
|
|
|
114
114
|
}
|
|
115
115
|
});
|
|
116
116
|
}
|
|
117
|
+
async function executeWithContext(params) {
|
|
118
|
+
const { span, fn } = params;
|
|
119
|
+
if (span?.executeInContext) {
|
|
120
|
+
return span.executeInContext(fn);
|
|
121
|
+
}
|
|
122
|
+
return fn();
|
|
123
|
+
}
|
|
124
|
+
function executeWithContextSync(params) {
|
|
125
|
+
const { span, fn } = params;
|
|
126
|
+
if (span?.executeInContextSync) {
|
|
127
|
+
return span.executeInContextSync(fn);
|
|
128
|
+
}
|
|
129
|
+
return fn();
|
|
130
|
+
}
|
|
117
131
|
|
|
118
132
|
// src/observability/context.ts
|
|
119
133
|
var AGENT_GETTERS = ["getAgent", "getAgentById"];
|
|
@@ -267,7 +281,9 @@ exports.NoOpObservability = NoOpObservability;
|
|
|
267
281
|
exports.SamplingStrategyType = SamplingStrategyType;
|
|
268
282
|
exports.SpanType = SpanType;
|
|
269
283
|
exports.TracingEventType = TracingEventType;
|
|
284
|
+
exports.executeWithContext = executeWithContext;
|
|
285
|
+
exports.executeWithContextSync = executeWithContextSync;
|
|
270
286
|
exports.getOrCreateSpan = getOrCreateSpan;
|
|
271
287
|
exports.wrapMastra = wrapMastra;
|
|
272
|
-
//# sourceMappingURL=chunk-
|
|
273
|
-
//# sourceMappingURL=chunk-
|
|
288
|
+
//# sourceMappingURL=chunk-72YCRTEX.cjs.map
|
|
289
|
+
//# sourceMappingURL=chunk-72YCRTEX.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/observability/types/tracing.ts","../src/observability/no-op.ts","../src/observability/utils.ts","../src/observability/context.ts"],"names":["SpanType","InternalSpans","SamplingStrategyType","TracingEventType"],"mappings":";;;AAiBO,IAAK,QAAA,qBAAAA,SAAAA,KAAL;AAEL,EAAAA,UAAA,WAAA,CAAA,GAAY,WAAA;AAEZ,EAAAA,UAAA,SAAA,CAAA,GAAU,SAAA;AAEV,EAAAA,UAAA,kBAAA,CAAA,GAAmB,k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,EAAA,IAAI;AACF,IAAA,OAAO,IAAI,MAAM,GAAA,EAAK;AAAA,MACpB,GAAA,CAAI,QAAQ,IAAA,EAAM;AAChB,QAAA,IAAI;AACF,UAAA,IAAI,SAAS,OAAA,EAAS;AACpB,YAAA,OAAO,CAAC,YAAA,GAAoB,EAAC,KAAM;AACjC,cAAA,OAAQ,OAAe,KAAA,CAAM;AAAA,gBAC3B,GAAG,YAAA;AAAA,gBACH,cAAA,EAAgB,aAAa,cAAA,IAAkB;AAAA,eAChD,CAAA;AAAA,YACH,CAAA;AAAA,UACF;AAGA,UAAA,MAAM,KAAA,GAAS,OAAe,IAAI,CAAA;AAClC,UAAA,OAAO,OAAO,KAAA,KAAU,UAAA,GAAa,KAAA,CAAM,IAAA,CAAK,MAAM,CAAA,GAAI,KAAA;AAAA,QAC5D,SAAS,KAAA,EAAO;AACd,UAAA,OAAA,CAAQ,IAAA,CAAK,gEAAgE,KAAK,CAAA;AAClF,UAAA,MAAM,KAAA,GAAS,OAAe,IAAI,CAAA;AAClC,UAAA,OAAO,OAAO,KAAA,KAAU,UAAA,GAAa,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-72YCRTEX.cjs","sourcesContent":["/**\n * Tracing interfaces\n */\nimport type { MastraError } from '../../error';\nimport type { IMastraLogger } from '../../logger';\nimport type { Mastra } from '../../mastra';\nimport type { RequestContext } from '../../request-context';\nimport type { LanguageModelUsage, ProviderMetadata } from '../../stream/types';\nimport type { WorkflowRunStatus, WorkflowStepStatus } from '../../workflows';\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\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 /** Agent identifier */\n agentId: string;\n /** Human-readable agent name */\n agentName?: string;\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}\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 /** Agent identifier (when generation is part of an agent run) */\n agentId?: string;\n /** Human-readable agent name (when generation is part of an agent run) */\n agentName?: string;\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 toolId?: string;\n toolType?: string;\n toolDescription?: string;\n success?: boolean;\n}\n\n/**\n * MCP Tool Call attributes\n */\nexport interface MCPToolCallAttributes extends AIBaseAttributes {\n /** Id of the MCP tool/function */\n toolId: string;\n /** MCP server identifier */\n mcpServer: string;\n /** MCP server version */\n serverVersion?: string;\n /** Whether tool execution was successful */\n success?: boolean;\n}\n\n/**\n * Processor attributes\n */\nexport interface ProcessorRunAttributes extends AIBaseAttributes {\n /** Name of the Processor */\n processorName: string;\n /** Processor type (input or output) */\n processorType: 'input' | 'output';\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}\n\n/**\n * Workflow Run attributes\n */\nexport interface WorkflowRunAttributes extends AIBaseAttributes {\n /** Workflow identifier */\n workflowId: string;\n /** Workflow status */\n status?: WorkflowRunStatus;\n}\n\n/**\n * Workflow Step attributes\n */\nexport interface WorkflowStepAttributes extends AIBaseAttributes {\n /** Step identifier */\n stepId: string;\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/**\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 /** 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?: {\n message: string;\n id?: string;\n domain?: string;\n category?: string;\n details?: Record<string, any>;\n };\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 /** 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\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 * Exported Span interface, used for tracing exporters\n */\nexport interface ExportedSpan<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 * 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\nexport interface IModelSpanTracker {\n getTracingContext(): TracingContext;\n reportGenerationError(options: ErrorSpanOptions<SpanType.MODEL_GENERATION>): void;\n endGeneration(options?: EndGenerationOptions): void;\n wrapStream<T extends { pipeThrough: Function }>(stream: T): T;\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// Tracing Interfaces\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 * 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// ============================================================================\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 /** 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 * 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 /** 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\nexport interface EndSpanOptions<TType extends SpanType> extends UpdateBaseOptions<TType> {\n /** Output data */\n output?: any;\n}\n\nexport interface UpdateSpanOptions<TType extends SpanType> extends UpdateBaseOptions<TType> {\n /** Input data */\n input?: any;\n /** Output data */\n output?: any;\n}\n\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\nexport interface GetOrCreateSpanOptions<TType extends SpanType> {\n type: TType;\n name: 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// Lifecycle Types\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 * 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\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\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};\n\n// ============================================================================\n// Registry Config Interfaces\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 observablity configuration.\n * Supports dot notation for nested values.\n */\n requestContextKeys?: string[];\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// Sampling Strategy Interfaces\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// 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\nexport interface InitExporterOptions {\n mastra?: Mastra;\n config?: ObservabilityInstanceConfig;\n}\n\nexport interface InitBridgeOptions {\n mastra?: Mastra;\n config?: ObservabilityInstanceConfig;\n}\n\n/**\n * Interface for tracing exporters\n */\nexport interface ObservabilityExporter {\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 /** Export tracing events */\n exportTracingEvent(event: TracingEvent): Promise<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 /** Shutdown exporter */\n shutdown(): Promise<void>;\n}\n\n/**\n * Interface for observability bridges\n */\nexport interface ObservabilityBridge {\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 * Export Mastra tracing events to OTEL infrastructure\n * Called for SPAN_STARTED, SPAN_UPDATED, SPAN_ENDED events\n *\n * @param event - Tracing event with exported span\n */\n exportTracingEvent(event: TracingEvent): Promise<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 /** Shutdown bridge and cleanup resources */\n shutdown(): Promise<void>;\n}\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// Tracing Config Selector Interfaces\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// Tracing Storage Interfaces\n// ============================================================================\n\nexport type TracingStorageStrategy = 'realtime' | 'batch-with-updates' | 'insert-only';\n","import type { Mastra } from '..';\nimport type { IMastraLogger } from '../logger';\nimport type { ObservabilityInstance, ConfigSelectorOptions, ObservabilityEntrypoint, ConfigSelector } from './types';\n\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 });\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 * 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 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 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 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 tracingContext: 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"]}
|