@mastra/core 1.0.0-beta.21 → 1.0.0-beta.22
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 +356 -0
- package/dist/action/index.d.ts +7 -7
- package/dist/action/index.d.ts.map +1 -1
- package/dist/agent/agent-legacy.d.ts.map +1 -1
- package/dist/agent/agent.d.ts +100 -18
- package/dist/agent/agent.d.ts.map +1 -1
- package/dist/agent/agent.types.d.ts +22 -18
- package/dist/agent/agent.types.d.ts.map +1 -1
- package/dist/agent/index.cjs +13 -13
- package/dist/agent/index.d.ts +1 -1
- package/dist/agent/index.d.ts.map +1 -1
- package/dist/agent/index.js +2 -2
- package/dist/agent/message-list/adapters/AIV4Adapter.d.ts.map +1 -1
- package/dist/agent/message-list/index.cjs +18 -18
- package/dist/agent/message-list/index.js +1 -1
- package/dist/agent/message-list/message-list.d.ts +2 -1
- package/dist/agent/message-list/message-list.d.ts.map +1 -1
- package/dist/agent/trip-wire.d.ts +1 -2
- package/dist/agent/trip-wire.d.ts.map +1 -1
- package/dist/agent/types.d.ts +9 -10
- package/dist/agent/types.d.ts.map +1 -1
- package/dist/agent/utils.d.ts +7 -42
- package/dist/agent/utils.d.ts.map +1 -1
- package/dist/agent/workflows/prepare-stream/index.d.ts +6 -118
- package/dist/agent/workflows/prepare-stream/index.d.ts.map +1 -1
- package/dist/agent/workflows/prepare-stream/map-results-step.d.ts +7 -11
- 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 +4 -68
- 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 +3 -45
- package/dist/agent/workflows/prepare-stream/prepare-tools-step.d.ts.map +1 -1
- package/dist/agent/workflows/prepare-stream/schema.d.ts +10 -10
- package/dist/agent/workflows/prepare-stream/stream-step.d.ts +2 -8
- package/dist/agent/workflows/prepare-stream/stream-step.d.ts.map +1 -1
- package/dist/{chunk-HJXEZSNI.js → chunk-3XY64RAM.js} +5 -5
- package/dist/{chunk-HJXEZSNI.js.map → chunk-3XY64RAM.js.map} +1 -1
- package/dist/{chunk-XSJNTLM7.js → chunk-453NPBJ7.js} +479 -47
- package/dist/chunk-453NPBJ7.js.map +1 -0
- package/dist/{chunk-3CZ42NBZ.js → chunk-5UVSKF5L.js} +17 -14
- package/dist/chunk-5UVSKF5L.js.map +1 -0
- package/dist/{chunk-XKDVT3ZH.cjs → chunk-67ZKOPA4.cjs} +480 -48
- package/dist/chunk-67ZKOPA4.cjs.map +1 -0
- package/dist/{chunk-YLP5IWH2.js → chunk-7IYWOBLG.js} +4 -4
- package/dist/{chunk-YLP5IWH2.js.map → chunk-7IYWOBLG.js.map} +1 -1
- package/dist/{chunk-3RCMDLCG.cjs → chunk-ALQFYWAR.cjs} +12 -12
- package/dist/{chunk-3RCMDLCG.cjs.map → chunk-ALQFYWAR.cjs.map} +1 -1
- package/dist/{chunk-PC3FBUWH.js → chunk-C4CIC3LZ.js} +2 -2
- package/dist/chunk-C4CIC3LZ.js.map +1 -0
- package/dist/{chunk-7JGQWNV5.js → chunk-CPLRD2VP.js} +3 -3
- package/dist/{chunk-7JGQWNV5.js.map → chunk-CPLRD2VP.js.map} +1 -1
- package/dist/{chunk-AHN7K3VE.js → chunk-CQ2E577C.js} +5 -5
- package/dist/chunk-CQ2E577C.js.map +1 -0
- package/dist/{chunk-A4MCHA5L.cjs → chunk-CVLIEFWM.cjs} +100 -819
- package/dist/chunk-CVLIEFWM.cjs.map +1 -0
- package/dist/{chunk-XBZWAUZ3.js → chunk-IFPQ2MLB.js} +25 -12
- package/dist/chunk-IFPQ2MLB.js.map +1 -0
- package/dist/{chunk-DVJZZAZA.cjs → chunk-IHD36QFA.cjs} +7 -7
- package/dist/{chunk-DVJZZAZA.cjs.map → chunk-IHD36QFA.cjs.map} +1 -1
- package/dist/{chunk-WMJEP45F.cjs → chunk-J4KVR4DZ.cjs} +25 -18
- package/dist/chunk-J4KVR4DZ.cjs.map +1 -0
- package/dist/{chunk-3RFSIHFR.js → chunk-K2LPTKSY.js} +4 -720
- package/dist/chunk-K2LPTKSY.js.map +1 -0
- package/dist/{chunk-FY3PYSMK.cjs → chunk-KHO4KFXW.cjs} +5 -5
- package/dist/{chunk-FY3PYSMK.cjs.map → chunk-KHO4KFXW.cjs.map} +1 -1
- package/dist/{chunk-W7R7GPNN.cjs → chunk-MGPIVG2O.cjs} +9 -9
- package/dist/chunk-MGPIVG2O.cjs.map +1 -0
- package/dist/{chunk-KGE3KAM7.js → chunk-N3PAHTKU.js} +23 -3
- package/dist/chunk-N3PAHTKU.js.map +1 -0
- package/dist/{chunk-O4H44CMA.js → chunk-N7TDP7ZE.js} +586 -117
- package/dist/chunk-N7TDP7ZE.js.map +1 -0
- package/dist/{chunk-I5GMA5UM.cjs → chunk-NPIYNC5A.cjs} +9 -9
- package/dist/{chunk-I5GMA5UM.cjs.map → chunk-NPIYNC5A.cjs.map} +1 -1
- package/dist/{chunk-AW7FISLD.cjs → chunk-OZ75PBBK.cjs} +27 -7
- package/dist/chunk-OZ75PBBK.cjs.map +1 -0
- package/dist/{chunk-JMAPJWVG.cjs → chunk-OZCUIZRA.cjs} +2021 -1426
- package/dist/chunk-OZCUIZRA.cjs.map +1 -0
- package/dist/{chunk-6OPEMI2Q.cjs → chunk-PM3UIIBK.cjs} +2 -3
- package/dist/{chunk-6OPEMI2Q.cjs.map → chunk-PM3UIIBK.cjs.map} +1 -1
- package/dist/{chunk-CISH55FP.js → chunk-PSIJ6OSV.js} +16 -9
- package/dist/chunk-PSIJ6OSV.js.map +1 -0
- package/dist/{chunk-UOZ3GJY2.cjs → chunk-PTK74KG4.cjs} +2 -2
- package/dist/chunk-PTK74KG4.cjs.map +1 -0
- package/dist/{chunk-O5IPTMEH.cjs → chunk-Q5QQDMSD.cjs} +32 -29
- package/dist/chunk-Q5QQDMSD.cjs.map +1 -0
- package/dist/{chunk-UVHSM2GU.cjs → chunk-SMM2C4KH.cjs} +6 -4
- package/dist/chunk-SMM2C4KH.cjs.map +1 -0
- package/dist/{chunk-UXLQEGIN.cjs → chunk-SVPXZEU7.cjs} +35 -22
- package/dist/chunk-SVPXZEU7.cjs.map +1 -0
- package/dist/{chunk-SOSXN7X4.cjs → chunk-TU6MNGBB.cjs} +619 -151
- package/dist/chunk-TU6MNGBB.cjs.map +1 -0
- package/dist/{chunk-EK7E4ETB.js → chunk-TX5GUG5Q.js} +3 -3
- package/dist/{chunk-EK7E4ETB.js.map → chunk-TX5GUG5Q.js.map} +1 -1
- package/dist/{chunk-SQ7T6FWC.cjs → chunk-UAH236P2.cjs} +13 -13
- package/dist/{chunk-SQ7T6FWC.cjs.map → chunk-UAH236P2.cjs.map} +1 -1
- package/dist/{chunk-AIJ6HPJG.js → chunk-UL7TJCKA.js} +4 -4
- package/dist/{chunk-AIJ6HPJG.js.map → chunk-UL7TJCKA.js.map} +1 -1
- package/dist/{chunk-IC2MIQBW.js → chunk-UVOQLIWL.js} +1922 -1326
- package/dist/chunk-UVOQLIWL.js.map +1 -0
- package/dist/{chunk-IMLORTHO.js → chunk-WANKWENG.js} +5 -5
- package/dist/{chunk-IMLORTHO.js.map → chunk-WANKWENG.js.map} +1 -1
- package/dist/{chunk-ICU4Z5MO.cjs → chunk-X7DR353F.cjs} +8 -8
- package/dist/{chunk-ICU4Z5MO.cjs.map → chunk-X7DR353F.cjs.map} +1 -1
- package/dist/{chunk-6TBWJV35.js → chunk-Y22QMA7S.js} +6 -4
- package/dist/chunk-Y22QMA7S.js.map +1 -0
- package/dist/{chunk-FT7DFPAL.js → chunk-YYNZEEOO.js} +5 -5
- package/dist/{chunk-FT7DFPAL.js.map → chunk-YYNZEEOO.js.map} +1 -1
- package/dist/di/index.cjs +4 -4
- package/dist/di/index.js +1 -1
- package/dist/docs/README.md +6 -5
- package/dist/docs/SKILL.md +6 -5
- package/dist/docs/SOURCE_MAP.json +288 -293
- package/dist/docs/agents/01-overview.md +2 -2
- package/dist/docs/agents/02-using-tools.md +5 -0
- package/dist/docs/agents/04-structured-output.md +24 -4
- package/dist/docs/agents/06-processors.md +65 -1
- package/dist/docs/agents/08-agent-approval.md +5 -6
- package/dist/docs/agents/09-network-approval.md +274 -0
- package/dist/docs/agents/{10-reference.md → 11-reference.md} +1 -1
- package/dist/docs/ai-sdk/01-reference.md +1 -1
- package/dist/docs/cli/01-reference.md +1 -1
- package/dist/docs/client-js/01-reference.md +10 -5
- package/dist/docs/configuration.mdx/01-reference.md +750 -0
- package/dist/docs/core/01-reference.md +9 -35
- package/dist/docs/deployer/01-reference.md +19 -6
- package/dist/docs/evals/01-overview.md +5 -5
- package/dist/docs/evals/02-custom-scorers.md +49 -6
- package/dist/docs/evals/04-reference.md +10 -4
- package/dist/docs/mcp/01-overview.md +26 -16
- package/dist/docs/mcp/02-publishing-mcp-server.md +2 -2
- package/dist/docs/memory/01-overview.md +2 -2
- package/dist/docs/memory/02-storage.md +59 -25
- package/dist/docs/memory/03-working-memory.md +10 -6
- package/dist/docs/memory/04-semantic-recall.md +2 -4
- package/dist/docs/memory/05-memory-processors.md +2 -3
- package/dist/docs/memory/06-reference.md +2 -4
- package/dist/docs/observability/01-overview.md +1 -1
- package/dist/docs/observability/02-logging.md +4 -5
- package/dist/docs/observability/03-overview.md +69 -13
- package/dist/docs/observability/09-datadog.md +169 -0
- package/dist/docs/observability/10-laminar.md +95 -0
- package/dist/docs/observability/{11-otel.md → 13-otel.md} +12 -7
- package/dist/docs/observability/{13-reference.md → 15-reference.md} +125 -1
- package/dist/docs/processors/01-reference.md +23 -0
- package/dist/docs/rag/01-overview.md +1 -1
- package/dist/docs/rag/02-chunking-and-embedding.md +0 -1
- package/dist/docs/rag/03-vector-databases.md +10 -5
- package/dist/docs/rag/04-retrieval.md +5 -6
- package/dist/docs/rag/06-reference.md +4 -5
- package/dist/docs/server/01-mastra-server.md +32 -49
- package/dist/docs/server/02-custom-adapters.md +5 -2
- package/dist/docs/server/04-request-context.md +50 -11
- package/dist/docs/server/05-custom-api-routes.md +1 -1
- package/dist/docs/server/06-mastra-client.md +2 -2
- package/dist/docs/storage/01-reference.md +99 -23
- package/dist/docs/streaming/04-reference.md +6 -1
- package/dist/docs/tools/01-reference.md +380 -25
- package/dist/docs/tools-mcp/01-mcp-overview.md +10 -2
- package/dist/docs/tools-mcp/02-overview.md +4 -4
- package/dist/docs/vectors/01-reference.md +24 -11
- package/dist/docs/voice/01-overview.md +2 -2
- package/dist/docs/voice/05-reference.md +2 -2
- package/dist/docs/workflows/01-overview.md +5 -5
- package/dist/docs/workflows/04-agents-and-tools.md +4 -6
- package/dist/docs/workflows/06-suspend-and-resume.md +5 -7
- package/dist/docs/workflows/11-reference.md +1 -91
- package/dist/evals/base.d.ts.map +1 -1
- package/dist/evals/index.cjs +20 -20
- package/dist/evals/index.js +3 -3
- package/dist/evals/scoreTraces/index.cjs +5 -5
- package/dist/evals/scoreTraces/index.js +2 -2
- package/dist/evals/scoreTraces/scoreTracesWorkflow.d.ts +4 -67
- package/dist/evals/scoreTraces/scoreTracesWorkflow.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 +9 -9
- package/dist/llm/index.js +2 -2
- package/dist/llm/model/model.loop.d.ts +1 -2
- package/dist/llm/model/model.loop.d.ts.map +1 -1
- package/dist/llm/model/model.loop.types.d.ts +1 -2
- package/dist/llm/model/model.loop.types.d.ts.map +1 -1
- package/dist/llm/model/provider-types.generated.d.ts +224 -18
- package/dist/loop/index.cjs +12 -12
- package/dist/loop/index.js +1 -1
- package/dist/loop/loop.d.ts +1 -2
- package/dist/loop/loop.d.ts.map +1 -1
- package/dist/loop/network/index.d.ts +21 -80
- package/dist/loop/network/index.d.ts.map +1 -1
- package/dist/loop/network/run-command-tool.d.ts +14 -11
- package/dist/loop/network/run-command-tool.d.ts.map +1 -1
- package/dist/loop/network/validation.d.ts +3 -4
- package/dist/loop/network/validation.d.ts.map +1 -1
- package/dist/loop/test-utils/options.d.ts.map +1 -1
- package/dist/loop/types.d.ts +4 -5
- package/dist/loop/types.d.ts.map +1 -1
- package/dist/loop/workflows/agentic-execution/index.d.ts +31 -804
- package/dist/loop/workflows/agentic-execution/index.d.ts.map +1 -1
- package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts +22 -539
- 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 +13 -294
- 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 +2 -41
- package/dist/loop/workflows/agentic-execution/tool-call-step.d.ts.map +1 -1
- package/dist/loop/workflows/agentic-loop/index.d.ts +32 -805
- package/dist/loop/workflows/agentic-loop/index.d.ts.map +1 -1
- package/dist/loop/workflows/schema.d.ts +90 -91
- package/dist/loop/workflows/schema.d.ts.map +1 -1
- package/dist/loop/workflows/stream.d.ts +1 -2
- package/dist/loop/workflows/stream.d.ts.map +1 -1
- package/dist/mastra/index.cjs +2 -2
- package/dist/mastra/index.d.ts +28 -9
- package/dist/mastra/index.d.ts.map +1 -1
- package/dist/mastra/index.js +1 -1
- package/dist/memory/index.cjs +11 -11
- package/dist/memory/index.js +1 -1
- package/dist/memory/memory.d.ts +4 -2
- package/dist/memory/memory.d.ts.map +1 -1
- package/dist/observability/index.cjs +11 -11
- package/dist/observability/index.js +1 -1
- package/dist/observability/types/tracing.d.ts +45 -7
- package/dist/observability/types/tracing.d.ts.map +1 -1
- package/dist/processors/index.cjs +38 -38
- package/dist/processors/index.d.ts +3 -3
- package/dist/processors/index.d.ts.map +1 -1
- package/dist/processors/index.js +1 -1
- package/dist/processors/memory/semantic-recall.d.ts +2 -0
- package/dist/processors/memory/semantic-recall.d.ts.map +1 -1
- package/dist/processors/processors/structured-output.d.ts +2 -2
- package/dist/processors/processors/structured-output.d.ts.map +1 -1
- package/dist/processors/processors/token-limiter.d.ts +16 -10
- package/dist/processors/processors/token-limiter.d.ts.map +1 -1
- package/dist/processors/runner.d.ts +4 -4
- package/dist/processors/runner.d.ts.map +1 -1
- package/dist/processors/step-schema.d.ts +66 -67
- package/dist/processors/step-schema.d.ts.map +1 -1
- package/dist/provider-registry-C3IAGLLU.js +3 -0
- package/dist/{provider-registry-6DWM3X3I.js.map → provider-registry-C3IAGLLU.js.map} +1 -1
- package/dist/provider-registry-YH4FCTT2.cjs +40 -0
- package/dist/{provider-registry-DCECMUCQ.cjs.map → provider-registry-YH4FCTT2.cjs.map} +1 -1
- package/dist/provider-registry.json +477 -45
- package/dist/relevance/index.cjs +3 -3
- package/dist/relevance/index.js +1 -1
- package/dist/request-context/index.cjs +4 -4
- package/dist/request-context/index.d.ts +10 -9
- package/dist/request-context/index.d.ts.map +1 -1
- package/dist/request-context/index.js +1 -1
- package/dist/server/types.d.ts +1 -1
- package/dist/storage/constants.cjs +14 -14
- package/dist/storage/constants.d.ts +1 -1
- package/dist/storage/constants.js +1 -1
- package/dist/storage/domains/observability/types.d.ts +90 -90
- package/dist/storage/domains/workflows/inmemory.d.ts.map +1 -1
- package/dist/storage/index.cjs +93 -93
- package/dist/storage/index.js +2 -2
- package/dist/stream/MastraAgentNetworkStream.d.ts +8 -12
- package/dist/stream/MastraAgentNetworkStream.d.ts.map +1 -1
- package/dist/stream/aisdk/v5/compat/prepare-tools.d.ts.map +1 -1
- package/dist/stream/aisdk/v5/execute.d.ts +2 -3
- package/dist/stream/aisdk/v5/execute.d.ts.map +1 -1
- package/dist/stream/aisdk/v5/transform.d.ts +2 -3
- package/dist/stream/aisdk/v5/transform.d.ts.map +1 -1
- package/dist/stream/base/output-format-handlers.d.ts +2 -2
- package/dist/stream/base/output-format-handlers.d.ts.map +1 -1
- package/dist/stream/base/output.d.ts +76 -50
- package/dist/stream/base/output.d.ts.map +1 -1
- package/dist/stream/base/schema.d.ts +7 -2
- package/dist/stream/base/schema.d.ts.map +1 -1
- package/dist/stream/index.cjs +11 -15
- 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 +72 -26
- package/dist/stream/types.d.ts.map +1 -1
- package/dist/test-utils/llm-mock.cjs +4 -4
- package/dist/test-utils/llm-mock.js +1 -1
- package/dist/tool-loop-agent/index.cjs +4 -4
- package/dist/tool-loop-agent/index.d.ts +1 -1
- package/dist/tool-loop-agent/index.d.ts.map +1 -1
- package/dist/tool-loop-agent/index.js +1 -1
- package/dist/tool-loop-agent/tool-loop-processor.d.ts +1 -2
- package/dist/tool-loop-agent/tool-loop-processor.d.ts.map +1 -1
- package/dist/tools/index.cjs +4 -4
- package/dist/tools/index.js +1 -1
- package/dist/tools/is-vercel-tool.cjs +2 -2
- package/dist/tools/is-vercel-tool.js +1 -1
- package/dist/tools/tool-builder/builder.d.ts.map +1 -1
- package/dist/tools/tool.d.ts +27 -14
- package/dist/tools/tool.d.ts.map +1 -1
- package/dist/tools/types.d.ts +76 -20
- package/dist/tools/types.d.ts.map +1 -1
- package/dist/tools/ui-types.d.ts +3 -4
- package/dist/tools/ui-types.d.ts.map +1 -1
- package/dist/tools/validation.d.ts +4 -4
- package/dist/tools/validation.d.ts.map +1 -1
- package/dist/types/dynamic-argument.d.ts +61 -1
- package/dist/types/dynamic-argument.d.ts.map +1 -1
- package/dist/types/zod-compat.d.ts +3 -11
- package/dist/types/zod-compat.d.ts.map +1 -1
- package/dist/utils.cjs +22 -22
- package/dist/utils.d.ts +1 -1
- package/dist/utils.d.ts.map +1 -1
- package/dist/utils.js +1 -1
- package/dist/vector/index.cjs +2 -2
- package/dist/vector/index.js +1 -1
- package/dist/voice/index.cjs +6 -6
- package/dist/voice/index.js +1 -1
- package/dist/workflows/default.d.ts +114 -2
- package/dist/workflows/default.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.map +1 -1
- package/dist/workflows/evented/workflow-event-processor/utils.d.ts +1 -1
- package/dist/workflows/evented/workflow.d.ts +74 -21
- package/dist/workflows/evented/workflow.d.ts.map +1 -1
- package/dist/workflows/handlers/control-flow.d.ts +2 -2
- package/dist/workflows/handlers/control-flow.d.ts.map +1 -1
- package/dist/workflows/handlers/sleep.d.ts.map +1 -1
- package/dist/workflows/handlers/step.d.ts +1 -1
- package/dist/workflows/handlers/step.d.ts.map +1 -1
- package/dist/workflows/index.cjs +23 -23
- package/dist/workflows/index.js +1 -1
- package/dist/workflows/step.d.ts +28 -24
- package/dist/workflows/step.d.ts.map +1 -1
- package/dist/workflows/types.d.ts +91 -54
- package/dist/workflows/types.d.ts.map +1 -1
- package/dist/workflows/workflow.d.ts +165 -118
- package/dist/workflows/workflow.d.ts.map +1 -1
- package/package.json +4 -4
- package/src/llm/model/provider-types.generated.d.ts +224 -18
- package/dist/chunk-3CZ42NBZ.js.map +0 -1
- package/dist/chunk-3RFSIHFR.js.map +0 -1
- package/dist/chunk-6TBWJV35.js.map +0 -1
- package/dist/chunk-A4MCHA5L.cjs.map +0 -1
- package/dist/chunk-AHN7K3VE.js.map +0 -1
- package/dist/chunk-AW7FISLD.cjs.map +0 -1
- package/dist/chunk-CISH55FP.js.map +0 -1
- package/dist/chunk-IC2MIQBW.js.map +0 -1
- package/dist/chunk-JMAPJWVG.cjs.map +0 -1
- package/dist/chunk-KGE3KAM7.js.map +0 -1
- package/dist/chunk-O4H44CMA.js.map +0 -1
- package/dist/chunk-O5IPTMEH.cjs.map +0 -1
- package/dist/chunk-PC3FBUWH.js.map +0 -1
- package/dist/chunk-SOSXN7X4.cjs.map +0 -1
- package/dist/chunk-UOZ3GJY2.cjs.map +0 -1
- package/dist/chunk-UVHSM2GU.cjs.map +0 -1
- package/dist/chunk-UXLQEGIN.cjs.map +0 -1
- package/dist/chunk-W7R7GPNN.cjs.map +0 -1
- package/dist/chunk-WMJEP45F.cjs.map +0 -1
- package/dist/chunk-XBZWAUZ3.js.map +0 -1
- package/dist/chunk-XKDVT3ZH.cjs.map +0 -1
- package/dist/chunk-XSJNTLM7.js.map +0 -1
- package/dist/provider-registry-6DWM3X3I.js +0 -3
- package/dist/provider-registry-DCECMUCQ.cjs +0 -40
- package/dist/stream/aisdk/v5/output.d.ts +0 -121
- package/dist/stream/aisdk/v5/output.d.ts.map +0 -1
- /package/dist/docs/agents/{09-adding-voice.md → 10-adding-voice.md} +0 -0
- /package/dist/docs/observability/{09-langfuse.md → 11-langfuse.md} +0 -0
- /package/dist/docs/observability/{10-langsmith.md → 12-langsmith.md} +0 -0
- /package/dist/docs/observability/{12-posthog.md → 14-posthog.md} +0 -0
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
import { DefaultVoice } from './chunk-
|
|
1
|
+
import { DefaultVoice } from './chunk-TX5GUG5Q.js';
|
|
2
2
|
import { PUBSUB_SYMBOL, STREAM_FORMAT_SYMBOL } from './chunk-YEQB4VUA.js';
|
|
3
|
-
import { InMemoryStore } from './chunk-
|
|
4
|
-
import { MessageList, coreContentToString, DefaultGeneratedFile, DefaultGeneratedFileWithType } from './chunk-
|
|
5
|
-
import {
|
|
6
|
-
import { generateId, asSchema, jsonSchema, APICallError, tool } from './chunk-
|
|
7
|
-
import { resolveModelConfig, ModelRouterEmbeddingModel, ModelRouterLanguageModel } from './chunk-
|
|
8
|
-
import { MastraLLMV1 } from './chunk-
|
|
3
|
+
import { InMemoryStore } from './chunk-3XY64RAM.js';
|
|
4
|
+
import { MessageList, coreContentToString, DefaultGeneratedFile, DefaultGeneratedFileWithType } from './chunk-PSIJ6OSV.js';
|
|
5
|
+
import { parsePartialJson, isDeepEqualData, stepCountIs } from './chunk-K2LPTKSY.js';
|
|
6
|
+
import { generateId, asSchema, jsonSchema, APICallError, tool } from './chunk-CPLRD2VP.js';
|
|
7
|
+
import { resolveModelConfig, ModelRouterEmbeddingModel, ModelRouterLanguageModel } from './chunk-YYNZEEOO.js';
|
|
8
|
+
import { MastraLLMV1 } from './chunk-UL7TJCKA.js';
|
|
9
9
|
import { PubSub } from './chunk-BVUMKER5.js';
|
|
10
10
|
import { executeHook } from './chunk-L54GIUCB.js';
|
|
11
|
-
import { removeUndefinedValues, ensureToolProperties, makeCoreTool, createMastraProxy,
|
|
12
|
-
import { getOrCreateSpan, wrapMastra, executeWithContextSync } from './chunk-
|
|
11
|
+
import { isZodType, removeUndefinedValues, ensureToolProperties, makeCoreTool, createMastraProxy, deepMerge, selectFields, delay } from './chunk-5UVSKF5L.js';
|
|
12
|
+
import { getOrCreateSpan, wrapMastra, executeWithContextSync } from './chunk-C4CIC3LZ.js';
|
|
13
13
|
import { MastraError, getErrorFromUnknown } from './chunk-FJEVLHJT.js';
|
|
14
14
|
import { ToolStream } from './chunk-DD2VNRQM.js';
|
|
15
|
-
import { Tool, createTool } from './chunk-
|
|
16
|
-
import { RequestContext, MASTRA_RESOURCE_ID_KEY, MASTRA_THREAD_ID_KEY } from './chunk-
|
|
17
|
-
import { zodToJsonSchema
|
|
15
|
+
import { Tool, createTool } from './chunk-N3PAHTKU.js';
|
|
16
|
+
import { RequestContext, MASTRA_RESOURCE_ID_KEY, MASTRA_THREAD_ID_KEY } from './chunk-Y22QMA7S.js';
|
|
17
|
+
import { zodToJsonSchema } from './chunk-PJKCPRYF.js';
|
|
18
18
|
import { MastraBase } from './chunk-LSHPJWM5.js';
|
|
19
19
|
import { RegisteredLogger, ConsoleLogger } from './chunk-NRUZYMHE.js';
|
|
20
20
|
import { __commonJS, __toESM } from './chunk-7D4SUZUM.js';
|
|
@@ -23,9 +23,9 @@ import * as crypto2 from 'crypto';
|
|
|
23
23
|
import { randomUUID } from 'crypto';
|
|
24
24
|
import { ReadableStream as ReadableStream$1, TransformStream, WritableStream as WritableStream$1 } from 'stream/web';
|
|
25
25
|
import EventEmitter2, { EventEmitter } from 'events';
|
|
26
|
-
import {
|
|
26
|
+
import { TypeValidationError } from '@ai-sdk/provider-v5';
|
|
27
27
|
import { OpenAIReasoningSchemaCompatLayer, OpenAISchemaCompatLayer, isZodType as isZodType$1, GoogleSchemaCompatLayer, AnthropicSchemaCompatLayer, DeepSeekSchemaCompatLayer, MetaSchemaCompatLayer, applyCompatLayer } from '@mastra/schema-compat';
|
|
28
|
-
import { zodToJsonSchema } from '@mastra/schema-compat/zod-to-json';
|
|
28
|
+
import { zodToJsonSchema as zodToJsonSchema$1 } from '@mastra/schema-compat/zod-to-json';
|
|
29
29
|
import z4 from 'zod/v4';
|
|
30
30
|
import { isEmpty } from 'radash';
|
|
31
31
|
import { isAbortError, injectJsonInstructionIntoMessages } from '@ai-sdk/provider-utils-v5';
|
|
@@ -176,6 +176,7 @@ var MastraAgentNetworkStream = class extends ReadableStream$1 {
|
|
|
176
176
|
#objectStreamController = null;
|
|
177
177
|
#objectStream = null;
|
|
178
178
|
#run;
|
|
179
|
+
runId;
|
|
179
180
|
constructor({
|
|
180
181
|
createStream,
|
|
181
182
|
run
|
|
@@ -289,6 +290,7 @@ var MastraAgentNetworkStream = class extends ReadableStream$1 {
|
|
|
289
290
|
});
|
|
290
291
|
this.#run = run;
|
|
291
292
|
this.#streamPromise = deferredPromise;
|
|
293
|
+
this.runId = run.runId;
|
|
292
294
|
this.#objectPromise = objectDeferredPromise;
|
|
293
295
|
this.#objectStream = new ReadableStream$1({
|
|
294
296
|
start: (ctrl) => {
|
|
@@ -324,16 +326,6 @@ var MastraAgentNetworkStream = class extends ReadableStream$1 {
|
|
|
324
326
|
};
|
|
325
327
|
|
|
326
328
|
// src/stream/aisdk/v5/compat/ui-message.ts
|
|
327
|
-
function getResponseUIMessageId({
|
|
328
|
-
originalMessages,
|
|
329
|
-
responseMessageId
|
|
330
|
-
}) {
|
|
331
|
-
if (originalMessages == null) {
|
|
332
|
-
return void 0;
|
|
333
|
-
}
|
|
334
|
-
const lastMessage = originalMessages[originalMessages.length - 1];
|
|
335
|
-
return lastMessage?.role === "assistant" ? lastMessage.id : typeof responseMessageId === "function" ? responseMessageId() : responseMessageId;
|
|
336
|
-
}
|
|
337
329
|
function convertFullStreamChunkToUIMessageStream({
|
|
338
330
|
part,
|
|
339
331
|
messageMetadataValue,
|
|
@@ -592,7 +584,8 @@ var DelayedPromise = class {
|
|
|
592
584
|
function isProviderTool(tool2) {
|
|
593
585
|
if (typeof tool2 !== "object" || tool2 === null) return false;
|
|
594
586
|
const t = tool2;
|
|
595
|
-
|
|
587
|
+
const isProviderType = t.type === "provider-defined" || t.type === "provider";
|
|
588
|
+
return isProviderType && typeof t.id === "string";
|
|
596
589
|
}
|
|
597
590
|
function getProviderToolName(providerId) {
|
|
598
591
|
return providerId.split(".").slice(1).join(".");
|
|
@@ -1824,7 +1817,7 @@ function asJsonSchema(schema) {
|
|
|
1824
1817
|
return schema;
|
|
1825
1818
|
}
|
|
1826
1819
|
if (isZodType$1(schema)) {
|
|
1827
|
-
return zodToJsonSchema(schema);
|
|
1820
|
+
return zodToJsonSchema$1(schema);
|
|
1828
1821
|
}
|
|
1829
1822
|
if (schema.jsonSchema) {
|
|
1830
1823
|
return schema.jsonSchema;
|
|
@@ -2161,7 +2154,7 @@ var EnumFormatHandler = class extends BaseFormatHandler {
|
|
|
2161
2154
|
}
|
|
2162
2155
|
let enumValues;
|
|
2163
2156
|
if (this.isZodSchema(this.schema)) {
|
|
2164
|
-
const convertedSchema = zodToJsonSchema(this.schema);
|
|
2157
|
+
const convertedSchema = zodToJsonSchema$1(this.schema);
|
|
2165
2158
|
enumValues = convertedSchema?.enum;
|
|
2166
2159
|
} else if (typeof this.schema === "object" && !this.schema.jsonSchema) {
|
|
2167
2160
|
const wrappedSchema = jsonSchema(this.schema);
|
|
@@ -2330,7 +2323,7 @@ function createJsonTextStreamTransformer(schema) {
|
|
|
2330
2323
|
if (chunk.type !== "object" || !chunk.object) {
|
|
2331
2324
|
return;
|
|
2332
2325
|
}
|
|
2333
|
-
if (outputSchema?.outputFormat === "array") {
|
|
2326
|
+
if (outputSchema?.outputFormat === "array" && Array.isArray(chunk.object)) {
|
|
2334
2327
|
chunkCount++;
|
|
2335
2328
|
if (chunkCount === 1) {
|
|
2336
2329
|
if (chunk.object.length > 0) {
|
|
@@ -2877,6 +2870,7 @@ var MastraModelOutput = class extends MastraBase {
|
|
|
2877
2870
|
uiMessages: messageList.get.response.aiV5.ui()
|
|
2878
2871
|
};
|
|
2879
2872
|
}
|
|
2873
|
+
chunk.payload.response = response;
|
|
2880
2874
|
} else if (!self.#options.isLLMExecutionStep) {
|
|
2881
2875
|
this.resolvePromises({
|
|
2882
2876
|
text: self.#bufferedText.join(""),
|
|
@@ -3222,7 +3216,6 @@ var MastraModelOutput = class extends MastraBase {
|
|
|
3222
3216
|
const steps = await this.steps;
|
|
3223
3217
|
const textFromSteps = steps.map((step) => step.text || "").join("");
|
|
3224
3218
|
const fullOutput = {
|
|
3225
|
-
// Use text calculated from steps to properly exclude rejected responses
|
|
3226
3219
|
text: textFromSteps,
|
|
3227
3220
|
usage: await this.usage,
|
|
3228
3221
|
steps,
|
|
@@ -3244,7 +3237,11 @@ var MastraModelOutput = class extends MastraBase {
|
|
|
3244
3237
|
...scoringData ? { scoringData } : {},
|
|
3245
3238
|
traceId: this.traceId,
|
|
3246
3239
|
runId: this.runId,
|
|
3247
|
-
suspendPayload: await this.suspendPayload
|
|
3240
|
+
suspendPayload: await this.suspendPayload,
|
|
3241
|
+
// All messages from this execution (input + memory history + response)
|
|
3242
|
+
messages: this.messageList.get.all.db(),
|
|
3243
|
+
// Only messages loaded from memory (conversation history)
|
|
3244
|
+
rememberedMessages: this.messageList.get.remembered.db()
|
|
3248
3245
|
};
|
|
3249
3246
|
return fullOutput;
|
|
3250
3247
|
}
|
|
@@ -4342,294 +4339,6 @@ function normalizeFinishReason(finishReason) {
|
|
|
4342
4339
|
return finishReason === "unknown" ? "other" : finishReason;
|
|
4343
4340
|
}
|
|
4344
4341
|
|
|
4345
|
-
// src/stream/aisdk/v5/output.ts
|
|
4346
|
-
var AISDKV5OutputStream = class {
|
|
4347
|
-
#modelOutput;
|
|
4348
|
-
#options;
|
|
4349
|
-
#messageList;
|
|
4350
|
-
/**
|
|
4351
|
-
* Trace ID used on the execution (if the execution was traced).
|
|
4352
|
-
*/
|
|
4353
|
-
traceId;
|
|
4354
|
-
constructor({
|
|
4355
|
-
modelOutput,
|
|
4356
|
-
options,
|
|
4357
|
-
messageList
|
|
4358
|
-
}) {
|
|
4359
|
-
this.#modelOutput = modelOutput;
|
|
4360
|
-
this.#options = options;
|
|
4361
|
-
this.#messageList = messageList;
|
|
4362
|
-
this.traceId = options.tracingContext?.currentSpan?.externalTraceId;
|
|
4363
|
-
}
|
|
4364
|
-
toTextStreamResponse(init) {
|
|
4365
|
-
return createTextStreamResponse({
|
|
4366
|
-
// Type assertion needed due to ReadableStream type mismatch between Node.js (stream/web) and DOM types
|
|
4367
|
-
// Both have the same interface but TypeScript treats them as incompatible
|
|
4368
|
-
textStream: this.#modelOutput.textStream,
|
|
4369
|
-
...init
|
|
4370
|
-
});
|
|
4371
|
-
}
|
|
4372
|
-
toUIMessageStreamResponse({
|
|
4373
|
-
generateMessageId,
|
|
4374
|
-
originalMessages,
|
|
4375
|
-
sendFinish,
|
|
4376
|
-
sendReasoning,
|
|
4377
|
-
sendSources,
|
|
4378
|
-
onError,
|
|
4379
|
-
sendStart,
|
|
4380
|
-
messageMetadata,
|
|
4381
|
-
onFinish,
|
|
4382
|
-
...init
|
|
4383
|
-
} = {}) {
|
|
4384
|
-
return createUIMessageStreamResponse({
|
|
4385
|
-
stream: this.toUIMessageStream({
|
|
4386
|
-
generateMessageId,
|
|
4387
|
-
originalMessages,
|
|
4388
|
-
sendFinish,
|
|
4389
|
-
sendReasoning,
|
|
4390
|
-
sendSources,
|
|
4391
|
-
onError,
|
|
4392
|
-
sendStart,
|
|
4393
|
-
messageMetadata,
|
|
4394
|
-
onFinish
|
|
4395
|
-
}),
|
|
4396
|
-
...init
|
|
4397
|
-
});
|
|
4398
|
-
}
|
|
4399
|
-
toUIMessageStream({
|
|
4400
|
-
generateMessageId,
|
|
4401
|
-
originalMessages,
|
|
4402
|
-
sendFinish = true,
|
|
4403
|
-
sendReasoning = true,
|
|
4404
|
-
sendSources = false,
|
|
4405
|
-
onError = getErrorMessage,
|
|
4406
|
-
sendStart = true,
|
|
4407
|
-
messageMetadata,
|
|
4408
|
-
onFinish
|
|
4409
|
-
} = {}) {
|
|
4410
|
-
let responseMessageId = generateMessageId != null ? getResponseUIMessageId({
|
|
4411
|
-
originalMessages,
|
|
4412
|
-
responseMessageId: generateMessageId
|
|
4413
|
-
}) : void 0;
|
|
4414
|
-
return createUIMessageStream({
|
|
4415
|
-
onError,
|
|
4416
|
-
onFinish,
|
|
4417
|
-
generateId: () => responseMessageId ?? generateMessageId?.() ?? generateId(),
|
|
4418
|
-
execute: async ({ writer }) => {
|
|
4419
|
-
for await (const part of this.fullStream) {
|
|
4420
|
-
const messageMetadataValue = messageMetadata?.({ part });
|
|
4421
|
-
const partType = part.type;
|
|
4422
|
-
responseMessageId = this.#modelOutput.messageId;
|
|
4423
|
-
const transformedChunk = convertFullStreamChunkToUIMessageStream({
|
|
4424
|
-
part,
|
|
4425
|
-
sendReasoning,
|
|
4426
|
-
messageMetadataValue,
|
|
4427
|
-
sendSources,
|
|
4428
|
-
sendStart,
|
|
4429
|
-
sendFinish,
|
|
4430
|
-
responseMessageId,
|
|
4431
|
-
onError
|
|
4432
|
-
});
|
|
4433
|
-
if (transformedChunk) {
|
|
4434
|
-
writer.write(transformedChunk);
|
|
4435
|
-
}
|
|
4436
|
-
if (messageMetadataValue != null && partType !== "start" && partType !== "finish") {
|
|
4437
|
-
writer.write({
|
|
4438
|
-
type: "message-metadata",
|
|
4439
|
-
messageMetadata: messageMetadataValue
|
|
4440
|
-
});
|
|
4441
|
-
}
|
|
4442
|
-
}
|
|
4443
|
-
}
|
|
4444
|
-
});
|
|
4445
|
-
}
|
|
4446
|
-
async consumeStream(options) {
|
|
4447
|
-
await this.#modelOutput.consumeStream(options);
|
|
4448
|
-
}
|
|
4449
|
-
get sources() {
|
|
4450
|
-
return this.#modelOutput.sources.then(
|
|
4451
|
-
(sources) => sources.map((source) => {
|
|
4452
|
-
return convertMastraChunkToAISDKv5({
|
|
4453
|
-
chunk: source
|
|
4454
|
-
});
|
|
4455
|
-
})
|
|
4456
|
-
);
|
|
4457
|
-
}
|
|
4458
|
-
get files() {
|
|
4459
|
-
return this.#modelOutput.files.then(
|
|
4460
|
-
(files) => files.map((file) => {
|
|
4461
|
-
if (file.type === "file") {
|
|
4462
|
-
const result = convertMastraChunkToAISDKv5({
|
|
4463
|
-
chunk: file
|
|
4464
|
-
});
|
|
4465
|
-
return result && "file" in result ? result.file : void 0;
|
|
4466
|
-
}
|
|
4467
|
-
return;
|
|
4468
|
-
}).filter(Boolean)
|
|
4469
|
-
);
|
|
4470
|
-
}
|
|
4471
|
-
get text() {
|
|
4472
|
-
return this.#modelOutput.text;
|
|
4473
|
-
}
|
|
4474
|
-
/**
|
|
4475
|
-
* Stream of valid JSON chunks. The final JSON result is validated against the output schema when the stream ends.
|
|
4476
|
-
*/
|
|
4477
|
-
get objectStream() {
|
|
4478
|
-
return this.#modelOutput.objectStream;
|
|
4479
|
-
}
|
|
4480
|
-
get toolCalls() {
|
|
4481
|
-
return this.#modelOutput.toolCalls.then(
|
|
4482
|
-
(toolCalls) => toolCalls.map((toolCall) => {
|
|
4483
|
-
return convertMastraChunkToAISDKv5({
|
|
4484
|
-
chunk: toolCall
|
|
4485
|
-
});
|
|
4486
|
-
})
|
|
4487
|
-
);
|
|
4488
|
-
}
|
|
4489
|
-
get toolResults() {
|
|
4490
|
-
return this.#modelOutput.toolResults.then(
|
|
4491
|
-
(toolResults) => toolResults.map((toolResult) => {
|
|
4492
|
-
return convertMastraChunkToAISDKv5({
|
|
4493
|
-
chunk: toolResult
|
|
4494
|
-
});
|
|
4495
|
-
})
|
|
4496
|
-
);
|
|
4497
|
-
}
|
|
4498
|
-
get reasoningText() {
|
|
4499
|
-
return this.#modelOutput.reasoningText;
|
|
4500
|
-
}
|
|
4501
|
-
get reasoning() {
|
|
4502
|
-
return this.#modelOutput.reasoning.then((reasoningChunk) => {
|
|
4503
|
-
return reasoningChunk.map((reasoningPart) => {
|
|
4504
|
-
return {
|
|
4505
|
-
providerMetadata: reasoningPart.payload.providerMetadata,
|
|
4506
|
-
text: reasoningPart.payload.text,
|
|
4507
|
-
type: "reasoning"
|
|
4508
|
-
};
|
|
4509
|
-
});
|
|
4510
|
-
});
|
|
4511
|
-
}
|
|
4512
|
-
get warnings() {
|
|
4513
|
-
return this.#modelOutput.warnings;
|
|
4514
|
-
}
|
|
4515
|
-
get usage() {
|
|
4516
|
-
return this.#modelOutput.usage;
|
|
4517
|
-
}
|
|
4518
|
-
get finishReason() {
|
|
4519
|
-
return this.#modelOutput.finishReason;
|
|
4520
|
-
}
|
|
4521
|
-
get providerMetadata() {
|
|
4522
|
-
return this.#modelOutput.providerMetadata;
|
|
4523
|
-
}
|
|
4524
|
-
get request() {
|
|
4525
|
-
return this.#modelOutput.request;
|
|
4526
|
-
}
|
|
4527
|
-
get totalUsage() {
|
|
4528
|
-
return this.#modelOutput.totalUsage;
|
|
4529
|
-
}
|
|
4530
|
-
get response() {
|
|
4531
|
-
return this.#modelOutput.response.then((response) => ({
|
|
4532
|
-
...response
|
|
4533
|
-
}));
|
|
4534
|
-
}
|
|
4535
|
-
get steps() {
|
|
4536
|
-
return this.#modelOutput.steps.then((steps) => steps);
|
|
4537
|
-
}
|
|
4538
|
-
get content() {
|
|
4539
|
-
return this.#messageList.get.response.aiV5.modelContent();
|
|
4540
|
-
}
|
|
4541
|
-
/**
|
|
4542
|
-
* Stream of only text content, compatible with streaming text responses.
|
|
4543
|
-
*/
|
|
4544
|
-
get textStream() {
|
|
4545
|
-
return this.#modelOutput.textStream;
|
|
4546
|
-
}
|
|
4547
|
-
/**
|
|
4548
|
-
* Stream of individual array elements when output schema is an array type.
|
|
4549
|
-
*/
|
|
4550
|
-
get elementStream() {
|
|
4551
|
-
return this.#modelOutput.elementStream;
|
|
4552
|
-
}
|
|
4553
|
-
/**
|
|
4554
|
-
* Stream of all chunks in AI SDK v5 format.
|
|
4555
|
-
*/
|
|
4556
|
-
get fullStream() {
|
|
4557
|
-
let startEvent;
|
|
4558
|
-
let hasStarted = false;
|
|
4559
|
-
return this.#modelOutput.fullStream.pipeThrough(
|
|
4560
|
-
new TransformStream({
|
|
4561
|
-
transform(chunk, controller) {
|
|
4562
|
-
if (chunk.type === "object") {
|
|
4563
|
-
controller.enqueue(chunk);
|
|
4564
|
-
return;
|
|
4565
|
-
}
|
|
4566
|
-
if (chunk.type === "step-start" && !startEvent) {
|
|
4567
|
-
startEvent = convertMastraChunkToAISDKv5({
|
|
4568
|
-
chunk
|
|
4569
|
-
});
|
|
4570
|
-
return;
|
|
4571
|
-
} else if (chunk.type !== "error") {
|
|
4572
|
-
hasStarted = true;
|
|
4573
|
-
}
|
|
4574
|
-
if (startEvent && hasStarted) {
|
|
4575
|
-
controller.enqueue(startEvent);
|
|
4576
|
-
startEvent = void 0;
|
|
4577
|
-
}
|
|
4578
|
-
if ("payload" in chunk) {
|
|
4579
|
-
const transformedChunk = convertMastraChunkToAISDKv5({
|
|
4580
|
-
chunk
|
|
4581
|
-
});
|
|
4582
|
-
if (transformedChunk) {
|
|
4583
|
-
controller.enqueue(transformedChunk);
|
|
4584
|
-
}
|
|
4585
|
-
}
|
|
4586
|
-
}
|
|
4587
|
-
})
|
|
4588
|
-
);
|
|
4589
|
-
}
|
|
4590
|
-
async getFullOutput() {
|
|
4591
|
-
await this.consumeStream({
|
|
4592
|
-
onError: (error) => {
|
|
4593
|
-
throw error;
|
|
4594
|
-
}
|
|
4595
|
-
});
|
|
4596
|
-
const object = await this.object;
|
|
4597
|
-
const fullOutput = {
|
|
4598
|
-
text: await this.#modelOutput.text,
|
|
4599
|
-
usage: await this.#modelOutput.usage,
|
|
4600
|
-
steps: await this.steps,
|
|
4601
|
-
finishReason: await this.#modelOutput.finishReason,
|
|
4602
|
-
warnings: await this.#modelOutput.warnings,
|
|
4603
|
-
providerMetadata: await this.#modelOutput.providerMetadata,
|
|
4604
|
-
request: await this.#modelOutput.request,
|
|
4605
|
-
reasoning: await this.reasoning,
|
|
4606
|
-
reasoningText: await this.reasoningText,
|
|
4607
|
-
toolCalls: await this.toolCalls,
|
|
4608
|
-
toolResults: await this.toolResults,
|
|
4609
|
-
sources: await this.sources,
|
|
4610
|
-
files: await this.files,
|
|
4611
|
-
response: await this.response,
|
|
4612
|
-
content: this.content,
|
|
4613
|
-
totalUsage: await this.#modelOutput.totalUsage,
|
|
4614
|
-
error: this.error,
|
|
4615
|
-
tripwire: this.#modelOutput.tripwire,
|
|
4616
|
-
traceId: this.traceId,
|
|
4617
|
-
...object ? { object } : {}
|
|
4618
|
-
};
|
|
4619
|
-
fullOutput.response.messages = this.#modelOutput.messageList.get.response.aiV5.model();
|
|
4620
|
-
return fullOutput;
|
|
4621
|
-
}
|
|
4622
|
-
get tripwire() {
|
|
4623
|
-
return this.#modelOutput.tripwire;
|
|
4624
|
-
}
|
|
4625
|
-
get error() {
|
|
4626
|
-
return this.#modelOutput.error;
|
|
4627
|
-
}
|
|
4628
|
-
get object() {
|
|
4629
|
-
return this.#modelOutput.object;
|
|
4630
|
-
}
|
|
4631
|
-
};
|
|
4632
|
-
|
|
4633
4342
|
// src/agent/trip-wire.ts
|
|
4634
4343
|
var TripWire = class extends Error {
|
|
4635
4344
|
options;
|
|
@@ -5072,7 +4781,7 @@ async function validateStepInput({
|
|
|
5072
4781
|
}) {
|
|
5073
4782
|
let inputData = prevOutput;
|
|
5074
4783
|
let validationError;
|
|
5075
|
-
if (validateInputs) {
|
|
4784
|
+
if (validateInputs && isZodType(step.inputSchema)) {
|
|
5076
4785
|
const inputSchema = step.inputSchema;
|
|
5077
4786
|
const validatedInput = await inputSchema.safeParseAsync(prevOutput);
|
|
5078
4787
|
if (!validatedInput.success) {
|
|
@@ -5101,7 +4810,7 @@ async function validateStepResumeData({ resumeData, step }) {
|
|
|
5101
4810
|
}
|
|
5102
4811
|
let validationError;
|
|
5103
4812
|
const resumeSchema = step.resumeSchema;
|
|
5104
|
-
if (resumeSchema) {
|
|
4813
|
+
if (resumeSchema && isZodType(resumeSchema)) {
|
|
5105
4814
|
const validatedResumeData = await resumeSchema.safeParseAsync(resumeData);
|
|
5106
4815
|
if (!validatedResumeData.success) {
|
|
5107
4816
|
const errors = getZodErrors(validatedResumeData.error);
|
|
@@ -5132,7 +4841,7 @@ async function validateStepSuspendData({
|
|
|
5132
4841
|
}
|
|
5133
4842
|
let validationError;
|
|
5134
4843
|
const suspendSchema = step.suspendSchema;
|
|
5135
|
-
if (suspendSchema && validateInputs) {
|
|
4844
|
+
if (suspendSchema && validateInputs && isZodType(suspendSchema)) {
|
|
5136
4845
|
const validatedSuspendData = await suspendSchema.safeParseAsync(suspendData);
|
|
5137
4846
|
if (!validatedSuspendData.success) {
|
|
5138
4847
|
const errors = getZodErrors(validatedSuspendData.error);
|
|
@@ -5163,7 +4872,7 @@ async function validateStepStateData({
|
|
|
5163
4872
|
}
|
|
5164
4873
|
let validationError;
|
|
5165
4874
|
const stateSchema = step.stateSchema;
|
|
5166
|
-
if (stateSchema && validateInputs) {
|
|
4875
|
+
if (stateSchema && validateInputs && isZodType(stateSchema)) {
|
|
5167
4876
|
const validatedStateData = await stateSchema.safeParseAsync(stateData);
|
|
5168
4877
|
if (!validatedStateData.success) {
|
|
5169
4878
|
const errors = getZodErrors(validatedStateData.error);
|
|
@@ -5344,15 +5053,19 @@ async function executeParallel(engine, params) {
|
|
|
5344
5053
|
disableScorers,
|
|
5345
5054
|
perStep
|
|
5346
5055
|
} = params;
|
|
5347
|
-
const parallelSpan =
|
|
5348
|
-
|
|
5349
|
-
|
|
5350
|
-
|
|
5351
|
-
|
|
5352
|
-
|
|
5353
|
-
|
|
5056
|
+
const parallelSpan = await engine.createChildSpan({
|
|
5057
|
+
parentSpan: tracingContext.currentSpan,
|
|
5058
|
+
operationId: `workflow.${workflowId}.run.${runId}.parallel.${executionContext.executionPath.join("-")}.span.start`,
|
|
5059
|
+
options: {
|
|
5060
|
+
type: "workflow_parallel" /* WORKFLOW_PARALLEL */,
|
|
5061
|
+
name: `parallel: '${entry.steps.length} branches'`,
|
|
5062
|
+
input: engine.getStepOutput(stepResults, prevStep),
|
|
5063
|
+
attributes: {
|
|
5064
|
+
branchCount: entry.steps.length,
|
|
5065
|
+
parallelSteps: entry.steps.map((s) => s.type === "step" ? s.step.id : `control-${s.type}`)
|
|
5066
|
+
}
|
|
5354
5067
|
},
|
|
5355
|
-
|
|
5068
|
+
executionContext
|
|
5356
5069
|
});
|
|
5357
5070
|
const prevOutput = engine.getStepOutput(stepResults, prevStep);
|
|
5358
5071
|
for (const [stepIndex, step] of entry.steps.entries()) {
|
|
@@ -5412,7 +5125,8 @@ async function executeParallel(engine, params) {
|
|
|
5412
5125
|
suspendedPaths: executionContext.suspendedPaths,
|
|
5413
5126
|
resumeLabels: executionContext.resumeLabels,
|
|
5414
5127
|
retryConfig: executionContext.retryConfig,
|
|
5415
|
-
state: executionContext.state
|
|
5128
|
+
state: executionContext.state,
|
|
5129
|
+
tracingIds: executionContext.tracingIds
|
|
5416
5130
|
},
|
|
5417
5131
|
tracingContext: {
|
|
5418
5132
|
currentSpan: parallelSpan
|
|
@@ -5457,10 +5171,16 @@ async function executeParallel(engine, params) {
|
|
|
5457
5171
|
};
|
|
5458
5172
|
}
|
|
5459
5173
|
if (execResults.status === "failed") {
|
|
5460
|
-
|
|
5174
|
+
await engine.errorChildSpan({
|
|
5175
|
+
span: parallelSpan,
|
|
5176
|
+
operationId: `workflow.${workflowId}.run.${runId}.parallel.${executionContext.executionPath.join("-")}.span.error`,
|
|
5177
|
+
errorOptions: { error: execResults.error }
|
|
5178
|
+
});
|
|
5461
5179
|
} else {
|
|
5462
|
-
|
|
5463
|
-
|
|
5180
|
+
await engine.endChildSpan({
|
|
5181
|
+
span: parallelSpan,
|
|
5182
|
+
operationId: `workflow.${workflowId}.run.${runId}.parallel.${executionContext.executionPath.join("-")}.span.end`,
|
|
5183
|
+
endOptions: { output: execResults.output || execResults }
|
|
5464
5184
|
});
|
|
5465
5185
|
}
|
|
5466
5186
|
return execResults;
|
|
@@ -5486,26 +5206,34 @@ async function executeConditional(engine, params) {
|
|
|
5486
5206
|
disableScorers,
|
|
5487
5207
|
perStep
|
|
5488
5208
|
} = params;
|
|
5489
|
-
const conditionalSpan =
|
|
5490
|
-
|
|
5491
|
-
|
|
5492
|
-
|
|
5493
|
-
|
|
5494
|
-
|
|
5209
|
+
const conditionalSpan = await engine.createChildSpan({
|
|
5210
|
+
parentSpan: tracingContext.currentSpan,
|
|
5211
|
+
operationId: `workflow.${workflowId}.run.${runId}.conditional.${executionContext.executionPath.join("-")}.span.start`,
|
|
5212
|
+
options: {
|
|
5213
|
+
type: "workflow_conditional" /* WORKFLOW_CONDITIONAL */,
|
|
5214
|
+
name: `conditional: '${entry.conditions.length} conditions'`,
|
|
5215
|
+
input: prevOutput,
|
|
5216
|
+
attributes: {
|
|
5217
|
+
conditionCount: entry.conditions.length
|
|
5218
|
+
}
|
|
5495
5219
|
},
|
|
5496
|
-
|
|
5220
|
+
executionContext
|
|
5497
5221
|
});
|
|
5498
5222
|
let execResults;
|
|
5499
5223
|
const truthyIndexes = (await Promise.all(
|
|
5500
5224
|
entry.conditions.map(async (cond, index) => {
|
|
5501
|
-
const evalSpan =
|
|
5502
|
-
|
|
5503
|
-
|
|
5504
|
-
|
|
5505
|
-
|
|
5506
|
-
|
|
5225
|
+
const evalSpan = await engine.createChildSpan({
|
|
5226
|
+
parentSpan: conditionalSpan,
|
|
5227
|
+
operationId: `workflow.${workflowId}.run.${runId}.conditional.${executionContext.executionPath.join("-")}.eval.${index}.span.start`,
|
|
5228
|
+
options: {
|
|
5229
|
+
type: "workflow_conditional_eval" /* WORKFLOW_CONDITIONAL_EVAL */,
|
|
5230
|
+
name: `condition '${index}'`,
|
|
5231
|
+
input: prevOutput,
|
|
5232
|
+
attributes: {
|
|
5233
|
+
conditionIndex: index
|
|
5234
|
+
}
|
|
5507
5235
|
},
|
|
5508
|
-
|
|
5236
|
+
executionContext
|
|
5509
5237
|
});
|
|
5510
5238
|
const operationId = `workflow.${workflowId}.conditional.${index}`;
|
|
5511
5239
|
const context = createDeprecationProxy(
|
|
@@ -5522,8 +5250,8 @@ async function executeConditional(engine, params) {
|
|
|
5522
5250
|
},
|
|
5523
5251
|
getInitData: () => stepResults?.input,
|
|
5524
5252
|
getStepResult: getStepResult.bind(null, stepResults),
|
|
5525
|
-
bail: () => {
|
|
5526
|
-
},
|
|
5253
|
+
bail: (() => {
|
|
5254
|
+
}),
|
|
5527
5255
|
abort: () => {
|
|
5528
5256
|
abortController?.abort();
|
|
5529
5257
|
},
|
|
@@ -5549,10 +5277,14 @@ async function executeConditional(engine, params) {
|
|
|
5549
5277
|
);
|
|
5550
5278
|
try {
|
|
5551
5279
|
const result = await engine.evaluateCondition(cond, index, context, operationId);
|
|
5552
|
-
|
|
5553
|
-
|
|
5554
|
-
|
|
5555
|
-
|
|
5280
|
+
await engine.endChildSpan({
|
|
5281
|
+
span: evalSpan,
|
|
5282
|
+
operationId: `workflow.${workflowId}.run.${runId}.conditional.${executionContext.executionPath.join("-")}.eval.${index}.span.end`,
|
|
5283
|
+
endOptions: {
|
|
5284
|
+
output: result !== null,
|
|
5285
|
+
attributes: {
|
|
5286
|
+
result: result !== null
|
|
5287
|
+
}
|
|
5556
5288
|
}
|
|
5557
5289
|
});
|
|
5558
5290
|
return result;
|
|
@@ -5569,10 +5301,14 @@ async function executeConditional(engine, params) {
|
|
|
5569
5301
|
);
|
|
5570
5302
|
engine.getLogger()?.trackException(mastraError);
|
|
5571
5303
|
engine.getLogger()?.error("Error evaluating condition: " + errorInstance.stack);
|
|
5572
|
-
|
|
5573
|
-
|
|
5574
|
-
|
|
5575
|
-
|
|
5304
|
+
await engine.errorChildSpan({
|
|
5305
|
+
span: evalSpan,
|
|
5306
|
+
operationId: `workflow.${workflowId}.run.${runId}.conditional.${executionContext.executionPath.join("-")}.eval.${index}.span.error`,
|
|
5307
|
+
errorOptions: {
|
|
5308
|
+
error: mastraError,
|
|
5309
|
+
attributes: {
|
|
5310
|
+
result: false
|
|
5311
|
+
}
|
|
5576
5312
|
}
|
|
5577
5313
|
});
|
|
5578
5314
|
return null;
|
|
@@ -5628,7 +5364,8 @@ async function executeConditional(engine, params) {
|
|
|
5628
5364
|
suspendedPaths: executionContext.suspendedPaths,
|
|
5629
5365
|
resumeLabels: executionContext.resumeLabels,
|
|
5630
5366
|
retryConfig: executionContext.retryConfig,
|
|
5631
|
-
state: executionContext.state
|
|
5367
|
+
state: executionContext.state,
|
|
5368
|
+
tracingIds: executionContext.tracingIds
|
|
5632
5369
|
},
|
|
5633
5370
|
tracingContext: {
|
|
5634
5371
|
currentSpan: conditionalSpan
|
|
@@ -5674,10 +5411,16 @@ async function executeConditional(engine, params) {
|
|
|
5674
5411
|
};
|
|
5675
5412
|
}
|
|
5676
5413
|
if (execResults.status === "failed") {
|
|
5677
|
-
|
|
5414
|
+
await engine.errorChildSpan({
|
|
5415
|
+
span: conditionalSpan,
|
|
5416
|
+
operationId: `workflow.${workflowId}.run.${runId}.conditional.${executionContext.executionPath.join("-")}.span.error`,
|
|
5417
|
+
errorOptions: { error: execResults.error }
|
|
5418
|
+
});
|
|
5678
5419
|
} else {
|
|
5679
|
-
|
|
5680
|
-
|
|
5420
|
+
await engine.endChildSpan({
|
|
5421
|
+
span: conditionalSpan,
|
|
5422
|
+
operationId: `workflow.${workflowId}.run.${runId}.conditional.${executionContext.executionPath.join("-")}.span.end`,
|
|
5423
|
+
endOptions: { output: execResults.output || execResults }
|
|
5681
5424
|
});
|
|
5682
5425
|
}
|
|
5683
5426
|
return execResults;
|
|
@@ -5704,14 +5447,18 @@ async function executeLoop(engine, params) {
|
|
|
5704
5447
|
perStep
|
|
5705
5448
|
} = params;
|
|
5706
5449
|
const { step, condition } = entry;
|
|
5707
|
-
const loopSpan =
|
|
5708
|
-
|
|
5709
|
-
|
|
5710
|
-
|
|
5711
|
-
|
|
5712
|
-
|
|
5450
|
+
const loopSpan = await engine.createChildSpan({
|
|
5451
|
+
parentSpan: tracingContext.currentSpan,
|
|
5452
|
+
operationId: `workflow.${workflowId}.run.${runId}.loop.${executionContext.executionPath.join("-")}.span.start`,
|
|
5453
|
+
options: {
|
|
5454
|
+
type: "workflow_loop" /* WORKFLOW_LOOP */,
|
|
5455
|
+
name: `loop: '${entry.loopType}'`,
|
|
5456
|
+
input: prevOutput,
|
|
5457
|
+
attributes: {
|
|
5458
|
+
loopType: entry.loopType
|
|
5459
|
+
}
|
|
5713
5460
|
},
|
|
5714
|
-
|
|
5461
|
+
executionContext
|
|
5715
5462
|
});
|
|
5716
5463
|
let isTrue = true;
|
|
5717
5464
|
const prevIterationCount = stepResults[step.id]?.metadata?.iterationCount;
|
|
@@ -5754,21 +5501,29 @@ async function executeLoop(engine, params) {
|
|
|
5754
5501
|
currentResume = void 0;
|
|
5755
5502
|
}
|
|
5756
5503
|
if (result.status !== "success") {
|
|
5757
|
-
|
|
5758
|
-
|
|
5759
|
-
|
|
5504
|
+
await engine.endChildSpan({
|
|
5505
|
+
span: loopSpan,
|
|
5506
|
+
operationId: `workflow.${workflowId}.run.${runId}.loop.${executionContext.executionPath.join("-")}.span.end.early`,
|
|
5507
|
+
endOptions: {
|
|
5508
|
+
attributes: {
|
|
5509
|
+
totalIterations: iteration
|
|
5510
|
+
}
|
|
5760
5511
|
}
|
|
5761
5512
|
});
|
|
5762
5513
|
return result;
|
|
5763
5514
|
}
|
|
5764
|
-
const evalSpan =
|
|
5765
|
-
|
|
5766
|
-
|
|
5767
|
-
|
|
5768
|
-
|
|
5769
|
-
|
|
5515
|
+
const evalSpan = await engine.createChildSpan({
|
|
5516
|
+
parentSpan: loopSpan,
|
|
5517
|
+
operationId: `workflow.${workflowId}.run.${runId}.loop.${executionContext.executionPath.join("-")}.eval.${iteration}.span.start`,
|
|
5518
|
+
options: {
|
|
5519
|
+
type: "workflow_conditional_eval" /* WORKFLOW_CONDITIONAL_EVAL */,
|
|
5520
|
+
name: `condition: '${entry.loopType}'`,
|
|
5521
|
+
input: selectFields(result.output, ["stepResult", "output.text", "output.object", "messages"]),
|
|
5522
|
+
attributes: {
|
|
5523
|
+
conditionIndex: iteration
|
|
5524
|
+
}
|
|
5770
5525
|
},
|
|
5771
|
-
|
|
5526
|
+
executionContext
|
|
5772
5527
|
});
|
|
5773
5528
|
isTrue = await condition(
|
|
5774
5529
|
createDeprecationProxy(
|
|
@@ -5786,8 +5541,8 @@ async function executeLoop(engine, params) {
|
|
|
5786
5541
|
iterationCount: iteration + 1,
|
|
5787
5542
|
getInitData: () => stepResults?.input,
|
|
5788
5543
|
getStepResult: getStepResult.bind(null, stepResults),
|
|
5789
|
-
bail: () => {
|
|
5790
|
-
},
|
|
5544
|
+
bail: (() => {
|
|
5545
|
+
}),
|
|
5791
5546
|
abort: () => {
|
|
5792
5547
|
abortController?.abort();
|
|
5793
5548
|
},
|
|
@@ -5812,15 +5567,23 @@ async function executeLoop(engine, params) {
|
|
|
5812
5567
|
}
|
|
5813
5568
|
)
|
|
5814
5569
|
);
|
|
5815
|
-
|
|
5816
|
-
|
|
5570
|
+
await engine.endChildSpan({
|
|
5571
|
+
span: evalSpan,
|
|
5572
|
+
operationId: `workflow.${workflowId}.run.${runId}.loop.${executionContext.executionPath.join("-")}.eval.${iteration}.span.end`,
|
|
5573
|
+
endOptions: {
|
|
5574
|
+
output: isTrue
|
|
5575
|
+
}
|
|
5817
5576
|
});
|
|
5818
5577
|
iteration++;
|
|
5819
5578
|
} while (entry.loopType === "dowhile" ? isTrue : !isTrue);
|
|
5820
|
-
|
|
5821
|
-
|
|
5822
|
-
|
|
5823
|
-
|
|
5579
|
+
await engine.endChildSpan({
|
|
5580
|
+
span: loopSpan,
|
|
5581
|
+
operationId: `workflow.${workflowId}.run.${runId}.loop.${executionContext.executionPath.join("-")}.span.end`,
|
|
5582
|
+
endOptions: {
|
|
5583
|
+
output: result.output,
|
|
5584
|
+
attributes: {
|
|
5585
|
+
totalIterations: iteration
|
|
5586
|
+
}
|
|
5824
5587
|
}
|
|
5825
5588
|
});
|
|
5826
5589
|
return result;
|
|
@@ -5857,15 +5620,19 @@ async function executeForeach(engine, params) {
|
|
|
5857
5620
|
...startTime ? { startedAt: startTime } : {},
|
|
5858
5621
|
...resumeTime ? { resumedAt: resumeTime } : {}
|
|
5859
5622
|
};
|
|
5860
|
-
const loopSpan =
|
|
5861
|
-
|
|
5862
|
-
|
|
5863
|
-
|
|
5864
|
-
|
|
5865
|
-
|
|
5866
|
-
|
|
5623
|
+
const loopSpan = await engine.createChildSpan({
|
|
5624
|
+
parentSpan: tracingContext.currentSpan,
|
|
5625
|
+
operationId: `workflow.${workflowId}.run.${runId}.foreach.${executionContext.executionPath.join("-")}.span.start`,
|
|
5626
|
+
options: {
|
|
5627
|
+
type: "workflow_loop" /* WORKFLOW_LOOP */,
|
|
5628
|
+
name: `loop: 'foreach'`,
|
|
5629
|
+
input: prevOutput,
|
|
5630
|
+
attributes: {
|
|
5631
|
+
loopType: "foreach",
|
|
5632
|
+
concurrency
|
|
5633
|
+
}
|
|
5867
5634
|
},
|
|
5868
|
-
|
|
5635
|
+
executionContext
|
|
5869
5636
|
});
|
|
5870
5637
|
await pubsub.publish(`workflow.events.v2.${runId}`, {
|
|
5871
5638
|
type: "watch",
|
|
@@ -6028,8 +5795,12 @@ async function executeForeach(engine, params) {
|
|
|
6028
5795
|
}
|
|
6029
5796
|
}
|
|
6030
5797
|
});
|
|
6031
|
-
|
|
6032
|
-
|
|
5798
|
+
await engine.endChildSpan({
|
|
5799
|
+
span: loopSpan,
|
|
5800
|
+
operationId: `workflow.${workflowId}.run.${runId}.foreach.${executionContext.executionPath.join("-")}.span.end`,
|
|
5801
|
+
endOptions: {
|
|
5802
|
+
output: results
|
|
5803
|
+
}
|
|
6033
5804
|
});
|
|
6034
5805
|
return {
|
|
6035
5806
|
...stepInfo,
|
|
@@ -6539,14 +6310,18 @@ async function executeSleep(engine, params) {
|
|
|
6539
6310
|
tracingContext
|
|
6540
6311
|
} = params;
|
|
6541
6312
|
let { duration, fn } = entry;
|
|
6542
|
-
const sleepSpan =
|
|
6543
|
-
|
|
6544
|
-
|
|
6545
|
-
|
|
6546
|
-
|
|
6547
|
-
|
|
6313
|
+
const sleepSpan = await engine.createChildSpan({
|
|
6314
|
+
parentSpan: tracingContext.currentSpan,
|
|
6315
|
+
operationId: `workflow.${workflowId}.run.${runId}.sleep.${entry.id}.span.start`,
|
|
6316
|
+
options: {
|
|
6317
|
+
type: "workflow_sleep" /* WORKFLOW_SLEEP */,
|
|
6318
|
+
name: `sleep: ${duration ? `${duration}ms` : "dynamic"}`,
|
|
6319
|
+
attributes: {
|
|
6320
|
+
durationMs: duration,
|
|
6321
|
+
sleepType: fn ? "dynamic" : "fixed"
|
|
6322
|
+
}
|
|
6548
6323
|
},
|
|
6549
|
-
|
|
6324
|
+
executionContext
|
|
6550
6325
|
});
|
|
6551
6326
|
if (fn) {
|
|
6552
6327
|
const stepCallId = randomUUID();
|
|
@@ -6570,8 +6345,8 @@ async function executeSleep(engine, params) {
|
|
|
6570
6345
|
// TODO: this function shouldn't have suspend probably?
|
|
6571
6346
|
suspend: async (_suspendPayload) => {
|
|
6572
6347
|
},
|
|
6573
|
-
bail: () => {
|
|
6574
|
-
},
|
|
6348
|
+
bail: (() => {
|
|
6349
|
+
}),
|
|
6575
6350
|
abort: () => {
|
|
6576
6351
|
abortController?.abort();
|
|
6577
6352
|
},
|
|
@@ -6598,9 +6373,16 @@ async function executeSleep(engine, params) {
|
|
|
6598
6373
|
}
|
|
6599
6374
|
try {
|
|
6600
6375
|
await engine.executeSleepDuration(!duration || duration < 0 ? 0 : duration, entry.id, workflowId);
|
|
6601
|
-
|
|
6376
|
+
await engine.endChildSpan({
|
|
6377
|
+
span: sleepSpan,
|
|
6378
|
+
operationId: `workflow.${workflowId}.run.${runId}.sleep.${entry.id}.span.end`
|
|
6379
|
+
});
|
|
6602
6380
|
} catch (e) {
|
|
6603
|
-
|
|
6381
|
+
await engine.errorChildSpan({
|
|
6382
|
+
span: sleepSpan,
|
|
6383
|
+
operationId: `workflow.${workflowId}.run.${runId}.sleep.${entry.id}.span.error`,
|
|
6384
|
+
errorOptions: { error: e }
|
|
6385
|
+
});
|
|
6604
6386
|
throw e;
|
|
6605
6387
|
}
|
|
6606
6388
|
}
|
|
@@ -6619,15 +6401,19 @@ async function executeSleepUntil(engine, params) {
|
|
|
6619
6401
|
tracingContext
|
|
6620
6402
|
} = params;
|
|
6621
6403
|
let { date, fn } = entry;
|
|
6622
|
-
const sleepUntilSpan =
|
|
6623
|
-
|
|
6624
|
-
|
|
6625
|
-
|
|
6626
|
-
|
|
6627
|
-
|
|
6628
|
-
|
|
6404
|
+
const sleepUntilSpan = await engine.createChildSpan({
|
|
6405
|
+
parentSpan: tracingContext.currentSpan,
|
|
6406
|
+
operationId: `workflow.${workflowId}.run.${runId}.sleepUntil.${entry.id}.span.start`,
|
|
6407
|
+
options: {
|
|
6408
|
+
type: "workflow_sleep" /* WORKFLOW_SLEEP */,
|
|
6409
|
+
name: `sleepUntil: ${date ? date.toISOString() : "dynamic"}`,
|
|
6410
|
+
attributes: {
|
|
6411
|
+
untilDate: date,
|
|
6412
|
+
durationMs: date ? Math.max(0, date.getTime() - Date.now()) : void 0,
|
|
6413
|
+
sleepType: fn ? "dynamic" : "fixed"
|
|
6414
|
+
}
|
|
6629
6415
|
},
|
|
6630
|
-
|
|
6416
|
+
executionContext
|
|
6631
6417
|
});
|
|
6632
6418
|
if (fn) {
|
|
6633
6419
|
const stepCallId = randomUUID();
|
|
@@ -6651,8 +6437,8 @@ async function executeSleepUntil(engine, params) {
|
|
|
6651
6437
|
// TODO: this function shouldn't have suspend probably?
|
|
6652
6438
|
suspend: async (_suspendPayload) => {
|
|
6653
6439
|
},
|
|
6654
|
-
bail: () => {
|
|
6655
|
-
},
|
|
6440
|
+
bail: (() => {
|
|
6441
|
+
}),
|
|
6656
6442
|
abort: () => {
|
|
6657
6443
|
abortController?.abort();
|
|
6658
6444
|
},
|
|
@@ -6680,14 +6466,24 @@ async function executeSleepUntil(engine, params) {
|
|
|
6680
6466
|
});
|
|
6681
6467
|
}
|
|
6682
6468
|
if (!date) {
|
|
6683
|
-
|
|
6469
|
+
await engine.endChildSpan({
|
|
6470
|
+
span: sleepUntilSpan,
|
|
6471
|
+
operationId: `workflow.${workflowId}.run.${runId}.sleepUntil.${entry.id}.span.end.nodate`
|
|
6472
|
+
});
|
|
6684
6473
|
return;
|
|
6685
6474
|
}
|
|
6686
6475
|
try {
|
|
6687
6476
|
await engine.executeSleepUntilDate(date, entry.id, workflowId);
|
|
6688
|
-
|
|
6477
|
+
await engine.endChildSpan({
|
|
6478
|
+
span: sleepUntilSpan,
|
|
6479
|
+
operationId: `workflow.${workflowId}.run.${runId}.sleepUntil.${entry.id}.span.end`
|
|
6480
|
+
});
|
|
6689
6481
|
} catch (e) {
|
|
6690
|
-
|
|
6482
|
+
await engine.errorChildSpan({
|
|
6483
|
+
span: sleepUntilSpan,
|
|
6484
|
+
operationId: `workflow.${workflowId}.run.${runId}.sleepUntil.${entry.id}.span.error`,
|
|
6485
|
+
errorOptions: { error: e }
|
|
6486
|
+
});
|
|
6691
6487
|
throw e;
|
|
6692
6488
|
}
|
|
6693
6489
|
}
|
|
@@ -6751,13 +6547,19 @@ async function executeStep(engine, params) {
|
|
|
6751
6547
|
...iterationCount ? { metadata: { iterationCount } } : {}
|
|
6752
6548
|
};
|
|
6753
6549
|
executionContext.activeStepsPath[step.id] = executionContext.executionPath;
|
|
6754
|
-
const stepSpan =
|
|
6755
|
-
|
|
6756
|
-
|
|
6757
|
-
|
|
6758
|
-
|
|
6759
|
-
|
|
6760
|
-
|
|
6550
|
+
const stepSpan = await engine.createStepSpan({
|
|
6551
|
+
parentSpan: tracingContext.currentSpan,
|
|
6552
|
+
stepId: step.id,
|
|
6553
|
+
operationId: `workflow.${workflowId}.run.${runId}.step.${step.id}.span.start`,
|
|
6554
|
+
options: {
|
|
6555
|
+
name: `workflow step: '${step.id}'`,
|
|
6556
|
+
type: "workflow_step" /* WORKFLOW_STEP */,
|
|
6557
|
+
entityType: "workflow_step" /* WORKFLOW_STEP */,
|
|
6558
|
+
entityId: step.id,
|
|
6559
|
+
input: inputData,
|
|
6560
|
+
tracingPolicy: engine.options?.tracingPolicy
|
|
6561
|
+
},
|
|
6562
|
+
executionContext
|
|
6761
6563
|
});
|
|
6762
6564
|
const operationId = `workflow.${workflowId}.run.${runId}.step.${step.id}.running_ev`;
|
|
6763
6565
|
await engine.onStepExecutionStart({
|
|
@@ -6802,6 +6604,28 @@ async function executeStep(engine, params) {
|
|
|
6802
6604
|
perStep
|
|
6803
6605
|
});
|
|
6804
6606
|
if (workflowResult !== null) {
|
|
6607
|
+
if (stepSpan) {
|
|
6608
|
+
if (workflowResult.status === "failed") {
|
|
6609
|
+
await engine.errorStepSpan({
|
|
6610
|
+
span: stepSpan,
|
|
6611
|
+
operationId: `workflow.${workflowId}.run.${runId}.step.${step.id}.span.error`,
|
|
6612
|
+
errorOptions: {
|
|
6613
|
+
error: workflowResult.error instanceof Error ? workflowResult.error : new Error(String(workflowResult.error)),
|
|
6614
|
+
attributes: { status: "failed" }
|
|
6615
|
+
}
|
|
6616
|
+
});
|
|
6617
|
+
} else {
|
|
6618
|
+
const output = workflowResult.status === "success" ? workflowResult.output : workflowResult.suspendOutput;
|
|
6619
|
+
await engine.endStepSpan({
|
|
6620
|
+
span: stepSpan,
|
|
6621
|
+
operationId: `workflow.${workflowId}.run.${runId}.step.${step.id}.span.end`,
|
|
6622
|
+
endOptions: {
|
|
6623
|
+
output,
|
|
6624
|
+
attributes: { status: workflowResult.status }
|
|
6625
|
+
}
|
|
6626
|
+
});
|
|
6627
|
+
}
|
|
6628
|
+
}
|
|
6805
6629
|
const stepResult2 = { ...stepInfo, ...workflowResult };
|
|
6806
6630
|
return {
|
|
6807
6631
|
result: stepResult2,
|
|
@@ -6841,11 +6665,13 @@ async function executeStep(engine, params) {
|
|
|
6841
6665
|
stateUpdate: null,
|
|
6842
6666
|
requestContextUpdate: null
|
|
6843
6667
|
};
|
|
6668
|
+
const isNestedWorkflow = step.component === "WORKFLOW";
|
|
6669
|
+
const mastraForStep = engine.mastra ? isNestedWorkflow ? engine.mastra : wrapMastra(engine.mastra, { currentSpan: stepSpan }) : void 0;
|
|
6844
6670
|
const output = await runStep({
|
|
6845
6671
|
runId,
|
|
6846
6672
|
resourceId,
|
|
6847
6673
|
workflowId,
|
|
6848
|
-
mastra:
|
|
6674
|
+
mastra: mastraForStep,
|
|
6849
6675
|
requestContext,
|
|
6850
6676
|
inputData,
|
|
6851
6677
|
state: executionContext.state,
|
|
@@ -6998,10 +6824,14 @@ async function executeStep(engine, params) {
|
|
|
6998
6824
|
});
|
|
6999
6825
|
}
|
|
7000
6826
|
if (execResults.status != "failed") {
|
|
7001
|
-
|
|
7002
|
-
|
|
7003
|
-
|
|
7004
|
-
|
|
6827
|
+
await engine.endStepSpan({
|
|
6828
|
+
span: stepSpan,
|
|
6829
|
+
operationId: `workflow.${workflowId}.run.${runId}.step.${step.id}.span.end`,
|
|
6830
|
+
endOptions: {
|
|
6831
|
+
output: execResults.output,
|
|
6832
|
+
attributes: {
|
|
6833
|
+
status: execResults.status
|
|
6834
|
+
}
|
|
7005
6835
|
}
|
|
7006
6836
|
});
|
|
7007
6837
|
}
|
|
@@ -7224,35 +7054,108 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
|
|
|
7224
7054
|
async executeWorkflowStep(_params) {
|
|
7225
7055
|
return null;
|
|
7226
7056
|
}
|
|
7057
|
+
// =============================================================================
|
|
7058
|
+
// Span Lifecycle Hooks
|
|
7059
|
+
// These methods can be overridden by subclasses (e.g., Inngest) to make span
|
|
7060
|
+
// creation/end durable across workflow replays.
|
|
7061
|
+
// =============================================================================
|
|
7227
7062
|
/**
|
|
7228
|
-
*
|
|
7229
|
-
*
|
|
7230
|
-
* Inngest engine: overrides to throw RetryAfterError for external retry handling.
|
|
7063
|
+
* Create a child span for a workflow step.
|
|
7064
|
+
* Override to add durability (e.g., Inngest memoization).
|
|
7231
7065
|
*
|
|
7232
|
-
*
|
|
7233
|
-
*
|
|
7234
|
-
* @param params -
|
|
7235
|
-
* @returns
|
|
7066
|
+
* Default: creates span directly via parent span's createChildSpan.
|
|
7067
|
+
*
|
|
7068
|
+
* @param params - Parameters for span creation
|
|
7069
|
+
* @returns The created span, or undefined if no parent span or tracing disabled
|
|
7236
7070
|
*/
|
|
7237
|
-
async
|
|
7238
|
-
|
|
7239
|
-
|
|
7240
|
-
|
|
7241
|
-
|
|
7242
|
-
|
|
7243
|
-
|
|
7244
|
-
|
|
7245
|
-
|
|
7246
|
-
|
|
7247
|
-
|
|
7248
|
-
|
|
7249
|
-
|
|
7250
|
-
|
|
7251
|
-
|
|
7252
|
-
|
|
7253
|
-
|
|
7254
|
-
|
|
7255
|
-
|
|
7071
|
+
async createStepSpan(params) {
|
|
7072
|
+
return params.parentSpan?.createChildSpan(params.options);
|
|
7073
|
+
}
|
|
7074
|
+
/**
|
|
7075
|
+
* End a workflow step span.
|
|
7076
|
+
* Override to add durability (e.g., Inngest memoization).
|
|
7077
|
+
*
|
|
7078
|
+
* Default: calls span.end() directly.
|
|
7079
|
+
*
|
|
7080
|
+
* @param params - Parameters for ending the span
|
|
7081
|
+
*/
|
|
7082
|
+
async endStepSpan(params) {
|
|
7083
|
+
params.span?.end(params.endOptions);
|
|
7084
|
+
}
|
|
7085
|
+
/**
|
|
7086
|
+
* Record an error on a workflow step span.
|
|
7087
|
+
* Override to add durability (e.g., Inngest memoization).
|
|
7088
|
+
*
|
|
7089
|
+
* Default: calls span.error() directly.
|
|
7090
|
+
*
|
|
7091
|
+
* @param params - Parameters for recording the error
|
|
7092
|
+
*/
|
|
7093
|
+
async errorStepSpan(params) {
|
|
7094
|
+
params.span?.error(params.errorOptions);
|
|
7095
|
+
}
|
|
7096
|
+
/**
|
|
7097
|
+
* Create a generic child span (for control-flow operations like parallel, conditional, loop).
|
|
7098
|
+
* Override to add durability (e.g., Inngest memoization).
|
|
7099
|
+
*
|
|
7100
|
+
* Default: creates span directly via parent span's createChildSpan.
|
|
7101
|
+
*
|
|
7102
|
+
* @param params - Parameters for span creation
|
|
7103
|
+
* @returns The created span, or undefined if no parent span or tracing disabled
|
|
7104
|
+
*/
|
|
7105
|
+
async createChildSpan(params) {
|
|
7106
|
+
return params.parentSpan?.createChildSpan(params.options);
|
|
7107
|
+
}
|
|
7108
|
+
/**
|
|
7109
|
+
* End a generic child span (for control-flow operations).
|
|
7110
|
+
* Override to add durability (e.g., Inngest memoization).
|
|
7111
|
+
*
|
|
7112
|
+
* Default: calls span.end() directly.
|
|
7113
|
+
*
|
|
7114
|
+
* @param params - Parameters for ending the span
|
|
7115
|
+
*/
|
|
7116
|
+
async endChildSpan(params) {
|
|
7117
|
+
params.span?.end(params.endOptions);
|
|
7118
|
+
}
|
|
7119
|
+
/**
|
|
7120
|
+
* Record an error on a generic child span (for control-flow operations).
|
|
7121
|
+
* Override to add durability (e.g., Inngest memoization).
|
|
7122
|
+
*
|
|
7123
|
+
* Default: calls span.error() directly.
|
|
7124
|
+
*
|
|
7125
|
+
* @param params - Parameters for recording the error
|
|
7126
|
+
*/
|
|
7127
|
+
async errorChildSpan(params) {
|
|
7128
|
+
params.span?.error(params.errorOptions);
|
|
7129
|
+
}
|
|
7130
|
+
/**
|
|
7131
|
+
* Execute a step with retry logic.
|
|
7132
|
+
* Default engine: handles retries internally with a loop.
|
|
7133
|
+
* Inngest engine: overrides to throw RetryAfterError for external retry handling.
|
|
7134
|
+
*
|
|
7135
|
+
* @param stepId - Unique identifier for the step (used for durability)
|
|
7136
|
+
* @param runStep - The step execution function to run
|
|
7137
|
+
* @param params - Retry parameters and context
|
|
7138
|
+
* @returns Discriminated union: { ok: true, result: T } or { ok: false, error: ... }
|
|
7139
|
+
*/
|
|
7140
|
+
async executeStepWithRetry(stepId, runStep, params) {
|
|
7141
|
+
for (let i = 0; i < params.retries + 1; i++) {
|
|
7142
|
+
if (i > 0 && params.delay) {
|
|
7143
|
+
await new Promise((resolve) => setTimeout(resolve, params.delay));
|
|
7144
|
+
}
|
|
7145
|
+
try {
|
|
7146
|
+
const result = await this.wrapDurableOperation(stepId, runStep);
|
|
7147
|
+
return { ok: true, result };
|
|
7148
|
+
} catch (e) {
|
|
7149
|
+
if (i === params.retries) {
|
|
7150
|
+
const errorInstance = getErrorFromUnknown(e, {
|
|
7151
|
+
serializeStack: false,
|
|
7152
|
+
fallbackMessage: "Unknown step execution error"
|
|
7153
|
+
});
|
|
7154
|
+
const mastraError = new MastraError(
|
|
7155
|
+
{
|
|
7156
|
+
id: "WORKFLOW_STEP_INVOKE_FAILED",
|
|
7157
|
+
domain: "MASTRA_WORKFLOW" /* MASTRA_WORKFLOW */,
|
|
7158
|
+
category: "USER" /* USER */,
|
|
7256
7159
|
details: { workflowId: params.workflowId, runId: params.runId, stepId }
|
|
7257
7160
|
},
|
|
7258
7161
|
errorInstance
|
|
@@ -7446,7 +7349,9 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
|
|
|
7446
7349
|
resumeLabels: {},
|
|
7447
7350
|
retryConfig: { attempts, delay: delay2 },
|
|
7448
7351
|
format: params.format,
|
|
7449
|
-
state: lastState ?? initialState
|
|
7352
|
+
state: lastState ?? initialState,
|
|
7353
|
+
// Tracing IDs for durable span operations (Inngest)
|
|
7354
|
+
tracingIds: params.tracingIds
|
|
7450
7355
|
};
|
|
7451
7356
|
lastExecutionContext = executionContext;
|
|
7452
7357
|
lastOutput = await this.executeEntry({
|
|
@@ -7653,648 +7558,655 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
|
|
|
7653
7558
|
function mapVariable(config) {
|
|
7654
7559
|
return config;
|
|
7655
7560
|
}
|
|
7561
|
+
function isAgent(input) {
|
|
7562
|
+
return input instanceof Agent;
|
|
7563
|
+
}
|
|
7564
|
+
function isToolStep(input) {
|
|
7565
|
+
return input instanceof Tool;
|
|
7566
|
+
}
|
|
7567
|
+
function isStepParams(input) {
|
|
7568
|
+
return input !== null && typeof input === "object" && "id" in input && "execute" in input && !(input instanceof Agent) && !(input instanceof Tool);
|
|
7569
|
+
}
|
|
7656
7570
|
function createStep(params, agentOrToolOptions) {
|
|
7657
|
-
if (params
|
|
7658
|
-
|
|
7659
|
-
|
|
7660
|
-
|
|
7661
|
-
return
|
|
7662
|
-
|
|
7663
|
-
|
|
7664
|
-
|
|
7665
|
-
|
|
7666
|
-
|
|
7667
|
-
|
|
7668
|
-
|
|
7669
|
-
|
|
7670
|
-
|
|
7671
|
-
|
|
7672
|
-
|
|
7673
|
-
|
|
7674
|
-
|
|
7675
|
-
|
|
7676
|
-
|
|
7677
|
-
|
|
7678
|
-
|
|
7679
|
-
|
|
7680
|
-
|
|
7681
|
-
|
|
7682
|
-
|
|
7683
|
-
|
|
7684
|
-
|
|
7685
|
-
|
|
7686
|
-
|
|
7687
|
-
|
|
7688
|
-
|
|
7689
|
-
|
|
7690
|
-
|
|
7691
|
-
|
|
7692
|
-
|
|
7693
|
-
|
|
7694
|
-
|
|
7695
|
-
|
|
7696
|
-
|
|
7697
|
-
|
|
7698
|
-
|
|
7699
|
-
|
|
7700
|
-
|
|
7701
|
-
|
|
7702
|
-
|
|
7703
|
-
|
|
7704
|
-
|
|
7705
|
-
|
|
7706
|
-
|
|
7707
|
-
|
|
7708
|
-
|
|
7709
|
-
|
|
7710
|
-
|
|
7711
|
-
|
|
7712
|
-
|
|
7713
|
-
|
|
7714
|
-
|
|
7715
|
-
|
|
7716
|
-
|
|
7717
|
-
|
|
7718
|
-
|
|
7719
|
-
|
|
7720
|
-
|
|
7721
|
-
|
|
7722
|
-
|
|
7723
|
-
|
|
7724
|
-
|
|
7725
|
-
|
|
7726
|
-
|
|
7727
|
-
|
|
7728
|
-
|
|
7729
|
-
stream = modelOutput.fullStream;
|
|
7730
|
-
}
|
|
7731
|
-
let tripwireChunk = null;
|
|
7732
|
-
if (streamFormat === "legacy") {
|
|
7733
|
-
await pubsub.publish(`workflow.events.v2.${runId}`, {
|
|
7734
|
-
type: "watch",
|
|
7735
|
-
runId,
|
|
7736
|
-
data: { type: "tool-call-streaming-start", ...toolData ?? {} }
|
|
7737
|
-
});
|
|
7738
|
-
for await (const chunk of stream) {
|
|
7739
|
-
if (chunk.type === "tripwire") {
|
|
7740
|
-
tripwireChunk = chunk;
|
|
7741
|
-
break;
|
|
7571
|
+
if (isAgent(params)) {
|
|
7572
|
+
return createStepFromAgent(params, agentOrToolOptions);
|
|
7573
|
+
}
|
|
7574
|
+
if (isToolStep(params)) {
|
|
7575
|
+
return createStepFromTool(params, agentOrToolOptions);
|
|
7576
|
+
}
|
|
7577
|
+
if (isStepParams(params)) {
|
|
7578
|
+
return createStepFromParams(params);
|
|
7579
|
+
}
|
|
7580
|
+
if (isProcessor(params)) {
|
|
7581
|
+
return createStepFromProcessor(params);
|
|
7582
|
+
}
|
|
7583
|
+
throw new Error("Invalid input: expected StepParams, Agent, ToolStep, or Processor");
|
|
7584
|
+
}
|
|
7585
|
+
function createStepFromParams(params) {
|
|
7586
|
+
return {
|
|
7587
|
+
id: params.id,
|
|
7588
|
+
description: params.description,
|
|
7589
|
+
inputSchema: params.inputSchema,
|
|
7590
|
+
stateSchema: params.stateSchema,
|
|
7591
|
+
outputSchema: params.outputSchema,
|
|
7592
|
+
resumeSchema: params.resumeSchema,
|
|
7593
|
+
suspendSchema: params.suspendSchema,
|
|
7594
|
+
scorers: params.scorers,
|
|
7595
|
+
retries: params.retries,
|
|
7596
|
+
execute: params.execute.bind(params)
|
|
7597
|
+
};
|
|
7598
|
+
}
|
|
7599
|
+
function createStepFromAgent(params, agentOrToolOptions) {
|
|
7600
|
+
const options = agentOrToolOptions ?? {};
|
|
7601
|
+
const outputSchema = options?.structuredOutput?.schema ?? z.object({ text: z.string() });
|
|
7602
|
+
const { retries, scorers, ...agentOptions } = options ?? {};
|
|
7603
|
+
return {
|
|
7604
|
+
id: params.id,
|
|
7605
|
+
description: params.getDescription(),
|
|
7606
|
+
inputSchema: z.object({
|
|
7607
|
+
prompt: z.string()
|
|
7608
|
+
}),
|
|
7609
|
+
outputSchema,
|
|
7610
|
+
retries,
|
|
7611
|
+
scorers,
|
|
7612
|
+
execute: async ({
|
|
7613
|
+
inputData,
|
|
7614
|
+
runId,
|
|
7615
|
+
[PUBSUB_SYMBOL]: pubsub,
|
|
7616
|
+
[STREAM_FORMAT_SYMBOL]: streamFormat,
|
|
7617
|
+
requestContext,
|
|
7618
|
+
tracingContext,
|
|
7619
|
+
abortSignal,
|
|
7620
|
+
abort,
|
|
7621
|
+
writer
|
|
7622
|
+
}) => {
|
|
7623
|
+
let streamPromise = {};
|
|
7624
|
+
streamPromise.promise = new Promise((resolve, reject) => {
|
|
7625
|
+
streamPromise.resolve = resolve;
|
|
7626
|
+
streamPromise.reject = reject;
|
|
7627
|
+
});
|
|
7628
|
+
let structuredResult = null;
|
|
7629
|
+
const toolData = {
|
|
7630
|
+
name: params.name,
|
|
7631
|
+
args: inputData
|
|
7632
|
+
};
|
|
7633
|
+
let stream;
|
|
7634
|
+
if ((await params.getModel()).specificationVersion === "v1") {
|
|
7635
|
+
const { fullStream } = await params.streamLegacy(inputData.prompt, {
|
|
7636
|
+
...agentOptions,
|
|
7637
|
+
requestContext,
|
|
7638
|
+
tracingContext,
|
|
7639
|
+
onFinish: (result) => {
|
|
7640
|
+
const resultWithObject = result;
|
|
7641
|
+
if (agentOptions?.structuredOutput?.schema && resultWithObject.object) {
|
|
7642
|
+
structuredResult = resultWithObject.object;
|
|
7742
7643
|
}
|
|
7743
|
-
|
|
7744
|
-
|
|
7745
|
-
|
|
7746
|
-
|
|
7747
|
-
|
|
7748
|
-
|
|
7644
|
+
streamPromise.resolve(result.text);
|
|
7645
|
+
void agentOptions?.onFinish?.(result);
|
|
7646
|
+
},
|
|
7647
|
+
abortSignal
|
|
7648
|
+
});
|
|
7649
|
+
stream = fullStream;
|
|
7650
|
+
} else {
|
|
7651
|
+
const modelOutput = await params.stream(inputData.prompt, {
|
|
7652
|
+
...agentOptions,
|
|
7653
|
+
requestContext,
|
|
7654
|
+
tracingContext,
|
|
7655
|
+
onFinish: (result) => {
|
|
7656
|
+
const resultWithObject = result;
|
|
7657
|
+
if (agentOptions?.structuredOutput?.schema && resultWithObject.object) {
|
|
7658
|
+
structuredResult = resultWithObject.object;
|
|
7749
7659
|
}
|
|
7660
|
+
streamPromise.resolve(result.text);
|
|
7661
|
+
void agentOptions?.onFinish?.(result);
|
|
7662
|
+
},
|
|
7663
|
+
abortSignal
|
|
7664
|
+
});
|
|
7665
|
+
stream = modelOutput.fullStream;
|
|
7666
|
+
}
|
|
7667
|
+
let tripwireChunk = null;
|
|
7668
|
+
if (streamFormat === "legacy") {
|
|
7669
|
+
await pubsub.publish(`workflow.events.v2.${runId}`, {
|
|
7670
|
+
type: "watch",
|
|
7671
|
+
runId,
|
|
7672
|
+
data: { type: "tool-call-streaming-start", ...toolData ?? {} }
|
|
7673
|
+
});
|
|
7674
|
+
for await (const chunk of stream) {
|
|
7675
|
+
if (chunk.type === "tripwire") {
|
|
7676
|
+
tripwireChunk = chunk;
|
|
7677
|
+
break;
|
|
7750
7678
|
}
|
|
7751
|
-
|
|
7752
|
-
|
|
7753
|
-
|
|
7754
|
-
|
|
7755
|
-
|
|
7756
|
-
|
|
7757
|
-
for await (const chunk of stream) {
|
|
7758
|
-
await writer.write(chunk);
|
|
7759
|
-
if (chunk.type === "tripwire") {
|
|
7760
|
-
tripwireChunk = chunk;
|
|
7761
|
-
break;
|
|
7762
|
-
}
|
|
7679
|
+
if (chunk.type === "text-delta") {
|
|
7680
|
+
await pubsub.publish(`workflow.events.v2.${runId}`, {
|
|
7681
|
+
type: "watch",
|
|
7682
|
+
runId,
|
|
7683
|
+
data: { type: "tool-call-delta", ...toolData ?? {}, argsTextDelta: chunk.textDelta }
|
|
7684
|
+
});
|
|
7763
7685
|
}
|
|
7764
7686
|
}
|
|
7765
|
-
|
|
7766
|
-
|
|
7767
|
-
|
|
7768
|
-
|
|
7769
|
-
|
|
7770
|
-
|
|
7771
|
-
|
|
7772
|
-
|
|
7773
|
-
)
|
|
7774
|
-
|
|
7775
|
-
|
|
7776
|
-
|
|
7777
|
-
}
|
|
7778
|
-
if (structuredResult !== null) {
|
|
7779
|
-
return structuredResult;
|
|
7687
|
+
await pubsub.publish(`workflow.events.v2.${runId}`, {
|
|
7688
|
+
type: "watch",
|
|
7689
|
+
runId,
|
|
7690
|
+
data: { type: "tool-call-streaming-finish", ...toolData ?? {} }
|
|
7691
|
+
});
|
|
7692
|
+
} else {
|
|
7693
|
+
for await (const chunk of stream) {
|
|
7694
|
+
await writer.write(chunk);
|
|
7695
|
+
if (chunk.type === "tripwire") {
|
|
7696
|
+
tripwireChunk = chunk;
|
|
7697
|
+
break;
|
|
7698
|
+
}
|
|
7780
7699
|
}
|
|
7781
|
-
|
|
7782
|
-
|
|
7783
|
-
|
|
7784
|
-
|
|
7785
|
-
|
|
7786
|
-
|
|
7700
|
+
}
|
|
7701
|
+
if (tripwireChunk) {
|
|
7702
|
+
throw new TripWire(
|
|
7703
|
+
tripwireChunk.payload?.reason || "Agent tripwire triggered",
|
|
7704
|
+
{
|
|
7705
|
+
retry: tripwireChunk.payload?.retry,
|
|
7706
|
+
metadata: tripwireChunk.payload?.metadata
|
|
7707
|
+
},
|
|
7708
|
+
tripwireChunk.payload?.processorId
|
|
7709
|
+
);
|
|
7710
|
+
}
|
|
7711
|
+
if (abortSignal.aborted) {
|
|
7712
|
+
return abort();
|
|
7713
|
+
}
|
|
7714
|
+
if (structuredResult !== null) {
|
|
7715
|
+
return structuredResult;
|
|
7716
|
+
}
|
|
7717
|
+
return {
|
|
7718
|
+
text: await streamPromise.promise
|
|
7719
|
+
};
|
|
7720
|
+
},
|
|
7721
|
+
component: params.component
|
|
7722
|
+
};
|
|
7723
|
+
}
|
|
7724
|
+
function createStepFromTool(params, toolOpts) {
|
|
7725
|
+
if (!params.inputSchema || !params.outputSchema) {
|
|
7726
|
+
throw new Error("Tool must have input and output schemas defined");
|
|
7787
7727
|
}
|
|
7788
|
-
|
|
7789
|
-
|
|
7790
|
-
|
|
7791
|
-
|
|
7792
|
-
|
|
7793
|
-
|
|
7794
|
-
|
|
7795
|
-
|
|
7796
|
-
|
|
7797
|
-
|
|
7798
|
-
|
|
7799
|
-
|
|
7800
|
-
|
|
7801
|
-
|
|
7802
|
-
|
|
7803
|
-
|
|
7804
|
-
|
|
7805
|
-
|
|
7728
|
+
return {
|
|
7729
|
+
id: params.id,
|
|
7730
|
+
description: params.description,
|
|
7731
|
+
inputSchema: params.inputSchema,
|
|
7732
|
+
outputSchema: params.outputSchema,
|
|
7733
|
+
resumeSchema: params.resumeSchema,
|
|
7734
|
+
suspendSchema: params.suspendSchema,
|
|
7735
|
+
retries: toolOpts?.retries,
|
|
7736
|
+
scorers: toolOpts?.scorers,
|
|
7737
|
+
execute: async ({
|
|
7738
|
+
inputData,
|
|
7739
|
+
mastra,
|
|
7740
|
+
requestContext,
|
|
7741
|
+
tracingContext,
|
|
7742
|
+
suspend,
|
|
7743
|
+
resumeData,
|
|
7744
|
+
runId,
|
|
7745
|
+
workflowId,
|
|
7746
|
+
state,
|
|
7747
|
+
setState
|
|
7748
|
+
}) => {
|
|
7749
|
+
const toolContext = {
|
|
7806
7750
|
mastra,
|
|
7807
7751
|
requestContext,
|
|
7808
7752
|
tracingContext,
|
|
7809
|
-
suspend,
|
|
7810
7753
|
resumeData,
|
|
7811
|
-
|
|
7812
|
-
|
|
7813
|
-
|
|
7814
|
-
setState
|
|
7815
|
-
}) => {
|
|
7816
|
-
const toolContext = {
|
|
7817
|
-
mastra,
|
|
7818
|
-
requestContext,
|
|
7819
|
-
tracingContext,
|
|
7754
|
+
workflow: {
|
|
7755
|
+
runId,
|
|
7756
|
+
suspend,
|
|
7820
7757
|
resumeData,
|
|
7821
|
-
|
|
7822
|
-
|
|
7823
|
-
|
|
7824
|
-
|
|
7825
|
-
|
|
7826
|
-
|
|
7827
|
-
|
|
7828
|
-
|
|
7829
|
-
|
|
7830
|
-
|
|
7831
|
-
|
|
7832
|
-
|
|
7833
|
-
|
|
7834
|
-
|
|
7835
|
-
|
|
7836
|
-
|
|
7837
|
-
|
|
7838
|
-
|
|
7839
|
-
|
|
7840
|
-
|
|
7841
|
-
|
|
7842
|
-
|
|
7843
|
-
|
|
7844
|
-
|
|
7845
|
-
|
|
7846
|
-
|
|
7847
|
-
|
|
7848
|
-
|
|
7849
|
-
|
|
7850
|
-
|
|
7851
|
-
|
|
7852
|
-
|
|
7853
|
-
|
|
7854
|
-
|
|
7855
|
-
|
|
7856
|
-
|
|
7857
|
-
|
|
7858
|
-
|
|
7859
|
-
|
|
7860
|
-
|
|
7861
|
-
|
|
7862
|
-
|
|
7863
|
-
|
|
7864
|
-
|
|
7865
|
-
|
|
7866
|
-
|
|
7867
|
-
|
|
7868
|
-
|
|
7869
|
-
|
|
7870
|
-
|
|
7871
|
-
|
|
7872
|
-
|
|
7873
|
-
|
|
7874
|
-
|
|
7875
|
-
|
|
7876
|
-
|
|
7877
|
-
|
|
7878
|
-
|
|
7879
|
-
|
|
7880
|
-
|
|
7881
|
-
|
|
7758
|
+
workflowId,
|
|
7759
|
+
state,
|
|
7760
|
+
setState
|
|
7761
|
+
}
|
|
7762
|
+
};
|
|
7763
|
+
return params.execute(inputData, toolContext);
|
|
7764
|
+
},
|
|
7765
|
+
component: "TOOL"
|
|
7766
|
+
};
|
|
7767
|
+
}
|
|
7768
|
+
function createStepFromProcessor(processor) {
|
|
7769
|
+
const getProcessorEntityType = (phase) => {
|
|
7770
|
+
switch (phase) {
|
|
7771
|
+
case "input":
|
|
7772
|
+
return "input_processor" /* INPUT_PROCESSOR */;
|
|
7773
|
+
case "inputStep":
|
|
7774
|
+
return "input_step_processor" /* INPUT_STEP_PROCESSOR */;
|
|
7775
|
+
case "outputStream":
|
|
7776
|
+
case "outputResult":
|
|
7777
|
+
return "output_processor" /* OUTPUT_PROCESSOR */;
|
|
7778
|
+
case "outputStep":
|
|
7779
|
+
return "output_step_processor" /* OUTPUT_STEP_PROCESSOR */;
|
|
7780
|
+
default:
|
|
7781
|
+
return "output_processor" /* OUTPUT_PROCESSOR */;
|
|
7782
|
+
}
|
|
7783
|
+
};
|
|
7784
|
+
const getSpanNamePrefix = (phase) => {
|
|
7785
|
+
switch (phase) {
|
|
7786
|
+
case "input":
|
|
7787
|
+
return "input processor";
|
|
7788
|
+
case "inputStep":
|
|
7789
|
+
return "input step processor";
|
|
7790
|
+
case "outputStream":
|
|
7791
|
+
return "output stream processor";
|
|
7792
|
+
case "outputResult":
|
|
7793
|
+
return "output processor";
|
|
7794
|
+
case "outputStep":
|
|
7795
|
+
return "output step processor";
|
|
7796
|
+
default:
|
|
7797
|
+
return "processor";
|
|
7798
|
+
}
|
|
7799
|
+
};
|
|
7800
|
+
const hasPhaseMethod = (phase) => {
|
|
7801
|
+
switch (phase) {
|
|
7802
|
+
case "input":
|
|
7803
|
+
return !!processor.processInput;
|
|
7804
|
+
case "inputStep":
|
|
7805
|
+
return !!processor.processInputStep;
|
|
7806
|
+
case "outputStream":
|
|
7807
|
+
return !!processor.processOutputStream;
|
|
7808
|
+
case "outputResult":
|
|
7809
|
+
return !!processor.processOutputResult;
|
|
7810
|
+
case "outputStep":
|
|
7811
|
+
return !!processor.processOutputStep;
|
|
7812
|
+
default:
|
|
7813
|
+
return false;
|
|
7814
|
+
}
|
|
7815
|
+
};
|
|
7816
|
+
return {
|
|
7817
|
+
id: `processor:${processor.id}`,
|
|
7818
|
+
description: processor.name ?? `Processor ${processor.id}`,
|
|
7819
|
+
inputSchema: ProcessorStepInputSchema,
|
|
7820
|
+
outputSchema: ProcessorStepOutputSchema,
|
|
7821
|
+
execute: async ({ inputData, requestContext, tracingContext }) => {
|
|
7822
|
+
const input = inputData;
|
|
7823
|
+
const {
|
|
7824
|
+
phase,
|
|
7825
|
+
messages,
|
|
7826
|
+
messageList,
|
|
7827
|
+
stepNumber,
|
|
7828
|
+
systemMessages,
|
|
7829
|
+
part,
|
|
7830
|
+
streamParts,
|
|
7831
|
+
state,
|
|
7832
|
+
finishReason,
|
|
7833
|
+
toolCalls,
|
|
7834
|
+
text,
|
|
7835
|
+
retryCount,
|
|
7836
|
+
// inputStep phase fields for model/tools configuration
|
|
7837
|
+
model,
|
|
7838
|
+
tools,
|
|
7839
|
+
toolChoice,
|
|
7840
|
+
activeTools,
|
|
7841
|
+
providerOptions,
|
|
7842
|
+
modelSettings,
|
|
7843
|
+
structuredOutput,
|
|
7844
|
+
steps
|
|
7845
|
+
} = input;
|
|
7846
|
+
const abort = (reason, options) => {
|
|
7847
|
+
throw new TripWire(reason || `Tripwire triggered by ${processor.id}`, options, processor.id);
|
|
7848
|
+
};
|
|
7849
|
+
if (!hasPhaseMethod(phase)) {
|
|
7850
|
+
return input;
|
|
7882
7851
|
}
|
|
7883
|
-
|
|
7884
|
-
|
|
7885
|
-
|
|
7886
|
-
|
|
7887
|
-
|
|
7888
|
-
|
|
7889
|
-
|
|
7890
|
-
|
|
7891
|
-
|
|
7892
|
-
|
|
7893
|
-
|
|
7852
|
+
const currentSpan = tracingContext?.currentSpan;
|
|
7853
|
+
const parentSpan = phase === "inputStep" || phase === "outputStep" ? currentSpan?.findParent("model_step" /* MODEL_STEP */) || currentSpan : currentSpan?.findParent("agent_run" /* AGENT_RUN */) || currentSpan;
|
|
7854
|
+
const processorSpan = phase !== "outputStream" ? parentSpan?.createChildSpan({
|
|
7855
|
+
type: "processor_run" /* PROCESSOR_RUN */,
|
|
7856
|
+
name: `${getSpanNamePrefix(phase)}: ${processor.id}`,
|
|
7857
|
+
entityType: getProcessorEntityType(phase),
|
|
7858
|
+
entityId: processor.id,
|
|
7859
|
+
entityName: processor.name ?? processor.id,
|
|
7860
|
+
input: { phase, messageCount: messages?.length },
|
|
7861
|
+
attributes: {
|
|
7862
|
+
processorExecutor: "workflow",
|
|
7863
|
+
// Read processorIndex from processor (set in combineProcessorsIntoWorkflow)
|
|
7864
|
+
processorIndex: processor.processorIndex
|
|
7865
|
+
}
|
|
7866
|
+
}) : void 0;
|
|
7867
|
+
const processorTracingContext = processorSpan ? { currentSpan: processorSpan } : tracingContext;
|
|
7868
|
+
const baseContext = {
|
|
7869
|
+
abort,
|
|
7870
|
+
retryCount: retryCount ?? 0,
|
|
7894
7871
|
requestContext,
|
|
7895
|
-
tracingContext
|
|
7896
|
-
}
|
|
7897
|
-
|
|
7898
|
-
|
|
7899
|
-
|
|
7900
|
-
|
|
7901
|
-
|
|
7902
|
-
|
|
7903
|
-
|
|
7904
|
-
|
|
7905
|
-
|
|
7906
|
-
|
|
7907
|
-
|
|
7908
|
-
|
|
7909
|
-
|
|
7910
|
-
|
|
7911
|
-
|
|
7912
|
-
|
|
7913
|
-
|
|
7914
|
-
|
|
7915
|
-
|
|
7916
|
-
|
|
7917
|
-
|
|
7918
|
-
|
|
7919
|
-
|
|
7920
|
-
|
|
7921
|
-
|
|
7922
|
-
|
|
7923
|
-
|
|
7924
|
-
|
|
7925
|
-
|
|
7926
|
-
|
|
7927
|
-
|
|
7928
|
-
|
|
7929
|
-
|
|
7930
|
-
type: "processor_run" /* PROCESSOR_RUN */,
|
|
7931
|
-
name: `${getSpanNamePrefix(phase)}: ${processor.id}`,
|
|
7932
|
-
entityType: getProcessorEntityType(phase),
|
|
7933
|
-
entityId: processor.id,
|
|
7934
|
-
entityName: processor.name ?? processor.id,
|
|
7935
|
-
input: { phase, messageCount: messages?.length },
|
|
7936
|
-
attributes: {
|
|
7937
|
-
processorExecutor: "workflow",
|
|
7938
|
-
// Read processorIndex from processor (set in combineProcessorsIntoWorkflow)
|
|
7939
|
-
processorIndex: processor.processorIndex
|
|
7940
|
-
}
|
|
7941
|
-
}) : void 0;
|
|
7942
|
-
const processorTracingContext = processorSpan ? { currentSpan: processorSpan } : tracingContext;
|
|
7943
|
-
const baseContext = {
|
|
7944
|
-
abort,
|
|
7945
|
-
retryCount: retryCount ?? 0,
|
|
7946
|
-
requestContext,
|
|
7947
|
-
tracingContext: processorTracingContext
|
|
7948
|
-
};
|
|
7949
|
-
const passThrough = {
|
|
7950
|
-
phase,
|
|
7951
|
-
// Auto-create MessageList from messages if not provided
|
|
7952
|
-
// This enables running processor workflows from the UI where messageList can't be serialized
|
|
7953
|
-
messageList: messageList ?? (Array.isArray(messages) ? new MessageList().add(messages, "input").addSystem(systemMessages ?? []) : void 0),
|
|
7954
|
-
stepNumber,
|
|
7955
|
-
systemMessages,
|
|
7956
|
-
streamParts,
|
|
7957
|
-
state,
|
|
7958
|
-
finishReason,
|
|
7959
|
-
toolCalls,
|
|
7960
|
-
text,
|
|
7961
|
-
retryCount,
|
|
7962
|
-
// inputStep phase fields for model/tools configuration
|
|
7963
|
-
model,
|
|
7964
|
-
tools,
|
|
7965
|
-
toolChoice,
|
|
7966
|
-
activeTools,
|
|
7967
|
-
providerOptions,
|
|
7968
|
-
modelSettings,
|
|
7969
|
-
structuredOutput,
|
|
7970
|
-
steps
|
|
7971
|
-
};
|
|
7972
|
-
const executePhaseWithSpan = async (fn) => {
|
|
7973
|
-
try {
|
|
7974
|
-
const result = await fn();
|
|
7975
|
-
processorSpan?.end({ output: result });
|
|
7976
|
-
return result;
|
|
7977
|
-
} catch (error) {
|
|
7978
|
-
if (error instanceof TripWire) {
|
|
7979
|
-
processorSpan?.end({ output: { tripwire: error.message } });
|
|
7980
|
-
} else {
|
|
7981
|
-
processorSpan?.error({ error, endSpan: true });
|
|
7982
|
-
}
|
|
7983
|
-
throw error;
|
|
7872
|
+
tracingContext: processorTracingContext
|
|
7873
|
+
};
|
|
7874
|
+
const passThrough = {
|
|
7875
|
+
phase,
|
|
7876
|
+
// Auto-create MessageList from messages if not provided
|
|
7877
|
+
// This enables running processor workflows from the UI where messageList can't be serialized
|
|
7878
|
+
messageList: messageList ?? (Array.isArray(messages) ? new MessageList().add(messages, "input").addSystem(systemMessages ?? []) : void 0),
|
|
7879
|
+
stepNumber,
|
|
7880
|
+
systemMessages,
|
|
7881
|
+
streamParts,
|
|
7882
|
+
state,
|
|
7883
|
+
finishReason,
|
|
7884
|
+
toolCalls,
|
|
7885
|
+
text,
|
|
7886
|
+
retryCount,
|
|
7887
|
+
// inputStep phase fields for model/tools configuration
|
|
7888
|
+
model,
|
|
7889
|
+
tools,
|
|
7890
|
+
toolChoice,
|
|
7891
|
+
activeTools,
|
|
7892
|
+
providerOptions,
|
|
7893
|
+
modelSettings,
|
|
7894
|
+
structuredOutput,
|
|
7895
|
+
steps
|
|
7896
|
+
};
|
|
7897
|
+
const executePhaseWithSpan = async (fn) => {
|
|
7898
|
+
try {
|
|
7899
|
+
const result = await fn();
|
|
7900
|
+
processorSpan?.end({ output: result });
|
|
7901
|
+
return result;
|
|
7902
|
+
} catch (error) {
|
|
7903
|
+
if (error instanceof TripWire) {
|
|
7904
|
+
processorSpan?.end({ output: { tripwire: error.message } });
|
|
7905
|
+
} else {
|
|
7906
|
+
processorSpan?.error({ error, endSpan: true });
|
|
7984
7907
|
}
|
|
7985
|
-
|
|
7986
|
-
|
|
7987
|
-
|
|
7988
|
-
|
|
7989
|
-
|
|
7990
|
-
|
|
7908
|
+
throw error;
|
|
7909
|
+
}
|
|
7910
|
+
};
|
|
7911
|
+
return executePhaseWithSpan(async () => {
|
|
7912
|
+
switch (phase) {
|
|
7913
|
+
case "input": {
|
|
7914
|
+
if (processor.processInput) {
|
|
7915
|
+
if (!passThrough.messageList) {
|
|
7916
|
+
throw new MastraError({
|
|
7917
|
+
category: "USER" /* USER */,
|
|
7918
|
+
domain: "MASTRA_WORKFLOW" /* MASTRA_WORKFLOW */,
|
|
7919
|
+
id: "PROCESSOR_MISSING_MESSAGE_LIST",
|
|
7920
|
+
text: `Processor ${processor.id} requires messageList or messages for processInput phase`
|
|
7921
|
+
});
|
|
7922
|
+
}
|
|
7923
|
+
const idsBeforeProcessing = messages.map((m) => m.id);
|
|
7924
|
+
const check = passThrough.messageList.makeMessageSourceChecker();
|
|
7925
|
+
const result = await processor.processInput({
|
|
7926
|
+
...baseContext,
|
|
7927
|
+
messages,
|
|
7928
|
+
messageList: passThrough.messageList,
|
|
7929
|
+
systemMessages: systemMessages ?? []
|
|
7930
|
+
});
|
|
7931
|
+
if (result instanceof MessageList) {
|
|
7932
|
+
if (result !== passThrough.messageList) {
|
|
7991
7933
|
throw new MastraError({
|
|
7992
7934
|
category: "USER" /* USER */,
|
|
7993
7935
|
domain: "MASTRA_WORKFLOW" /* MASTRA_WORKFLOW */,
|
|
7994
|
-
id: "
|
|
7995
|
-
text: `Processor ${processor.id}
|
|
7936
|
+
id: "PROCESSOR_RETURNED_EXTERNAL_MESSAGE_LIST",
|
|
7937
|
+
text: `Processor ${processor.id} returned a MessageList instance other than the one passed in. Use the messageList argument instead.`
|
|
7996
7938
|
});
|
|
7997
7939
|
}
|
|
7998
|
-
|
|
7999
|
-
|
|
8000
|
-
|
|
8001
|
-
|
|
8002
|
-
|
|
8003
|
-
|
|
8004
|
-
|
|
8005
|
-
|
|
8006
|
-
|
|
8007
|
-
|
|
8008
|
-
|
|
8009
|
-
|
|
8010
|
-
|
|
8011
|
-
|
|
8012
|
-
|
|
8013
|
-
|
|
8014
|
-
|
|
8015
|
-
|
|
8016
|
-
|
|
8017
|
-
|
|
8018
|
-
|
|
8019
|
-
|
|
8020
|
-
|
|
8021
|
-
|
|
8022
|
-
|
|
8023
|
-
|
|
8024
|
-
|
|
8025
|
-
|
|
8026
|
-
|
|
8027
|
-
);
|
|
8028
|
-
return { ...passThrough, messages: result };
|
|
8029
|
-
} else if (result && "messages" in result && "systemMessages" in result) {
|
|
8030
|
-
const typedResult = result;
|
|
8031
|
-
ProcessorRunner.applyMessagesToMessageList(
|
|
8032
|
-
typedResult.messages,
|
|
8033
|
-
passThrough.messageList,
|
|
8034
|
-
idsBeforeProcessing,
|
|
8035
|
-
check,
|
|
8036
|
-
"input"
|
|
8037
|
-
);
|
|
8038
|
-
passThrough.messageList.replaceAllSystemMessages(typedResult.systemMessages);
|
|
8039
|
-
return {
|
|
8040
|
-
...passThrough,
|
|
8041
|
-
messages: typedResult.messages,
|
|
8042
|
-
systemMessages: typedResult.systemMessages
|
|
8043
|
-
};
|
|
8044
|
-
}
|
|
8045
|
-
return { ...passThrough, messages };
|
|
7940
|
+
return {
|
|
7941
|
+
...passThrough,
|
|
7942
|
+
messages: result.get.all.db(),
|
|
7943
|
+
systemMessages: result.getAllSystemMessages()
|
|
7944
|
+
};
|
|
7945
|
+
} else if (Array.isArray(result)) {
|
|
7946
|
+
ProcessorRunner.applyMessagesToMessageList(
|
|
7947
|
+
result,
|
|
7948
|
+
passThrough.messageList,
|
|
7949
|
+
idsBeforeProcessing,
|
|
7950
|
+
check,
|
|
7951
|
+
"input"
|
|
7952
|
+
);
|
|
7953
|
+
return { ...passThrough, messages: result };
|
|
7954
|
+
} else if (result && "messages" in result && "systemMessages" in result) {
|
|
7955
|
+
const typedResult = result;
|
|
7956
|
+
ProcessorRunner.applyMessagesToMessageList(
|
|
7957
|
+
typedResult.messages,
|
|
7958
|
+
passThrough.messageList,
|
|
7959
|
+
idsBeforeProcessing,
|
|
7960
|
+
check,
|
|
7961
|
+
"input"
|
|
7962
|
+
);
|
|
7963
|
+
passThrough.messageList.replaceAllSystemMessages(typedResult.systemMessages);
|
|
7964
|
+
return {
|
|
7965
|
+
...passThrough,
|
|
7966
|
+
messages: typedResult.messages,
|
|
7967
|
+
systemMessages: typedResult.systemMessages
|
|
7968
|
+
};
|
|
8046
7969
|
}
|
|
8047
7970
|
return { ...passThrough, messages };
|
|
8048
7971
|
}
|
|
8049
|
-
|
|
8050
|
-
|
|
8051
|
-
|
|
8052
|
-
|
|
8053
|
-
|
|
8054
|
-
|
|
8055
|
-
|
|
8056
|
-
|
|
8057
|
-
|
|
8058
|
-
|
|
8059
|
-
|
|
8060
|
-
|
|
8061
|
-
|
|
7972
|
+
return { ...passThrough, messages };
|
|
7973
|
+
}
|
|
7974
|
+
case "inputStep": {
|
|
7975
|
+
if (processor.processInputStep) {
|
|
7976
|
+
if (!passThrough.messageList) {
|
|
7977
|
+
throw new MastraError({
|
|
7978
|
+
category: "USER" /* USER */,
|
|
7979
|
+
domain: "MASTRA_WORKFLOW" /* MASTRA_WORKFLOW */,
|
|
7980
|
+
id: "PROCESSOR_MISSING_MESSAGE_LIST",
|
|
7981
|
+
text: `Processor ${processor.id} requires messageList or messages for processInputStep phase`
|
|
7982
|
+
});
|
|
7983
|
+
}
|
|
7984
|
+
const idsBeforeProcessing = messages.map((m) => m.id);
|
|
7985
|
+
const check = passThrough.messageList.makeMessageSourceChecker();
|
|
7986
|
+
const result = await processor.processInputStep({
|
|
7987
|
+
...baseContext,
|
|
7988
|
+
messages,
|
|
7989
|
+
messageList: passThrough.messageList,
|
|
7990
|
+
stepNumber: stepNumber ?? 0,
|
|
7991
|
+
systemMessages: systemMessages ?? [],
|
|
7992
|
+
// Pass model/tools configuration fields - types match ProcessInputStepArgs
|
|
7993
|
+
model,
|
|
7994
|
+
tools,
|
|
7995
|
+
toolChoice,
|
|
7996
|
+
activeTools,
|
|
7997
|
+
providerOptions,
|
|
7998
|
+
modelSettings,
|
|
7999
|
+
structuredOutput,
|
|
8000
|
+
steps: steps ?? []
|
|
8001
|
+
});
|
|
8002
|
+
const validatedResult = await ProcessorRunner.validateAndFormatProcessInputStepResult(result, {
|
|
8003
|
+
messageList: passThrough.messageList,
|
|
8004
|
+
processor,
|
|
8005
|
+
stepNumber: stepNumber ?? 0
|
|
8006
|
+
});
|
|
8007
|
+
if (validatedResult.messages) {
|
|
8008
|
+
ProcessorRunner.applyMessagesToMessageList(
|
|
8009
|
+
validatedResult.messages,
|
|
8010
|
+
passThrough.messageList,
|
|
8011
|
+
idsBeforeProcessing,
|
|
8012
|
+
check
|
|
8013
|
+
);
|
|
8014
|
+
}
|
|
8015
|
+
if (validatedResult.systemMessages) {
|
|
8016
|
+
passThrough.messageList.replaceAllSystemMessages(validatedResult.systemMessages);
|
|
8017
|
+
}
|
|
8018
|
+
return { ...passThrough, messages, ...validatedResult };
|
|
8019
|
+
}
|
|
8020
|
+
return { ...passThrough, messages };
|
|
8021
|
+
}
|
|
8022
|
+
case "outputStream": {
|
|
8023
|
+
if (processor.processOutputStream) {
|
|
8024
|
+
const spanKey = `__outputStreamSpan_${processor.id}`;
|
|
8025
|
+
const mutableState = state ?? {};
|
|
8026
|
+
let processorSpan2 = mutableState[spanKey];
|
|
8027
|
+
if (!processorSpan2 && parentSpan) {
|
|
8028
|
+
processorSpan2 = parentSpan.createChildSpan({
|
|
8029
|
+
type: "processor_run" /* PROCESSOR_RUN */,
|
|
8030
|
+
name: `output stream processor: ${processor.id}`,
|
|
8031
|
+
entityType: "output_processor" /* OUTPUT_PROCESSOR */,
|
|
8032
|
+
entityId: processor.id,
|
|
8033
|
+
entityName: processor.name ?? processor.id,
|
|
8034
|
+
input: { phase, streamParts: [] },
|
|
8035
|
+
attributes: {
|
|
8036
|
+
processorExecutor: "workflow",
|
|
8037
|
+
processorIndex: processor.processorIndex
|
|
8038
|
+
}
|
|
8039
|
+
});
|
|
8040
|
+
mutableState[spanKey] = processorSpan2;
|
|
8041
|
+
}
|
|
8042
|
+
if (processorSpan2) {
|
|
8043
|
+
processorSpan2.input = {
|
|
8044
|
+
phase,
|
|
8045
|
+
streamParts: streamParts ?? [],
|
|
8046
|
+
totalChunks: (streamParts ?? []).length
|
|
8047
|
+
};
|
|
8048
|
+
}
|
|
8049
|
+
const processorTracingContext2 = processorSpan2 ? { currentSpan: processorSpan2 } : baseContext.tracingContext;
|
|
8050
|
+
let result;
|
|
8051
|
+
try {
|
|
8052
|
+
result = await processor.processOutputStream({
|
|
8062
8053
|
...baseContext,
|
|
8063
|
-
|
|
8064
|
-
|
|
8065
|
-
|
|
8066
|
-
|
|
8067
|
-
|
|
8068
|
-
|
|
8069
|
-
tools,
|
|
8070
|
-
toolChoice,
|
|
8071
|
-
activeTools,
|
|
8072
|
-
providerOptions,
|
|
8073
|
-
modelSettings,
|
|
8074
|
-
structuredOutput,
|
|
8075
|
-
steps: steps ?? []
|
|
8076
|
-
});
|
|
8077
|
-
const validatedResult = await ProcessorRunner.validateAndFormatProcessInputStepResult(result, {
|
|
8078
|
-
messageList: passThrough.messageList,
|
|
8079
|
-
processor,
|
|
8080
|
-
stepNumber: stepNumber ?? 0
|
|
8054
|
+
tracingContext: processorTracingContext2,
|
|
8055
|
+
part,
|
|
8056
|
+
streamParts: streamParts ?? [],
|
|
8057
|
+
state: mutableState,
|
|
8058
|
+
messageList: passThrough.messageList
|
|
8059
|
+
// Optional for stream processing
|
|
8081
8060
|
});
|
|
8082
|
-
if (
|
|
8083
|
-
|
|
8084
|
-
|
|
8085
|
-
passThrough.messageList,
|
|
8086
|
-
idsBeforeProcessing,
|
|
8087
|
-
check
|
|
8088
|
-
);
|
|
8061
|
+
if (part && part.type === "finish") {
|
|
8062
|
+
processorSpan2?.end({ output: result });
|
|
8063
|
+
delete mutableState[spanKey];
|
|
8089
8064
|
}
|
|
8090
|
-
|
|
8091
|
-
|
|
8065
|
+
} catch (error) {
|
|
8066
|
+
if (error instanceof TripWire) {
|
|
8067
|
+
processorSpan2?.end({ output: { tripwire: error.message } });
|
|
8068
|
+
} else {
|
|
8069
|
+
processorSpan2?.error({ error, endSpan: true });
|
|
8092
8070
|
}
|
|
8093
|
-
|
|
8071
|
+
delete mutableState[spanKey];
|
|
8072
|
+
throw error;
|
|
8094
8073
|
}
|
|
8095
|
-
return { ...passThrough,
|
|
8074
|
+
return { ...passThrough, state: mutableState, part: result };
|
|
8096
8075
|
}
|
|
8097
|
-
|
|
8098
|
-
|
|
8099
|
-
|
|
8100
|
-
|
|
8101
|
-
|
|
8102
|
-
|
|
8103
|
-
|
|
8104
|
-
|
|
8105
|
-
|
|
8106
|
-
|
|
8107
|
-
|
|
8108
|
-
entityName: processor.name ?? processor.id,
|
|
8109
|
-
input: { phase, streamParts: [] },
|
|
8110
|
-
attributes: {
|
|
8111
|
-
processorExecutor: "workflow",
|
|
8112
|
-
processorIndex: processor.processorIndex
|
|
8113
|
-
}
|
|
8114
|
-
});
|
|
8115
|
-
mutableState[spanKey] = processorSpan2;
|
|
8116
|
-
}
|
|
8117
|
-
if (processorSpan2) {
|
|
8118
|
-
processorSpan2.input = {
|
|
8119
|
-
phase,
|
|
8120
|
-
streamParts: streamParts ?? [],
|
|
8121
|
-
totalChunks: (streamParts ?? []).length
|
|
8122
|
-
};
|
|
8123
|
-
}
|
|
8124
|
-
const processorTracingContext2 = processorSpan2 ? { currentSpan: processorSpan2 } : baseContext.tracingContext;
|
|
8125
|
-
let result;
|
|
8126
|
-
try {
|
|
8127
|
-
result = await processor.processOutputStream({
|
|
8128
|
-
...baseContext,
|
|
8129
|
-
tracingContext: processorTracingContext2,
|
|
8130
|
-
part,
|
|
8131
|
-
streamParts: streamParts ?? [],
|
|
8132
|
-
state: mutableState,
|
|
8133
|
-
messageList: passThrough.messageList
|
|
8134
|
-
// Optional for stream processing
|
|
8135
|
-
});
|
|
8136
|
-
if (part && part.type === "finish") {
|
|
8137
|
-
processorSpan2?.end({ output: result });
|
|
8138
|
-
delete mutableState[spanKey];
|
|
8139
|
-
}
|
|
8140
|
-
} catch (error) {
|
|
8141
|
-
if (error instanceof TripWire) {
|
|
8142
|
-
processorSpan2?.end({ output: { tripwire: error.message } });
|
|
8143
|
-
} else {
|
|
8144
|
-
processorSpan2?.error({ error, endSpan: true });
|
|
8145
|
-
}
|
|
8146
|
-
delete mutableState[spanKey];
|
|
8147
|
-
throw error;
|
|
8148
|
-
}
|
|
8149
|
-
return { ...passThrough, state: mutableState, part: result };
|
|
8076
|
+
return { ...passThrough, part };
|
|
8077
|
+
}
|
|
8078
|
+
case "outputResult": {
|
|
8079
|
+
if (processor.processOutputResult) {
|
|
8080
|
+
if (!passThrough.messageList) {
|
|
8081
|
+
throw new MastraError({
|
|
8082
|
+
category: "USER" /* USER */,
|
|
8083
|
+
domain: "MASTRA_WORKFLOW" /* MASTRA_WORKFLOW */,
|
|
8084
|
+
id: "PROCESSOR_MISSING_MESSAGE_LIST",
|
|
8085
|
+
text: `Processor ${processor.id} requires messageList or messages for processOutputResult phase`
|
|
8086
|
+
});
|
|
8150
8087
|
}
|
|
8151
|
-
|
|
8152
|
-
|
|
8153
|
-
|
|
8154
|
-
|
|
8155
|
-
|
|
8088
|
+
const idsBeforeProcessing = messages.map((m) => m.id);
|
|
8089
|
+
const check = passThrough.messageList.makeMessageSourceChecker();
|
|
8090
|
+
const result = await processor.processOutputResult({
|
|
8091
|
+
...baseContext,
|
|
8092
|
+
messages,
|
|
8093
|
+
messageList: passThrough.messageList
|
|
8094
|
+
});
|
|
8095
|
+
if (result instanceof MessageList) {
|
|
8096
|
+
if (result !== passThrough.messageList) {
|
|
8156
8097
|
throw new MastraError({
|
|
8157
8098
|
category: "USER" /* USER */,
|
|
8158
8099
|
domain: "MASTRA_WORKFLOW" /* MASTRA_WORKFLOW */,
|
|
8159
|
-
id: "
|
|
8160
|
-
text: `Processor ${processor.id}
|
|
8100
|
+
id: "PROCESSOR_RETURNED_EXTERNAL_MESSAGE_LIST",
|
|
8101
|
+
text: `Processor ${processor.id} returned a MessageList instance other than the one passed in. Use the messageList argument instead.`
|
|
8161
8102
|
});
|
|
8162
8103
|
}
|
|
8163
|
-
|
|
8164
|
-
|
|
8165
|
-
|
|
8166
|
-
|
|
8167
|
-
|
|
8168
|
-
|
|
8169
|
-
|
|
8170
|
-
|
|
8171
|
-
|
|
8172
|
-
|
|
8173
|
-
|
|
8174
|
-
|
|
8175
|
-
|
|
8176
|
-
|
|
8177
|
-
|
|
8178
|
-
|
|
8179
|
-
|
|
8180
|
-
|
|
8181
|
-
|
|
8182
|
-
|
|
8183
|
-
|
|
8184
|
-
|
|
8185
|
-
|
|
8186
|
-
|
|
8187
|
-
|
|
8188
|
-
|
|
8189
|
-
|
|
8190
|
-
|
|
8191
|
-
|
|
8192
|
-
return { ...passThrough, messages: result };
|
|
8193
|
-
} else if (result && "messages" in result && "systemMessages" in result) {
|
|
8194
|
-
const typedResult = result;
|
|
8195
|
-
ProcessorRunner.applyMessagesToMessageList(
|
|
8196
|
-
typedResult.messages,
|
|
8197
|
-
passThrough.messageList,
|
|
8198
|
-
idsBeforeProcessing,
|
|
8199
|
-
check,
|
|
8200
|
-
"response"
|
|
8201
|
-
);
|
|
8202
|
-
passThrough.messageList.replaceAllSystemMessages(typedResult.systemMessages);
|
|
8203
|
-
return {
|
|
8204
|
-
...passThrough,
|
|
8205
|
-
messages: typedResult.messages,
|
|
8206
|
-
systemMessages: typedResult.systemMessages
|
|
8207
|
-
};
|
|
8208
|
-
}
|
|
8209
|
-
return { ...passThrough, messages };
|
|
8104
|
+
return {
|
|
8105
|
+
...passThrough,
|
|
8106
|
+
messages: result.get.all.db(),
|
|
8107
|
+
systemMessages: result.getAllSystemMessages()
|
|
8108
|
+
};
|
|
8109
|
+
} else if (Array.isArray(result)) {
|
|
8110
|
+
ProcessorRunner.applyMessagesToMessageList(
|
|
8111
|
+
result,
|
|
8112
|
+
passThrough.messageList,
|
|
8113
|
+
idsBeforeProcessing,
|
|
8114
|
+
check,
|
|
8115
|
+
"response"
|
|
8116
|
+
);
|
|
8117
|
+
return { ...passThrough, messages: result };
|
|
8118
|
+
} else if (result && "messages" in result && "systemMessages" in result) {
|
|
8119
|
+
const typedResult = result;
|
|
8120
|
+
ProcessorRunner.applyMessagesToMessageList(
|
|
8121
|
+
typedResult.messages,
|
|
8122
|
+
passThrough.messageList,
|
|
8123
|
+
idsBeforeProcessing,
|
|
8124
|
+
check,
|
|
8125
|
+
"response"
|
|
8126
|
+
);
|
|
8127
|
+
passThrough.messageList.replaceAllSystemMessages(typedResult.systemMessages);
|
|
8128
|
+
return {
|
|
8129
|
+
...passThrough,
|
|
8130
|
+
messages: typedResult.messages,
|
|
8131
|
+
systemMessages: typedResult.systemMessages
|
|
8132
|
+
};
|
|
8210
8133
|
}
|
|
8211
8134
|
return { ...passThrough, messages };
|
|
8212
8135
|
}
|
|
8213
|
-
|
|
8214
|
-
|
|
8215
|
-
|
|
8136
|
+
return { ...passThrough, messages };
|
|
8137
|
+
}
|
|
8138
|
+
case "outputStep": {
|
|
8139
|
+
if (processor.processOutputStep) {
|
|
8140
|
+
if (!passThrough.messageList) {
|
|
8141
|
+
throw new MastraError({
|
|
8142
|
+
category: "USER" /* USER */,
|
|
8143
|
+
domain: "MASTRA_WORKFLOW" /* MASTRA_WORKFLOW */,
|
|
8144
|
+
id: "PROCESSOR_MISSING_MESSAGE_LIST",
|
|
8145
|
+
text: `Processor ${processor.id} requires messageList or messages for processOutputStep phase`
|
|
8146
|
+
});
|
|
8147
|
+
}
|
|
8148
|
+
const idsBeforeProcessing = messages.map((m) => m.id);
|
|
8149
|
+
const check = passThrough.messageList.makeMessageSourceChecker();
|
|
8150
|
+
const result = await processor.processOutputStep({
|
|
8151
|
+
...baseContext,
|
|
8152
|
+
messages,
|
|
8153
|
+
messageList: passThrough.messageList,
|
|
8154
|
+
stepNumber: stepNumber ?? 0,
|
|
8155
|
+
finishReason,
|
|
8156
|
+
toolCalls,
|
|
8157
|
+
text,
|
|
8158
|
+
systemMessages: systemMessages ?? [],
|
|
8159
|
+
steps: steps ?? []
|
|
8160
|
+
});
|
|
8161
|
+
if (result instanceof MessageList) {
|
|
8162
|
+
if (result !== passThrough.messageList) {
|
|
8216
8163
|
throw new MastraError({
|
|
8217
8164
|
category: "USER" /* USER */,
|
|
8218
8165
|
domain: "MASTRA_WORKFLOW" /* MASTRA_WORKFLOW */,
|
|
8219
|
-
id: "
|
|
8220
|
-
text: `Processor ${processor.id}
|
|
8166
|
+
id: "PROCESSOR_RETURNED_EXTERNAL_MESSAGE_LIST",
|
|
8167
|
+
text: `Processor ${processor.id} returned a MessageList instance other than the one passed in. Use the messageList argument instead.`
|
|
8221
8168
|
});
|
|
8222
8169
|
}
|
|
8223
|
-
|
|
8224
|
-
|
|
8225
|
-
|
|
8226
|
-
|
|
8227
|
-
|
|
8228
|
-
|
|
8229
|
-
|
|
8230
|
-
|
|
8231
|
-
|
|
8232
|
-
|
|
8233
|
-
|
|
8234
|
-
|
|
8235
|
-
|
|
8236
|
-
|
|
8237
|
-
|
|
8238
|
-
|
|
8239
|
-
|
|
8240
|
-
|
|
8241
|
-
|
|
8242
|
-
|
|
8243
|
-
|
|
8244
|
-
|
|
8245
|
-
|
|
8246
|
-
|
|
8247
|
-
|
|
8248
|
-
|
|
8249
|
-
|
|
8250
|
-
|
|
8251
|
-
|
|
8252
|
-
result,
|
|
8253
|
-
passThrough.messageList,
|
|
8254
|
-
idsBeforeProcessing,
|
|
8255
|
-
check,
|
|
8256
|
-
"response"
|
|
8257
|
-
);
|
|
8258
|
-
return { ...passThrough, messages: result };
|
|
8259
|
-
} else if (result && "messages" in result && "systemMessages" in result) {
|
|
8260
|
-
const typedResult = result;
|
|
8261
|
-
ProcessorRunner.applyMessagesToMessageList(
|
|
8262
|
-
typedResult.messages,
|
|
8263
|
-
passThrough.messageList,
|
|
8264
|
-
idsBeforeProcessing,
|
|
8265
|
-
check,
|
|
8266
|
-
"response"
|
|
8267
|
-
);
|
|
8268
|
-
passThrough.messageList.replaceAllSystemMessages(typedResult.systemMessages);
|
|
8269
|
-
return {
|
|
8270
|
-
...passThrough,
|
|
8271
|
-
messages: typedResult.messages,
|
|
8272
|
-
systemMessages: typedResult.systemMessages
|
|
8273
|
-
};
|
|
8274
|
-
}
|
|
8275
|
-
return { ...passThrough, messages };
|
|
8170
|
+
return {
|
|
8171
|
+
...passThrough,
|
|
8172
|
+
messages: result.get.all.db(),
|
|
8173
|
+
systemMessages: result.getAllSystemMessages()
|
|
8174
|
+
};
|
|
8175
|
+
} else if (Array.isArray(result)) {
|
|
8176
|
+
ProcessorRunner.applyMessagesToMessageList(
|
|
8177
|
+
result,
|
|
8178
|
+
passThrough.messageList,
|
|
8179
|
+
idsBeforeProcessing,
|
|
8180
|
+
check,
|
|
8181
|
+
"response"
|
|
8182
|
+
);
|
|
8183
|
+
return { ...passThrough, messages: result };
|
|
8184
|
+
} else if (result && "messages" in result && "systemMessages" in result) {
|
|
8185
|
+
const typedResult = result;
|
|
8186
|
+
ProcessorRunner.applyMessagesToMessageList(
|
|
8187
|
+
typedResult.messages,
|
|
8188
|
+
passThrough.messageList,
|
|
8189
|
+
idsBeforeProcessing,
|
|
8190
|
+
check,
|
|
8191
|
+
"response"
|
|
8192
|
+
);
|
|
8193
|
+
passThrough.messageList.replaceAllSystemMessages(typedResult.systemMessages);
|
|
8194
|
+
return {
|
|
8195
|
+
...passThrough,
|
|
8196
|
+
messages: typedResult.messages,
|
|
8197
|
+
systemMessages: typedResult.systemMessages
|
|
8198
|
+
};
|
|
8276
8199
|
}
|
|
8277
8200
|
return { ...passThrough, messages };
|
|
8278
8201
|
}
|
|
8279
|
-
|
|
8280
|
-
return { ...passThrough, messages };
|
|
8202
|
+
return { ...passThrough, messages };
|
|
8281
8203
|
}
|
|
8282
|
-
|
|
8283
|
-
|
|
8284
|
-
|
|
8285
|
-
|
|
8286
|
-
|
|
8287
|
-
|
|
8288
|
-
id: params.id,
|
|
8289
|
-
description: params.description,
|
|
8290
|
-
inputSchema: params.inputSchema,
|
|
8291
|
-
stateSchema: params.stateSchema,
|
|
8292
|
-
outputSchema: params.outputSchema,
|
|
8293
|
-
resumeSchema: params.resumeSchema,
|
|
8294
|
-
suspendSchema: params.suspendSchema,
|
|
8295
|
-
scorers: params.scorers,
|
|
8296
|
-
retries: params.retries,
|
|
8297
|
-
execute: params.execute.bind(params)
|
|
8204
|
+
default:
|
|
8205
|
+
return { ...passThrough, messages };
|
|
8206
|
+
}
|
|
8207
|
+
});
|
|
8208
|
+
},
|
|
8209
|
+
component: "PROCESSOR"
|
|
8298
8210
|
};
|
|
8299
8211
|
}
|
|
8300
8212
|
function cloneStep(step, opts) {
|
|
@@ -8422,6 +8334,9 @@ var Workflow = class extends MastraBase {
|
|
|
8422
8334
|
* Adds a step to the workflow
|
|
8423
8335
|
* @param step The step to add to the workflow
|
|
8424
8336
|
* @returns The workflow instance for chaining
|
|
8337
|
+
*
|
|
8338
|
+
* The step's inputSchema must be satisfied by the previous step's output (or workflow input for first step).
|
|
8339
|
+
* This means: TPrevSchema must be assignable to TStepInput
|
|
8425
8340
|
*/
|
|
8426
8341
|
then(step) {
|
|
8427
8342
|
this.stepFlow.push({ type: "step", step });
|
|
@@ -8444,7 +8359,7 @@ var Workflow = class extends MastraBase {
|
|
|
8444
8359
|
* @returns The workflow instance for chaining
|
|
8445
8360
|
*/
|
|
8446
8361
|
sleep(duration) {
|
|
8447
|
-
const id = `sleep_${this.#mastra?.generateId() || randomUUID()}`;
|
|
8362
|
+
const id = `sleep_${this.#mastra?.generateId({ idType: "step", source: "workflow", entityId: this.id, stepType: "sleep" }) || randomUUID()}`;
|
|
8448
8363
|
const opts = typeof duration === "function" ? { type: "sleep", id, fn: duration } : { type: "sleep", id, duration };
|
|
8449
8364
|
const serializedOpts = typeof duration === "function" ? { type: "sleep", id, fn: duration.toString() } : { type: "sleep", id, duration };
|
|
8450
8365
|
this.stepFlow.push(opts);
|
|
@@ -8465,7 +8380,7 @@ var Workflow = class extends MastraBase {
|
|
|
8465
8380
|
* @returns The workflow instance for chaining
|
|
8466
8381
|
*/
|
|
8467
8382
|
sleepUntil(date) {
|
|
8468
|
-
const id = `sleep_${this.#mastra?.generateId() || randomUUID()}`;
|
|
8383
|
+
const id = `sleep_${this.#mastra?.generateId({ idType: "step", source: "workflow", entityId: this.id, stepType: "sleep-until" }) || randomUUID()}`;
|
|
8469
8384
|
const opts = typeof date === "function" ? { type: "sleepUntil", id, fn: date } : { type: "sleepUntil", id, date };
|
|
8470
8385
|
const serializedOpts = typeof date === "function" ? { type: "sleepUntil", id, fn: date.toString() } : { type: "sleepUntil", id, date };
|
|
8471
8386
|
this.stepFlow.push(opts);
|
|
@@ -8494,7 +8409,7 @@ var Workflow = class extends MastraBase {
|
|
|
8494
8409
|
map(mappingConfig, stepOptions) {
|
|
8495
8410
|
if (typeof mappingConfig === "function") {
|
|
8496
8411
|
const mappingStep2 = createStep({
|
|
8497
|
-
id: stepOptions?.id || `mapping_${this.#mastra?.generateId() || randomUUID()}`,
|
|
8412
|
+
id: stepOptions?.id || `mapping_${this.#mastra?.generateId({ idType: "step", source: "workflow", entityId: this.id, stepType: "mapping" }) || randomUUID()}`,
|
|
8498
8413
|
inputSchema: z.any(),
|
|
8499
8414
|
outputSchema: z.any(),
|
|
8500
8415
|
execute: mappingConfig
|
|
@@ -8532,7 +8447,7 @@ var Workflow = class extends MastraBase {
|
|
|
8532
8447
|
{}
|
|
8533
8448
|
);
|
|
8534
8449
|
const mappingStep = createStep({
|
|
8535
|
-
id: stepOptions?.id || `mapping_${this.#mastra?.generateId() || randomUUID()}`,
|
|
8450
|
+
id: stepOptions?.id || `mapping_${this.#mastra?.generateId({ idType: "step", source: "workflow", entityId: this.id, stepType: "mapping" }) || randomUUID()}`,
|
|
8536
8451
|
inputSchema: z.any(),
|
|
8537
8452
|
outputSchema: z.any(),
|
|
8538
8453
|
execute: async (ctx) => {
|
|
@@ -8747,7 +8662,12 @@ var Workflow = class extends MastraBase {
|
|
|
8747
8662
|
if (!this.executionGraph.steps) {
|
|
8748
8663
|
throw new Error("Uncommitted step flow changes detected. Call .commit() to register the steps.");
|
|
8749
8664
|
}
|
|
8750
|
-
const runIdToUse = options?.runId || this.#mastra?.generateId(
|
|
8665
|
+
const runIdToUse = options?.runId || this.#mastra?.generateId({
|
|
8666
|
+
idType: "run",
|
|
8667
|
+
source: "workflow",
|
|
8668
|
+
entityId: this.id,
|
|
8669
|
+
resourceId: options?.resourceId
|
|
8670
|
+
}) || randomUUID();
|
|
8751
8671
|
const run = this.#runs.get(runIdToUse) ?? new Run({
|
|
8752
8672
|
workflowId: this.id,
|
|
8753
8673
|
stateSchema: this.stateSchema,
|
|
@@ -8788,6 +8708,7 @@ var Workflow = class extends MastraBase {
|
|
|
8788
8708
|
runId: runIdToUse,
|
|
8789
8709
|
status: "pending",
|
|
8790
8710
|
value: {},
|
|
8711
|
+
// @ts-ignore
|
|
8791
8712
|
context: this.#nestedWorkflowInput ? { input: this.#nestedWorkflowInput } : {},
|
|
8792
8713
|
activePaths: [],
|
|
8793
8714
|
activeStepsPath: {},
|
|
@@ -9263,13 +9184,11 @@ var Run = class {
|
|
|
9263
9184
|
}
|
|
9264
9185
|
async _validateInput(inputData) {
|
|
9265
9186
|
let inputDataToUse = inputData;
|
|
9266
|
-
if (this.validateInputs && this.inputSchema) {
|
|
9187
|
+
if (this.validateInputs && this.inputSchema && isZodType(this.inputSchema)) {
|
|
9267
9188
|
const validatedInputData = await this.inputSchema.safeParseAsync(inputData);
|
|
9268
9189
|
if (!validatedInputData.success) {
|
|
9269
9190
|
const errors = getZodErrors(validatedInputData.error);
|
|
9270
|
-
throw new Error(
|
|
9271
|
-
"Invalid input data: \n" + errors.map((e) => `- ${e.path?.join(".")}: ${e.message}`).join("\n")
|
|
9272
|
-
);
|
|
9191
|
+
throw new Error("Invalid input data: \n" + errors.map((e) => `- ${e.path?.join(".")}: ${e.message}`).join("\n"));
|
|
9273
9192
|
}
|
|
9274
9193
|
inputDataToUse = validatedInputData.data;
|
|
9275
9194
|
}
|
|
@@ -9279,7 +9198,7 @@ var Run = class {
|
|
|
9279
9198
|
let initialStateToUse = initialState;
|
|
9280
9199
|
if (this.validateInputs) {
|
|
9281
9200
|
let stateSchema = this.stateSchema;
|
|
9282
|
-
if (stateSchema) {
|
|
9201
|
+
if (stateSchema && isZodType(stateSchema)) {
|
|
9283
9202
|
const validatedInitialState = await stateSchema.safeParseAsync(initialState);
|
|
9284
9203
|
if (!validatedInitialState.success) {
|
|
9285
9204
|
const errors = getZodErrors(validatedInitialState.error);
|
|
@@ -9294,14 +9213,12 @@ var Run = class {
|
|
|
9294
9213
|
}
|
|
9295
9214
|
async _validateResumeData(resumeData, suspendedStep) {
|
|
9296
9215
|
let resumeDataToUse = resumeData;
|
|
9297
|
-
if (suspendedStep && suspendedStep.resumeSchema && this.validateInputs) {
|
|
9216
|
+
if (suspendedStep && suspendedStep.resumeSchema && this.validateInputs && isZodType(suspendedStep.resumeSchema)) {
|
|
9298
9217
|
const resumeSchema = suspendedStep.resumeSchema;
|
|
9299
9218
|
const validatedResumeData = await resumeSchema.safeParseAsync(resumeData);
|
|
9300
9219
|
if (!validatedResumeData.success) {
|
|
9301
9220
|
const errors = getZodErrors(validatedResumeData.error);
|
|
9302
|
-
throw new Error(
|
|
9303
|
-
"Invalid resume data: \n" + errors.map((e) => `- ${e.path?.join(".")}: ${e.message}`).join("\n")
|
|
9304
|
-
);
|
|
9221
|
+
throw new Error("Invalid resume data: \n" + errors.map((e) => `- ${e.path?.join(".")}: ${e.message}`).join("\n"));
|
|
9305
9222
|
}
|
|
9306
9223
|
resumeDataToUse = validatedResumeData.data;
|
|
9307
9224
|
}
|
|
@@ -9309,7 +9226,7 @@ var Run = class {
|
|
|
9309
9226
|
}
|
|
9310
9227
|
async _validateTimetravelInputData(inputData, step) {
|
|
9311
9228
|
let inputDataToUse = inputData;
|
|
9312
|
-
if (step && step.inputSchema && this.validateInputs) {
|
|
9229
|
+
if (step && step.inputSchema && this.validateInputs && isZodType(step.inputSchema)) {
|
|
9313
9230
|
const inputSchema = step.inputSchema;
|
|
9314
9231
|
const validatedInputData = await inputSchema.safeParseAsync(inputData);
|
|
9315
9232
|
if (!validatedInputData.success) {
|
|
@@ -9518,13 +9435,6 @@ var Run = class {
|
|
|
9518
9435
|
}
|
|
9519
9436
|
return this.streamOutput.fullStream;
|
|
9520
9437
|
}
|
|
9521
|
-
async streamAsync({
|
|
9522
|
-
inputData,
|
|
9523
|
-
requestContext,
|
|
9524
|
-
perStep
|
|
9525
|
-
} = {}) {
|
|
9526
|
-
return this.stream({ inputData, requestContext, perStep });
|
|
9527
|
-
}
|
|
9528
9438
|
/**
|
|
9529
9439
|
* Starts the workflow execution with the provided input as a stream
|
|
9530
9440
|
* @param input The input data for the workflow
|
|
@@ -9539,7 +9449,7 @@ var Run = class {
|
|
|
9539
9449
|
initialState,
|
|
9540
9450
|
outputOptions,
|
|
9541
9451
|
perStep
|
|
9542
|
-
}
|
|
9452
|
+
}) {
|
|
9543
9453
|
if (this.closeStreamAction && this.streamOutput) {
|
|
9544
9454
|
return this.streamOutput;
|
|
9545
9455
|
}
|
|
@@ -10177,9 +10087,9 @@ var Run = class {
|
|
|
10177
10087
|
}
|
|
10178
10088
|
};
|
|
10179
10089
|
var languageModelUsageSchema = z10.object({
|
|
10180
|
-
inputTokens: z10.number(),
|
|
10181
|
-
outputTokens: z10.number(),
|
|
10182
|
-
totalTokens: z10.number(),
|
|
10090
|
+
inputTokens: z10.number().optional(),
|
|
10091
|
+
outputTokens: z10.number().optional(),
|
|
10092
|
+
totalTokens: z10.number().optional(),
|
|
10183
10093
|
reasoningTokens: z10.number().optional(),
|
|
10184
10094
|
cachedInputTokens: z10.number().optional()
|
|
10185
10095
|
});
|
|
@@ -11263,7 +11173,7 @@ Analyse the suspended tools: ${JSON.stringify(suspendedTools)}, using the messag
|
|
|
11263
11173
|
output: {
|
|
11264
11174
|
text: text2,
|
|
11265
11175
|
toolCalls: [],
|
|
11266
|
-
usage: usage2 ?? inputData.output
|
|
11176
|
+
usage: usage2 ?? inputData.output.usage,
|
|
11267
11177
|
steps: []
|
|
11268
11178
|
},
|
|
11269
11179
|
messages: {
|
|
@@ -11423,7 +11333,6 @@ Analyse the suspended tools: ${JSON.stringify(suspendedTools)}, using the messag
|
|
|
11423
11333
|
text,
|
|
11424
11334
|
toolCalls: shouldRetry ? [] : toolCalls,
|
|
11425
11335
|
// Clear tool calls on retry
|
|
11426
|
-
tools: stepTools,
|
|
11427
11336
|
usage: usage ?? inputData.output?.usage,
|
|
11428
11337
|
steps,
|
|
11429
11338
|
...object ? { object } : {}
|
|
@@ -11799,11 +11708,15 @@ function createToolCallStep({
|
|
|
11799
11708
|
toolCallId: inputData.toolCallId,
|
|
11800
11709
|
toolName: inputData.toolName,
|
|
11801
11710
|
args: inputData.args,
|
|
11802
|
-
resumeSchema:
|
|
11803
|
-
|
|
11804
|
-
|
|
11711
|
+
resumeSchema: JSON.stringify(
|
|
11712
|
+
zodToJsonSchema$1(
|
|
11713
|
+
z10.object({
|
|
11714
|
+
approved: z10.boolean().describe(
|
|
11715
|
+
"Controls if the tool call is approved or not, should be true when approved and false when declined"
|
|
11716
|
+
)
|
|
11717
|
+
})
|
|
11805
11718
|
)
|
|
11806
|
-
|
|
11719
|
+
)
|
|
11807
11720
|
}
|
|
11808
11721
|
});
|
|
11809
11722
|
addToolMetadata({
|
|
@@ -11811,11 +11724,15 @@ function createToolCallStep({
|
|
|
11811
11724
|
toolName: inputData.toolName,
|
|
11812
11725
|
args: inputData.args,
|
|
11813
11726
|
type: "approval",
|
|
11814
|
-
resumeSchema:
|
|
11815
|
-
|
|
11816
|
-
|
|
11727
|
+
resumeSchema: JSON.stringify(
|
|
11728
|
+
zodToJsonSchema$1(
|
|
11729
|
+
z10.object({
|
|
11730
|
+
approved: z10.boolean().describe(
|
|
11731
|
+
"Controls if the tool call is approved or not, should be true when approved and false when declined"
|
|
11732
|
+
)
|
|
11733
|
+
})
|
|
11817
11734
|
)
|
|
11818
|
-
|
|
11735
|
+
)
|
|
11819
11736
|
});
|
|
11820
11737
|
await flushMessagesBeforeSuspension();
|
|
11821
11738
|
return suspend(
|
|
@@ -11912,7 +11829,11 @@ function createToolCallStep({
|
|
|
11912
11829
|
}
|
|
11913
11830
|
|
|
11914
11831
|
// src/loop/workflows/agentic-execution/index.ts
|
|
11915
|
-
function createAgenticExecutionWorkflow({
|
|
11832
|
+
function createAgenticExecutionWorkflow({
|
|
11833
|
+
models,
|
|
11834
|
+
_internal,
|
|
11835
|
+
...rest
|
|
11836
|
+
}) {
|
|
11916
11837
|
const llmExecutionStep = createLLMExecutionStep({
|
|
11917
11838
|
models,
|
|
11918
11839
|
_internal,
|
|
@@ -12278,7 +12199,13 @@ function loop({
|
|
|
12278
12199
|
const firstModel = models[0];
|
|
12279
12200
|
let runIdToUse = runId;
|
|
12280
12201
|
if (!runIdToUse) {
|
|
12281
|
-
runIdToUse = idGenerator?.(
|
|
12202
|
+
runIdToUse = idGenerator?.({
|
|
12203
|
+
idType: "run",
|
|
12204
|
+
source: "agent",
|
|
12205
|
+
entityId: agentId,
|
|
12206
|
+
threadId: _internal?.threadId,
|
|
12207
|
+
resourceId: _internal?.resourceId
|
|
12208
|
+
}) || crypto.randomUUID();
|
|
12282
12209
|
}
|
|
12283
12210
|
const internalToUse = {
|
|
12284
12211
|
now: _internal?.now || (() => Date.now()),
|
|
@@ -12873,6 +12800,8 @@ Primitives already executed: ${completedPrimitives.join(", ")}` : "";
|
|
|
12873
12800
|
|
|
12874
12801
|
If no primitive (type = 'none'), the task is complete because we can't run any primitive to further task completion.
|
|
12875
12802
|
|
|
12803
|
+
Also, if the ${context.selectedPrimitive.type} ${context.selectedPrimitive.id} has declined the tool call in its response, then the task is complete as the primitive tool-call was declined by the user.
|
|
12804
|
+
|
|
12876
12805
|
IMPORTANT: If the above result is from an AGENT PRIMITIVE and it is a suitable final result itself considering the original task, then finalResult should be an empty string or undefined.
|
|
12877
12806
|
|
|
12878
12807
|
If the task is complete and the result is not from an AGENT PRIMITIVE, always generate a finalResult.
|
|
@@ -13360,6 +13289,26 @@ var MastraLLMVNext = class extends MastraBase {
|
|
|
13360
13289
|
var PRIMITIVE_TYPES = z10.enum(["agent", "workflow", "none", "tool"]);
|
|
13361
13290
|
|
|
13362
13291
|
// src/loop/network/index.ts
|
|
13292
|
+
function filterMessagesForSubAgent(messages) {
|
|
13293
|
+
return messages.filter((msg) => {
|
|
13294
|
+
if (msg.role === "user") return true;
|
|
13295
|
+
if (msg.role === "assistant") {
|
|
13296
|
+
const parts = msg.content?.parts ?? [];
|
|
13297
|
+
for (const part of parts) {
|
|
13298
|
+
if (part?.type === "text" && part?.text) {
|
|
13299
|
+
try {
|
|
13300
|
+
const parsed = JSON.parse(part.text);
|
|
13301
|
+
if (parsed.isNetwork) return false;
|
|
13302
|
+
if (parsed.primitiveId && parsed.selectionReason) return false;
|
|
13303
|
+
} catch {
|
|
13304
|
+
}
|
|
13305
|
+
}
|
|
13306
|
+
}
|
|
13307
|
+
return true;
|
|
13308
|
+
}
|
|
13309
|
+
return false;
|
|
13310
|
+
});
|
|
13311
|
+
}
|
|
13363
13312
|
async function getRoutingAgent({
|
|
13364
13313
|
requestContext,
|
|
13365
13314
|
agent,
|
|
@@ -13376,13 +13325,13 @@ async function getRoutingAgent({
|
|
|
13376
13325
|
}).join("\n");
|
|
13377
13326
|
const workflowList = Object.entries(workflowsToUse).map(([name, workflow]) => {
|
|
13378
13327
|
return ` - **${name}**: ${workflow.description}, input schema: ${JSON.stringify(
|
|
13379
|
-
zodToJsonSchema
|
|
13328
|
+
zodToJsonSchema(workflow.inputSchema)
|
|
13380
13329
|
)}`;
|
|
13381
13330
|
}).join("\n");
|
|
13382
13331
|
const memoryTools = await memoryToUse?.listTools?.();
|
|
13383
13332
|
const toolList = Object.entries({ ...toolsToUse, ...memoryTools }).map(([name, tool2]) => {
|
|
13384
13333
|
return ` - **${name}**: ${tool2.description}, input schema: ${JSON.stringify(
|
|
13385
|
-
zodToJsonSchema
|
|
13334
|
+
zodToJsonSchema("inputSchema" in tool2 ? tool2.inputSchema : z10.object({}))
|
|
13386
13335
|
)}`;
|
|
13387
13336
|
}).join("\n");
|
|
13388
13337
|
const additionalInstructionsSection = routingConfig?.additionalInstructions ? `
|
|
@@ -13479,7 +13428,13 @@ async function prepareMemoryStep({
|
|
|
13479
13428
|
memory.saveMessages({
|
|
13480
13429
|
messages: [
|
|
13481
13430
|
{
|
|
13482
|
-
id: generateId2(
|
|
13431
|
+
id: generateId2({
|
|
13432
|
+
idType: "message",
|
|
13433
|
+
source: "agent",
|
|
13434
|
+
threadId: thread?.id,
|
|
13435
|
+
resourceId: thread?.resourceId,
|
|
13436
|
+
role: "user"
|
|
13437
|
+
}),
|
|
13483
13438
|
type: "text",
|
|
13484
13439
|
role: "user",
|
|
13485
13440
|
content: { parts: [{ type: "text", text: messages }], format: 2 },
|
|
@@ -13509,7 +13464,7 @@ async function prepareMemoryStep({
|
|
|
13509
13464
|
const mostRecentUserMessage = routingAgent.getMostRecentUserMessage(uiMessages);
|
|
13510
13465
|
userMessage = mostRecentUserMessage?.content;
|
|
13511
13466
|
}
|
|
13512
|
-
if (thread
|
|
13467
|
+
if (thread && memory) {
|
|
13513
13468
|
const config = memory.getMergedThreadConfig(memoryConfig || {});
|
|
13514
13469
|
const {
|
|
13515
13470
|
shouldGenerate,
|
|
@@ -13517,25 +13472,33 @@ async function prepareMemoryStep({
|
|
|
13517
13472
|
instructions: titleInstructions
|
|
13518
13473
|
} = routingAgent.resolveTitleGenerationConfig(config?.generateTitle);
|
|
13519
13474
|
if (shouldGenerate && userMessage) {
|
|
13520
|
-
|
|
13521
|
-
|
|
13522
|
-
|
|
13523
|
-
|
|
13524
|
-
|
|
13525
|
-
|
|
13526
|
-
|
|
13527
|
-
|
|
13528
|
-
|
|
13529
|
-
|
|
13530
|
-
|
|
13531
|
-
|
|
13532
|
-
|
|
13533
|
-
|
|
13534
|
-
|
|
13535
|
-
|
|
13536
|
-
|
|
13537
|
-
|
|
13538
|
-
|
|
13475
|
+
const existingMessages = await memory.recall({
|
|
13476
|
+
threadId: thread.id,
|
|
13477
|
+
resourceId: thread.resourceId
|
|
13478
|
+
});
|
|
13479
|
+
const existingUserMessages = existingMessages.messages.filter((m) => m.role === "user");
|
|
13480
|
+
const isFirstUserMessage = existingUserMessages.length === 0;
|
|
13481
|
+
if (isFirstUserMessage) {
|
|
13482
|
+
promises.push(
|
|
13483
|
+
routingAgent.genTitle(
|
|
13484
|
+
userMessage,
|
|
13485
|
+
requestContext,
|
|
13486
|
+
tracingContext || { currentSpan: void 0 },
|
|
13487
|
+
titleModel,
|
|
13488
|
+
titleInstructions
|
|
13489
|
+
).then((title) => {
|
|
13490
|
+
if (title) {
|
|
13491
|
+
return memory.createThread({
|
|
13492
|
+
threadId: thread.id,
|
|
13493
|
+
resourceId: thread.resourceId,
|
|
13494
|
+
memoryConfig,
|
|
13495
|
+
title,
|
|
13496
|
+
metadata: thread.metadata
|
|
13497
|
+
});
|
|
13498
|
+
}
|
|
13499
|
+
})
|
|
13500
|
+
);
|
|
13501
|
+
}
|
|
13539
13502
|
}
|
|
13540
13503
|
}
|
|
13541
13504
|
await Promise.all(promises);
|
|
@@ -13597,13 +13560,18 @@ async function createNetworkLoop({
|
|
|
13597
13560
|
result: z10.string(),
|
|
13598
13561
|
isComplete: z10.boolean().optional(),
|
|
13599
13562
|
selectionReason: z10.string(),
|
|
13600
|
-
iteration: z10.number()
|
|
13563
|
+
iteration: z10.number(),
|
|
13564
|
+
conversationContext: z10.array(z10.any()).optional()
|
|
13601
13565
|
}),
|
|
13602
13566
|
execute: async ({ inputData, getInitData, writer }) => {
|
|
13603
13567
|
const initData = await getInitData();
|
|
13604
13568
|
const routingAgent = await getRoutingAgent({ requestContext, agent, routingConfig: routing });
|
|
13605
13569
|
const iterationCount = (inputData.iteration ?? -1) + 1;
|
|
13606
|
-
const stepId = generateId2(
|
|
13570
|
+
const stepId = generateId2({
|
|
13571
|
+
idType: "step",
|
|
13572
|
+
source: "agent",
|
|
13573
|
+
stepType: "routing-agent"
|
|
13574
|
+
});
|
|
13607
13575
|
await writer.write({
|
|
13608
13576
|
type: "routing-agent-start",
|
|
13609
13577
|
payload: {
|
|
@@ -13676,7 +13644,7 @@ async function createNetworkLoop({
|
|
|
13676
13644
|
...routingAgentOptions
|
|
13677
13645
|
};
|
|
13678
13646
|
const result = await tryGenerateWithJsonFallback(routingAgent, prompt, options);
|
|
13679
|
-
const object = result.object;
|
|
13647
|
+
const object = await result.object;
|
|
13680
13648
|
const isComplete = object.primitiveId === "none" && object.primitiveType === "none";
|
|
13681
13649
|
if (isComplete && object.selectionReason) {
|
|
13682
13650
|
await writer.write({
|
|
@@ -13692,6 +13660,7 @@ async function createNetworkLoop({
|
|
|
13692
13660
|
runId
|
|
13693
13661
|
});
|
|
13694
13662
|
}
|
|
13663
|
+
const conversationContext = filterMessagesForSubAgent(result.rememberedMessages ?? []);
|
|
13695
13664
|
const endPayload = {
|
|
13696
13665
|
task: inputData.task,
|
|
13697
13666
|
result: isComplete ? object.selectionReason : "",
|
|
@@ -13701,7 +13670,8 @@ async function createNetworkLoop({
|
|
|
13701
13670
|
isComplete,
|
|
13702
13671
|
selectionReason: object.selectionReason,
|
|
13703
13672
|
iteration: iterationCount,
|
|
13704
|
-
runId: stepId
|
|
13673
|
+
runId: stepId,
|
|
13674
|
+
conversationContext
|
|
13705
13675
|
};
|
|
13706
13676
|
await writer.write({
|
|
13707
13677
|
type: "routing-agent-end",
|
|
@@ -13725,7 +13695,8 @@ async function createNetworkLoop({
|
|
|
13725
13695
|
result: z10.string(),
|
|
13726
13696
|
isComplete: z10.boolean().optional(),
|
|
13727
13697
|
selectionReason: z10.string(),
|
|
13728
|
-
iteration: z10.number()
|
|
13698
|
+
iteration: z10.number(),
|
|
13699
|
+
conversationContext: z10.array(z10.any()).optional()
|
|
13729
13700
|
}),
|
|
13730
13701
|
outputSchema: z10.object({
|
|
13731
13702
|
task: z10.string(),
|
|
@@ -13735,7 +13706,7 @@ async function createNetworkLoop({
|
|
|
13735
13706
|
isComplete: z10.boolean().optional(),
|
|
13736
13707
|
iteration: z10.number()
|
|
13737
13708
|
}),
|
|
13738
|
-
execute: async ({ inputData, writer, getInitData }) => {
|
|
13709
|
+
execute: async ({ inputData, writer, getInitData, suspend, resumeData }) => {
|
|
13739
13710
|
const agentsMap = await agent.listAgents({ requestContext });
|
|
13740
13711
|
const agentForStep = agentsMap[inputData.primitiveId];
|
|
13741
13712
|
if (!agentForStep) {
|
|
@@ -13748,7 +13719,12 @@ async function createNetworkLoop({
|
|
|
13748
13719
|
throw mastraError;
|
|
13749
13720
|
}
|
|
13750
13721
|
const agentId = agentForStep.id;
|
|
13751
|
-
const stepId = generateId2(
|
|
13722
|
+
const stepId = generateId2({
|
|
13723
|
+
idType: "step",
|
|
13724
|
+
source: "agent",
|
|
13725
|
+
entityId: agentId,
|
|
13726
|
+
stepType: "agent-execution"
|
|
13727
|
+
});
|
|
13752
13728
|
await writer.write({
|
|
13753
13729
|
type: "agent-execution-start",
|
|
13754
13730
|
payload: {
|
|
@@ -13762,17 +13738,35 @@ async function createNetworkLoop({
|
|
|
13762
13738
|
const initData = await getInitData();
|
|
13763
13739
|
const threadId = initData?.threadId || runId;
|
|
13764
13740
|
const resourceId = initData?.threadResourceId || networkName;
|
|
13765
|
-
const
|
|
13766
|
-
const
|
|
13741
|
+
const conversationContext = inputData.conversationContext ?? [];
|
|
13742
|
+
const messagesForSubAgent = [
|
|
13743
|
+
...conversationContext,
|
|
13744
|
+
{ role: "user", content: inputData.prompt }
|
|
13745
|
+
];
|
|
13746
|
+
const result = await (resumeData ? agentForStep.resumeStream(resumeData, {
|
|
13747
|
+
requestContext,
|
|
13748
|
+
runId,
|
|
13749
|
+
memory: {
|
|
13750
|
+
thread: threadId,
|
|
13751
|
+
resource: resourceId,
|
|
13752
|
+
options: {
|
|
13753
|
+
lastMessages: 0
|
|
13754
|
+
}
|
|
13755
|
+
}
|
|
13756
|
+
}) : agentForStep.stream(messagesForSubAgent, {
|
|
13767
13757
|
requestContext,
|
|
13768
13758
|
runId,
|
|
13769
|
-
|
|
13770
|
-
|
|
13771
|
-
|
|
13772
|
-
|
|
13759
|
+
memory: {
|
|
13760
|
+
thread: threadId,
|
|
13761
|
+
resource: resourceId,
|
|
13762
|
+
options: {
|
|
13763
|
+
lastMessages: 0
|
|
13773
13764
|
}
|
|
13774
|
-
}
|
|
13775
|
-
});
|
|
13765
|
+
}
|
|
13766
|
+
}));
|
|
13767
|
+
let requireApprovalMetadata;
|
|
13768
|
+
let suspendedTools;
|
|
13769
|
+
let toolCallDeclined = false;
|
|
13776
13770
|
for await (const chunk of result.fullStream) {
|
|
13777
13771
|
await writer.write({
|
|
13778
13772
|
type: `agent-execution-event-${chunk.type}`,
|
|
@@ -13783,13 +13777,60 @@ async function createNetworkLoop({
|
|
|
13783
13777
|
from: "NETWORK" /* NETWORK */,
|
|
13784
13778
|
runId
|
|
13785
13779
|
});
|
|
13780
|
+
if (chunk.type === "tool-call-approval") {
|
|
13781
|
+
requireApprovalMetadata = {
|
|
13782
|
+
...requireApprovalMetadata ?? {},
|
|
13783
|
+
[inputData.primitiveId]: {
|
|
13784
|
+
resumeSchema: chunk.payload.resumeSchema,
|
|
13785
|
+
args: { prompt: inputData.prompt },
|
|
13786
|
+
toolName: inputData.primitiveId,
|
|
13787
|
+
toolCallId: inputData.primitiveId,
|
|
13788
|
+
runId,
|
|
13789
|
+
type: "approval",
|
|
13790
|
+
primitiveType: "agent",
|
|
13791
|
+
primitiveId: inputData.primitiveId
|
|
13792
|
+
}
|
|
13793
|
+
};
|
|
13794
|
+
}
|
|
13795
|
+
if (chunk.type === "tool-call-suspended") {
|
|
13796
|
+
suspendedTools = {
|
|
13797
|
+
...suspendedTools ?? {},
|
|
13798
|
+
[inputData.primitiveId]: {
|
|
13799
|
+
suspendPayload: chunk.payload.suspendPayload,
|
|
13800
|
+
resumeSchema: chunk.payload.resumeSchema,
|
|
13801
|
+
toolName: inputData.primitiveId,
|
|
13802
|
+
toolCallId: inputData.primitiveId,
|
|
13803
|
+
args: { prompt: inputData.prompt },
|
|
13804
|
+
runId,
|
|
13805
|
+
type: "suspension",
|
|
13806
|
+
primitiveType: "agent",
|
|
13807
|
+
primitiveId: inputData.primitiveId
|
|
13808
|
+
}
|
|
13809
|
+
};
|
|
13810
|
+
}
|
|
13811
|
+
if (chunk.type === "tool-result") {
|
|
13812
|
+
if (chunk.payload.result === "Tool call was not approved by the user") {
|
|
13813
|
+
toolCallDeclined = true;
|
|
13814
|
+
}
|
|
13815
|
+
}
|
|
13786
13816
|
}
|
|
13787
13817
|
const memory = await agent.getMemory({ requestContext });
|
|
13788
13818
|
const messages = result.messageList.get.all.v1();
|
|
13819
|
+
let finalText = await result.text;
|
|
13820
|
+
if (toolCallDeclined) {
|
|
13821
|
+
finalText = finalText + "\n\nTool call was not approved by the user";
|
|
13822
|
+
}
|
|
13789
13823
|
await memory?.saveMessages({
|
|
13790
13824
|
messages: [
|
|
13791
13825
|
{
|
|
13792
|
-
id: generateId2(
|
|
13826
|
+
id: generateId2({
|
|
13827
|
+
idType: "message",
|
|
13828
|
+
source: "agent",
|
|
13829
|
+
entityId: agentId,
|
|
13830
|
+
threadId: initData?.threadId || runId,
|
|
13831
|
+
resourceId: initData?.threadResourceId || networkName,
|
|
13832
|
+
role: "assistant"
|
|
13833
|
+
}),
|
|
13793
13834
|
type: "text",
|
|
13794
13835
|
role: "assistant",
|
|
13795
13836
|
content: {
|
|
@@ -13802,11 +13843,17 @@ async function createNetworkLoop({
|
|
|
13802
13843
|
primitiveType: inputData.primitiveType,
|
|
13803
13844
|
primitiveId: inputData.primitiveId,
|
|
13804
13845
|
input: inputData.prompt,
|
|
13805
|
-
finalResult: { text:
|
|
13846
|
+
finalResult: { text: finalText, messages }
|
|
13806
13847
|
})
|
|
13807
13848
|
}
|
|
13808
13849
|
],
|
|
13809
|
-
format: 2
|
|
13850
|
+
format: 2,
|
|
13851
|
+
...requireApprovalMetadata || suspendedTools ? {
|
|
13852
|
+
metadata: {
|
|
13853
|
+
...requireApprovalMetadata ? { requireApprovalMetadata } : {},
|
|
13854
|
+
...suspendedTools ? { suspendedTools } : {}
|
|
13855
|
+
}
|
|
13856
|
+
} : {}
|
|
13810
13857
|
},
|
|
13811
13858
|
createdAt: /* @__PURE__ */ new Date(),
|
|
13812
13859
|
threadId: initData?.threadId || runId,
|
|
@@ -13814,31 +13861,64 @@ async function createNetworkLoop({
|
|
|
13814
13861
|
}
|
|
13815
13862
|
]
|
|
13816
13863
|
});
|
|
13817
|
-
|
|
13818
|
-
|
|
13819
|
-
|
|
13820
|
-
|
|
13821
|
-
|
|
13822
|
-
|
|
13823
|
-
|
|
13824
|
-
|
|
13825
|
-
|
|
13826
|
-
|
|
13827
|
-
|
|
13828
|
-
|
|
13829
|
-
|
|
13830
|
-
|
|
13831
|
-
|
|
13832
|
-
|
|
13833
|
-
|
|
13834
|
-
|
|
13835
|
-
|
|
13836
|
-
|
|
13837
|
-
|
|
13838
|
-
|
|
13839
|
-
|
|
13840
|
-
|
|
13841
|
-
|
|
13864
|
+
if (requireApprovalMetadata || suspendedTools) {
|
|
13865
|
+
await writer.write({
|
|
13866
|
+
type: requireApprovalMetadata ? "agent-execution-approval" : "agent-execution-suspended",
|
|
13867
|
+
payload: {
|
|
13868
|
+
args: { prompt: inputData.prompt },
|
|
13869
|
+
agentId,
|
|
13870
|
+
runId: stepId,
|
|
13871
|
+
toolName: inputData.primitiveId,
|
|
13872
|
+
toolCallId: inputData.primitiveId,
|
|
13873
|
+
usage: await result.usage,
|
|
13874
|
+
selectionReason: inputData.selectionReason,
|
|
13875
|
+
...requireApprovalMetadata ? {
|
|
13876
|
+
resumeSchema: requireApprovalMetadata[inputData.primitiveId].resumeSchema
|
|
13877
|
+
} : {},
|
|
13878
|
+
...suspendedTools ? {
|
|
13879
|
+
resumeSchema: suspendedTools[inputData.primitiveId].resumeSchema,
|
|
13880
|
+
suspendPayload: suspendedTools[inputData.primitiveId].suspendPayload
|
|
13881
|
+
} : {}
|
|
13882
|
+
},
|
|
13883
|
+
from: "NETWORK" /* NETWORK */,
|
|
13884
|
+
runId
|
|
13885
|
+
});
|
|
13886
|
+
return await suspend({
|
|
13887
|
+
...requireApprovalMetadata ? { requireToolApproval: requireApprovalMetadata[inputData.primitiveId] } : {},
|
|
13888
|
+
...suspendedTools ? {
|
|
13889
|
+
toolCallSuspended: suspendedTools[inputData.primitiveId].suspendPayload,
|
|
13890
|
+
args: inputData.prompt,
|
|
13891
|
+
agentId
|
|
13892
|
+
} : {},
|
|
13893
|
+
runId: stepId
|
|
13894
|
+
});
|
|
13895
|
+
} else {
|
|
13896
|
+
const endPayload = {
|
|
13897
|
+
task: inputData.task,
|
|
13898
|
+
agentId,
|
|
13899
|
+
result: finalText,
|
|
13900
|
+
isComplete: false,
|
|
13901
|
+
iteration: inputData.iteration,
|
|
13902
|
+
runId: stepId
|
|
13903
|
+
};
|
|
13904
|
+
await writer.write({
|
|
13905
|
+
type: "agent-execution-end",
|
|
13906
|
+
payload: {
|
|
13907
|
+
...endPayload,
|
|
13908
|
+
usage: await result.usage
|
|
13909
|
+
},
|
|
13910
|
+
from: "NETWORK" /* NETWORK */,
|
|
13911
|
+
runId
|
|
13912
|
+
});
|
|
13913
|
+
return {
|
|
13914
|
+
task: inputData.task,
|
|
13915
|
+
primitiveId: inputData.primitiveId,
|
|
13916
|
+
primitiveType: inputData.primitiveType,
|
|
13917
|
+
result: finalText,
|
|
13918
|
+
isComplete: false,
|
|
13919
|
+
iteration: inputData.iteration
|
|
13920
|
+
};
|
|
13921
|
+
}
|
|
13842
13922
|
}
|
|
13843
13923
|
});
|
|
13844
13924
|
const workflowStep = createStep({
|
|
@@ -13851,7 +13931,8 @@ async function createNetworkLoop({
|
|
|
13851
13931
|
result: z10.string(),
|
|
13852
13932
|
isComplete: z10.boolean().optional(),
|
|
13853
13933
|
selectionReason: z10.string(),
|
|
13854
|
-
iteration: z10.number()
|
|
13934
|
+
iteration: z10.number(),
|
|
13935
|
+
conversationContext: z10.array(z10.any()).optional()
|
|
13855
13936
|
}),
|
|
13856
13937
|
outputSchema: z10.object({
|
|
13857
13938
|
task: z10.string(),
|
|
@@ -13861,7 +13942,7 @@ async function createNetworkLoop({
|
|
|
13861
13942
|
isComplete: z10.boolean().optional(),
|
|
13862
13943
|
iteration: z10.number()
|
|
13863
13944
|
}),
|
|
13864
|
-
execute: async ({ inputData, writer, getInitData }) => {
|
|
13945
|
+
execute: async ({ inputData, writer, getInitData, suspend, resumeData, mastra }) => {
|
|
13865
13946
|
const workflowsMap = await agent.listWorkflows({ requestContext });
|
|
13866
13947
|
const workflowId = inputData.primitiveId;
|
|
13867
13948
|
const wf = workflowsMap[workflowId];
|
|
@@ -13889,7 +13970,12 @@ async function createNetworkLoop({
|
|
|
13889
13970
|
);
|
|
13890
13971
|
throw mastraError;
|
|
13891
13972
|
}
|
|
13892
|
-
const stepId = generateId2(
|
|
13973
|
+
const stepId = generateId2({
|
|
13974
|
+
idType: "step",
|
|
13975
|
+
source: "workflow",
|
|
13976
|
+
entityId: wf.id,
|
|
13977
|
+
stepType: "workflow-execution"
|
|
13978
|
+
});
|
|
13893
13979
|
const run = await wf.createRun({ runId });
|
|
13894
13980
|
const toolData = {
|
|
13895
13981
|
workflowId: wf.id,
|
|
@@ -13902,7 +13988,10 @@ async function createNetworkLoop({
|
|
|
13902
13988
|
from: "NETWORK" /* NETWORK */,
|
|
13903
13989
|
runId
|
|
13904
13990
|
});
|
|
13905
|
-
const stream = run.
|
|
13991
|
+
const stream = resumeData ? run.resumeStream({
|
|
13992
|
+
resumeData,
|
|
13993
|
+
requestContext
|
|
13994
|
+
}) : run.stream({
|
|
13906
13995
|
inputData: input,
|
|
13907
13996
|
requestContext
|
|
13908
13997
|
});
|
|
@@ -13924,6 +14013,33 @@ async function createNetworkLoop({
|
|
|
13924
14013
|
if (!workflowState?.status || workflowState?.status === "failed") {
|
|
13925
14014
|
runSuccess = false;
|
|
13926
14015
|
}
|
|
14016
|
+
let resumeSchema;
|
|
14017
|
+
let suspendPayload;
|
|
14018
|
+
if (workflowState?.status === "suspended") {
|
|
14019
|
+
const suspendedStep = workflowState?.suspended?.[0]?.[0];
|
|
14020
|
+
suspendPayload = workflowState?.steps?.[suspendedStep]?.suspendPayload;
|
|
14021
|
+
if (suspendPayload?.__workflow_meta) {
|
|
14022
|
+
delete suspendPayload.__workflow_meta;
|
|
14023
|
+
}
|
|
14024
|
+
const firstSuspendedStepPath = [...workflowState?.suspended?.[0] ?? []];
|
|
14025
|
+
let wflowStep = wf;
|
|
14026
|
+
while (firstSuspendedStepPath.length > 0) {
|
|
14027
|
+
const key = firstSuspendedStepPath.shift();
|
|
14028
|
+
if (key) {
|
|
14029
|
+
if (!wflowStep.steps[key]) {
|
|
14030
|
+
mastra?.getLogger()?.warn(`Suspended step '${key}' not found in workflow '${workflowId}'`);
|
|
14031
|
+
break;
|
|
14032
|
+
}
|
|
14033
|
+
wflowStep = wflowStep.steps[key];
|
|
14034
|
+
}
|
|
14035
|
+
}
|
|
14036
|
+
const wflowStepSchema = wflowStep?.resumeSchema;
|
|
14037
|
+
if (wflowStepSchema) {
|
|
14038
|
+
resumeSchema = JSON.stringify(zodToJsonSchema(wflowStepSchema));
|
|
14039
|
+
} else {
|
|
14040
|
+
resumeSchema = "";
|
|
14041
|
+
}
|
|
14042
|
+
}
|
|
13927
14043
|
const finalResult = JSON.stringify({
|
|
13928
14044
|
isNetwork: true,
|
|
13929
14045
|
primitiveType: inputData.primitiveType,
|
|
@@ -13942,37 +14058,86 @@ async function createNetworkLoop({
|
|
|
13942
14058
|
await memory?.saveMessages({
|
|
13943
14059
|
messages: [
|
|
13944
14060
|
{
|
|
13945
|
-
id: generateId2(
|
|
14061
|
+
id: generateId2({
|
|
14062
|
+
idType: "message",
|
|
14063
|
+
source: "workflow",
|
|
14064
|
+
entityId: wf.id,
|
|
14065
|
+
threadId: initData?.threadId || runId,
|
|
14066
|
+
resourceId: initData?.threadResourceId || networkName,
|
|
14067
|
+
role: "assistant"
|
|
14068
|
+
}),
|
|
13946
14069
|
type: "text",
|
|
13947
14070
|
role: "assistant",
|
|
13948
|
-
content: {
|
|
13949
|
-
|
|
13950
|
-
|
|
13951
|
-
|
|
13952
|
-
|
|
13953
|
-
|
|
13954
|
-
|
|
13955
|
-
|
|
13956
|
-
|
|
13957
|
-
|
|
13958
|
-
|
|
13959
|
-
|
|
13960
|
-
|
|
13961
|
-
|
|
13962
|
-
|
|
13963
|
-
|
|
13964
|
-
|
|
13965
|
-
|
|
13966
|
-
|
|
13967
|
-
|
|
13968
|
-
|
|
13969
|
-
|
|
13970
|
-
|
|
13971
|
-
|
|
13972
|
-
|
|
13973
|
-
|
|
14071
|
+
content: {
|
|
14072
|
+
parts: [{ type: "text", text: finalResult }],
|
|
14073
|
+
format: 2,
|
|
14074
|
+
...suspendPayload ? {
|
|
14075
|
+
metadata: {
|
|
14076
|
+
suspendedTools: {
|
|
14077
|
+
[inputData.primitiveId]: {
|
|
14078
|
+
args: input,
|
|
14079
|
+
suspendPayload,
|
|
14080
|
+
runId,
|
|
14081
|
+
type: "suspension",
|
|
14082
|
+
resumeSchema,
|
|
14083
|
+
workflowId,
|
|
14084
|
+
primitiveType: "workflow",
|
|
14085
|
+
primitiveId: inputData.primitiveId,
|
|
14086
|
+
toolName: inputData.primitiveId,
|
|
14087
|
+
toolCallId: inputData.primitiveId
|
|
14088
|
+
}
|
|
14089
|
+
}
|
|
14090
|
+
}
|
|
14091
|
+
} : {}
|
|
14092
|
+
},
|
|
14093
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
14094
|
+
threadId: initData?.threadId || runId,
|
|
14095
|
+
resourceId: initData?.threadResourceId || networkName
|
|
14096
|
+
}
|
|
14097
|
+
]
|
|
13974
14098
|
});
|
|
13975
|
-
|
|
14099
|
+
if (suspendPayload) {
|
|
14100
|
+
await writer?.write({
|
|
14101
|
+
type: "workflow-execution-suspended",
|
|
14102
|
+
payload: {
|
|
14103
|
+
args: input,
|
|
14104
|
+
workflowId,
|
|
14105
|
+
suspendPayload,
|
|
14106
|
+
resumeSchema,
|
|
14107
|
+
name: wf.name,
|
|
14108
|
+
runId: stepId,
|
|
14109
|
+
usage: await stream.usage,
|
|
14110
|
+
selectionReason: inputData.selectionReason,
|
|
14111
|
+
toolName: inputData.primitiveId,
|
|
14112
|
+
toolCallId: inputData.primitiveId
|
|
14113
|
+
},
|
|
14114
|
+
from: "NETWORK" /* NETWORK */,
|
|
14115
|
+
runId
|
|
14116
|
+
});
|
|
14117
|
+
return suspend({ ...toolData, workflowSuspended: suspendPayload });
|
|
14118
|
+
} else {
|
|
14119
|
+
const endPayload = {
|
|
14120
|
+
task: inputData.task,
|
|
14121
|
+
primitiveId: inputData.primitiveId,
|
|
14122
|
+
primitiveType: inputData.primitiveType,
|
|
14123
|
+
result: finalResult,
|
|
14124
|
+
isComplete: false,
|
|
14125
|
+
iteration: inputData.iteration
|
|
14126
|
+
};
|
|
14127
|
+
await writer?.write({
|
|
14128
|
+
type: "workflow-execution-end",
|
|
14129
|
+
payload: {
|
|
14130
|
+
...endPayload,
|
|
14131
|
+
result: workflowState,
|
|
14132
|
+
name: wf.name,
|
|
14133
|
+
runId: stepId,
|
|
14134
|
+
usage: await stream.usage
|
|
14135
|
+
},
|
|
14136
|
+
from: "NETWORK" /* NETWORK */,
|
|
14137
|
+
runId
|
|
14138
|
+
});
|
|
14139
|
+
return endPayload;
|
|
14140
|
+
}
|
|
13976
14141
|
}
|
|
13977
14142
|
});
|
|
13978
14143
|
const toolStep = createStep({
|
|
@@ -13985,7 +14150,8 @@ async function createNetworkLoop({
|
|
|
13985
14150
|
result: z10.string(),
|
|
13986
14151
|
isComplete: z10.boolean().optional(),
|
|
13987
14152
|
selectionReason: z10.string(),
|
|
13988
|
-
iteration: z10.number()
|
|
14153
|
+
iteration: z10.number(),
|
|
14154
|
+
conversationContext: z10.array(z10.any()).optional()
|
|
13989
14155
|
}),
|
|
13990
14156
|
outputSchema: z10.object({
|
|
13991
14157
|
task: z10.string(),
|
|
@@ -13995,8 +14161,12 @@ async function createNetworkLoop({
|
|
|
13995
14161
|
isComplete: z10.boolean().optional(),
|
|
13996
14162
|
iteration: z10.number()
|
|
13997
14163
|
}),
|
|
13998
|
-
|
|
14164
|
+
resumeSchema: z10.object({
|
|
14165
|
+
approved: z10.boolean().describe("Controls if the tool call is approved or not, should be true when approved and false when declined")
|
|
14166
|
+
}),
|
|
14167
|
+
execute: async ({ inputData, getInitData, writer, resumeData, mastra, suspend }) => {
|
|
13999
14168
|
const initData = await getInitData();
|
|
14169
|
+
const logger = mastra?.getLogger();
|
|
14000
14170
|
const agentTools = await agent.listTools({ requestContext });
|
|
14001
14171
|
const memory = await agent.getMemory({ requestContext });
|
|
14002
14172
|
const memoryTools = await memory?.listTools?.();
|
|
@@ -14036,7 +14206,12 @@ async function createNetworkLoop({
|
|
|
14036
14206
|
);
|
|
14037
14207
|
throw mastraError;
|
|
14038
14208
|
}
|
|
14039
|
-
const toolCallId = generateId2(
|
|
14209
|
+
const toolCallId = generateId2({
|
|
14210
|
+
idType: "step",
|
|
14211
|
+
source: "agent",
|
|
14212
|
+
entityId: toolId,
|
|
14213
|
+
stepType: "tool-execution"
|
|
14214
|
+
});
|
|
14040
14215
|
await writer?.write({
|
|
14041
14216
|
type: "tool-execution-start",
|
|
14042
14217
|
payload: {
|
|
@@ -14051,6 +14226,140 @@ async function createNetworkLoop({
|
|
|
14051
14226
|
from: "NETWORK" /* NETWORK */,
|
|
14052
14227
|
runId
|
|
14053
14228
|
});
|
|
14229
|
+
let toolRequiresApproval = tool2.requireApproval;
|
|
14230
|
+
if (tool2.needsApprovalFn) {
|
|
14231
|
+
try {
|
|
14232
|
+
const needsApprovalResult = await tool2.needsApprovalFn(inputDataToUse);
|
|
14233
|
+
toolRequiresApproval = needsApprovalResult;
|
|
14234
|
+
} catch (error) {
|
|
14235
|
+
logger?.error(`Error evaluating needsApprovalFn for tool ${toolId}:`, error);
|
|
14236
|
+
toolRequiresApproval = true;
|
|
14237
|
+
}
|
|
14238
|
+
}
|
|
14239
|
+
if (toolRequiresApproval) {
|
|
14240
|
+
if (!resumeData) {
|
|
14241
|
+
const requireApprovalResumeSchema = JSON.stringify(
|
|
14242
|
+
zodToJsonSchema(
|
|
14243
|
+
z10.object({
|
|
14244
|
+
approved: z10.boolean().describe(
|
|
14245
|
+
"Controls if the tool call is approved or not, should be true when approved and false when declined"
|
|
14246
|
+
)
|
|
14247
|
+
})
|
|
14248
|
+
)
|
|
14249
|
+
);
|
|
14250
|
+
await memory?.saveMessages({
|
|
14251
|
+
messages: [
|
|
14252
|
+
{
|
|
14253
|
+
id: generateId2(),
|
|
14254
|
+
type: "text",
|
|
14255
|
+
role: "assistant",
|
|
14256
|
+
content: {
|
|
14257
|
+
parts: [
|
|
14258
|
+
{
|
|
14259
|
+
type: "text",
|
|
14260
|
+
text: JSON.stringify({
|
|
14261
|
+
isNetwork: true,
|
|
14262
|
+
selectionReason: inputData.selectionReason,
|
|
14263
|
+
primitiveType: inputData.primitiveType,
|
|
14264
|
+
primitiveId: inputData.primitiveId,
|
|
14265
|
+
finalResult: { result: "", toolCallId },
|
|
14266
|
+
input: inputDataToUse
|
|
14267
|
+
})
|
|
14268
|
+
}
|
|
14269
|
+
],
|
|
14270
|
+
format: 2,
|
|
14271
|
+
metadata: {
|
|
14272
|
+
mode: "network",
|
|
14273
|
+
requireApprovalMetadata: {
|
|
14274
|
+
[inputData.primitiveId]: {
|
|
14275
|
+
toolCallId,
|
|
14276
|
+
toolName: inputData.primitiveId,
|
|
14277
|
+
args: inputDataToUse,
|
|
14278
|
+
type: "approval",
|
|
14279
|
+
resumeSchema: requireApprovalResumeSchema,
|
|
14280
|
+
runId,
|
|
14281
|
+
primitiveType: "tool",
|
|
14282
|
+
primitiveId: inputData.primitiveId
|
|
14283
|
+
}
|
|
14284
|
+
}
|
|
14285
|
+
}
|
|
14286
|
+
},
|
|
14287
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
14288
|
+
threadId: initData.threadId || runId,
|
|
14289
|
+
resourceId: initData.threadResourceId || networkName
|
|
14290
|
+
}
|
|
14291
|
+
]
|
|
14292
|
+
});
|
|
14293
|
+
await writer?.write({
|
|
14294
|
+
type: "tool-execution-approval",
|
|
14295
|
+
payload: {
|
|
14296
|
+
toolName: inputData.primitiveId,
|
|
14297
|
+
toolCallId,
|
|
14298
|
+
args: inputDataToUse,
|
|
14299
|
+
selectionReason: inputData.selectionReason,
|
|
14300
|
+
resumeSchema: requireApprovalResumeSchema,
|
|
14301
|
+
runId
|
|
14302
|
+
}
|
|
14303
|
+
});
|
|
14304
|
+
return suspend({
|
|
14305
|
+
requireToolApproval: {
|
|
14306
|
+
toolName: inputData.primitiveId,
|
|
14307
|
+
args: inputDataToUse,
|
|
14308
|
+
toolCallId
|
|
14309
|
+
}
|
|
14310
|
+
});
|
|
14311
|
+
} else {
|
|
14312
|
+
if (!resumeData.approved) {
|
|
14313
|
+
const rejectionResult = "Tool call was not approved by the user";
|
|
14314
|
+
await memory?.saveMessages({
|
|
14315
|
+
messages: [
|
|
14316
|
+
{
|
|
14317
|
+
id: generateId2(),
|
|
14318
|
+
type: "text",
|
|
14319
|
+
role: "assistant",
|
|
14320
|
+
content: {
|
|
14321
|
+
parts: [
|
|
14322
|
+
{
|
|
14323
|
+
type: "text",
|
|
14324
|
+
text: JSON.stringify({
|
|
14325
|
+
isNetwork: true,
|
|
14326
|
+
selectionReason: inputData.selectionReason,
|
|
14327
|
+
primitiveType: inputData.primitiveType,
|
|
14328
|
+
primitiveId: inputData.primitiveId,
|
|
14329
|
+
finalResult: { result: rejectionResult, toolCallId },
|
|
14330
|
+
input: inputDataToUse
|
|
14331
|
+
})
|
|
14332
|
+
}
|
|
14333
|
+
],
|
|
14334
|
+
format: 2
|
|
14335
|
+
},
|
|
14336
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
14337
|
+
threadId: initData.threadId || runId,
|
|
14338
|
+
resourceId: initData.threadResourceId || networkName
|
|
14339
|
+
}
|
|
14340
|
+
]
|
|
14341
|
+
});
|
|
14342
|
+
const endPayload2 = {
|
|
14343
|
+
task: inputData.task,
|
|
14344
|
+
primitiveId: inputData.primitiveId,
|
|
14345
|
+
primitiveType: inputData.primitiveType,
|
|
14346
|
+
result: rejectionResult,
|
|
14347
|
+
isComplete: false,
|
|
14348
|
+
iteration: inputData.iteration,
|
|
14349
|
+
toolCallId,
|
|
14350
|
+
toolName: toolId
|
|
14351
|
+
};
|
|
14352
|
+
await writer?.write({
|
|
14353
|
+
type: "tool-execution-end",
|
|
14354
|
+
payload: endPayload2,
|
|
14355
|
+
from: "NETWORK" /* NETWORK */,
|
|
14356
|
+
runId
|
|
14357
|
+
});
|
|
14358
|
+
return endPayload2;
|
|
14359
|
+
}
|
|
14360
|
+
}
|
|
14361
|
+
}
|
|
14362
|
+
let toolSuspendPayload;
|
|
14054
14363
|
const finalResult = await tool2.execute(
|
|
14055
14364
|
inputDataToUse,
|
|
14056
14365
|
{
|
|
@@ -14059,7 +14368,67 @@ async function createNetworkLoop({
|
|
|
14059
14368
|
agent: {
|
|
14060
14369
|
resourceId: initData.threadResourceId || networkName,
|
|
14061
14370
|
toolCallId,
|
|
14062
|
-
threadId: initData.threadId
|
|
14371
|
+
threadId: initData.threadId,
|
|
14372
|
+
suspend: async (suspendPayload, suspendOptions) => {
|
|
14373
|
+
await memory?.saveMessages({
|
|
14374
|
+
messages: [
|
|
14375
|
+
{
|
|
14376
|
+
id: generateId2(),
|
|
14377
|
+
type: "text",
|
|
14378
|
+
role: "assistant",
|
|
14379
|
+
content: {
|
|
14380
|
+
parts: [
|
|
14381
|
+
{
|
|
14382
|
+
type: "text",
|
|
14383
|
+
text: JSON.stringify({
|
|
14384
|
+
isNetwork: true,
|
|
14385
|
+
selectionReason: inputData.selectionReason,
|
|
14386
|
+
primitiveType: inputData.primitiveType,
|
|
14387
|
+
primitiveId: toolId,
|
|
14388
|
+
finalResult: { result: "", toolCallId },
|
|
14389
|
+
input: inputDataToUse
|
|
14390
|
+
})
|
|
14391
|
+
}
|
|
14392
|
+
],
|
|
14393
|
+
format: 2,
|
|
14394
|
+
metadata: {
|
|
14395
|
+
mode: "network",
|
|
14396
|
+
suspendedTools: {
|
|
14397
|
+
[inputData.primitiveId]: {
|
|
14398
|
+
toolCallId,
|
|
14399
|
+
toolName: inputData.primitiveId,
|
|
14400
|
+
args: inputDataToUse,
|
|
14401
|
+
suspendPayload,
|
|
14402
|
+
type: "suspension",
|
|
14403
|
+
resumeSchema: suspendOptions?.resumeSchema ?? JSON.stringify(zodToJsonSchema(tool2.resumeSchema)),
|
|
14404
|
+
runId,
|
|
14405
|
+
primitiveType: "tool",
|
|
14406
|
+
primitiveId: inputData.primitiveId
|
|
14407
|
+
}
|
|
14408
|
+
}
|
|
14409
|
+
}
|
|
14410
|
+
},
|
|
14411
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
14412
|
+
threadId: initData.threadId || runId,
|
|
14413
|
+
resourceId: initData.threadResourceId || networkName
|
|
14414
|
+
}
|
|
14415
|
+
]
|
|
14416
|
+
});
|
|
14417
|
+
await writer?.write({
|
|
14418
|
+
type: "tool-execution-suspended",
|
|
14419
|
+
payload: {
|
|
14420
|
+
toolName: inputData.primitiveId,
|
|
14421
|
+
toolCallId,
|
|
14422
|
+
args: inputDataToUse,
|
|
14423
|
+
resumeSchema: suspendOptions?.resumeSchema ?? JSON.stringify(zodToJsonSchema(tool2.resumeSchema)),
|
|
14424
|
+
suspendPayload,
|
|
14425
|
+
runId,
|
|
14426
|
+
selectionReason: inputData.selectionReason
|
|
14427
|
+
}
|
|
14428
|
+
});
|
|
14429
|
+
toolSuspendPayload = suspendPayload;
|
|
14430
|
+
},
|
|
14431
|
+
resumeData
|
|
14063
14432
|
},
|
|
14064
14433
|
runId,
|
|
14065
14434
|
memory,
|
|
@@ -14070,10 +14439,25 @@ async function createNetworkLoop({
|
|
|
14070
14439
|
},
|
|
14071
14440
|
{ toolCallId, messages: [] }
|
|
14072
14441
|
);
|
|
14442
|
+
if (toolSuspendPayload) {
|
|
14443
|
+
return await suspend({
|
|
14444
|
+
toolCallSuspended: toolSuspendPayload,
|
|
14445
|
+
toolName: inputData.primitiveId,
|
|
14446
|
+
args: inputDataToUse,
|
|
14447
|
+
toolCallId
|
|
14448
|
+
});
|
|
14449
|
+
}
|
|
14073
14450
|
await memory?.saveMessages({
|
|
14074
14451
|
messages: [
|
|
14075
14452
|
{
|
|
14076
|
-
id: generateId2(
|
|
14453
|
+
id: generateId2({
|
|
14454
|
+
idType: "message",
|
|
14455
|
+
source: "agent",
|
|
14456
|
+
entityId: toolId,
|
|
14457
|
+
threadId: initData.threadId,
|
|
14458
|
+
resourceId: initData.threadResourceId || networkName,
|
|
14459
|
+
role: "assistant"
|
|
14460
|
+
}),
|
|
14077
14461
|
type: "text",
|
|
14078
14462
|
role: "assistant",
|
|
14079
14463
|
content: {
|
|
@@ -14100,7 +14484,7 @@ async function createNetworkLoop({
|
|
|
14100
14484
|
});
|
|
14101
14485
|
const endPayload = {
|
|
14102
14486
|
task: inputData.task,
|
|
14103
|
-
primitiveId:
|
|
14487
|
+
primitiveId: inputData.primitiveId,
|
|
14104
14488
|
primitiveType: inputData.primitiveType,
|
|
14105
14489
|
result: finalResult,
|
|
14106
14490
|
isComplete: false,
|
|
@@ -14127,7 +14511,8 @@ async function createNetworkLoop({
|
|
|
14127
14511
|
result: z10.string(),
|
|
14128
14512
|
isComplete: z10.boolean().optional(),
|
|
14129
14513
|
selectionReason: z10.string(),
|
|
14130
|
-
iteration: z10.number()
|
|
14514
|
+
iteration: z10.number(),
|
|
14515
|
+
conversationContext: z10.array(z10.any()).optional()
|
|
14131
14516
|
}),
|
|
14132
14517
|
outputSchema: z10.object({
|
|
14133
14518
|
task: z10.string(),
|
|
@@ -14250,6 +14635,9 @@ async function networkLoop({
|
|
|
14250
14635
|
validation,
|
|
14251
14636
|
routing,
|
|
14252
14637
|
onIterationComplete,
|
|
14638
|
+
resumeData,
|
|
14639
|
+
autoResumeSuspendedTools,
|
|
14640
|
+
mastra,
|
|
14253
14641
|
structuredOutput
|
|
14254
14642
|
}) {
|
|
14255
14643
|
const memoryToUse = await routingAgent.getMemory({ requestContext });
|
|
@@ -14264,11 +14652,84 @@ async function networkLoop({
|
|
|
14264
14652
|
}
|
|
14265
14653
|
});
|
|
14266
14654
|
}
|
|
14655
|
+
const task = getLastMessage(messages);
|
|
14656
|
+
let resumeDataFromTask;
|
|
14657
|
+
let runIdFromTask;
|
|
14658
|
+
if (autoResumeSuspendedTools && threadId) {
|
|
14659
|
+
let lastAssistantMessage;
|
|
14660
|
+
let requireApprovalMetadata;
|
|
14661
|
+
let suspendedTools;
|
|
14662
|
+
const memory = await routingAgent.getMemory({ requestContext });
|
|
14663
|
+
const threadExists = await memory?.getThreadById({ threadId });
|
|
14664
|
+
if (threadExists) {
|
|
14665
|
+
const recallResult = await memory?.recall({
|
|
14666
|
+
threadId,
|
|
14667
|
+
resourceId: resourceId || networkName
|
|
14668
|
+
});
|
|
14669
|
+
if (recallResult && recallResult.messages?.length > 0) {
|
|
14670
|
+
const messages2 = [...recallResult.messages]?.reverse()?.filter((message) => message.role === "assistant");
|
|
14671
|
+
lastAssistantMessage = messages2[0];
|
|
14672
|
+
}
|
|
14673
|
+
if (lastAssistantMessage) {
|
|
14674
|
+
const { metadata } = lastAssistantMessage.content;
|
|
14675
|
+
if (metadata?.requireApprovalMetadata) {
|
|
14676
|
+
requireApprovalMetadata = metadata.requireApprovalMetadata;
|
|
14677
|
+
}
|
|
14678
|
+
if (metadata?.suspendedTools) {
|
|
14679
|
+
suspendedTools = metadata.suspendedTools;
|
|
14680
|
+
}
|
|
14681
|
+
if (requireApprovalMetadata || suspendedTools) {
|
|
14682
|
+
const suspendedToolsArr = Object.values({ ...suspendedTools, ...requireApprovalMetadata });
|
|
14683
|
+
const firstSuspendedTool = suspendedToolsArr[0];
|
|
14684
|
+
if (firstSuspendedTool.resumeSchema) {
|
|
14685
|
+
try {
|
|
14686
|
+
const llm = await routingAgent.getLLM({ requestContext });
|
|
14687
|
+
const systemInstructions = `
|
|
14688
|
+
You are an assistant used to resume a suspended tool call.
|
|
14689
|
+
Your job is to construct the resumeData for the tool call using the messages available to you and the schema passed.
|
|
14690
|
+
You will generate an object that matches this schema: ${firstSuspendedTool.resumeSchema}.
|
|
14691
|
+
The resumeData generated should be a JSON value that is constructed from the messages, using the schema as guide. The JSON value is stringified.
|
|
14692
|
+
|
|
14693
|
+
{
|
|
14694
|
+
"resumeData": "string"
|
|
14695
|
+
}
|
|
14696
|
+
`;
|
|
14697
|
+
const messageList = new MessageList();
|
|
14698
|
+
messageList.addSystem(systemInstructions);
|
|
14699
|
+
messageList.add(task, "user");
|
|
14700
|
+
const result = llm.stream({
|
|
14701
|
+
methodType: "generate",
|
|
14702
|
+
requestContext,
|
|
14703
|
+
messageList,
|
|
14704
|
+
agentId: routingAgent.id,
|
|
14705
|
+
tracingContext: routingAgentOptions?.tracingContext,
|
|
14706
|
+
structuredOutput: {
|
|
14707
|
+
schema: z10.object({
|
|
14708
|
+
resumeData: z10.string()
|
|
14709
|
+
})
|
|
14710
|
+
}
|
|
14711
|
+
});
|
|
14712
|
+
const object = await result.object;
|
|
14713
|
+
const resumeDataFromLLM = JSON.parse(object.resumeData);
|
|
14714
|
+
if (Object.keys(resumeDataFromLLM).length > 0) {
|
|
14715
|
+
resumeDataFromTask = resumeDataFromLLM;
|
|
14716
|
+
runIdFromTask = firstSuspendedTool.runId;
|
|
14717
|
+
}
|
|
14718
|
+
} catch (error) {
|
|
14719
|
+
mastra?.getLogger()?.error(`Error generating resume data for network agent ${routingAgent.id}`, error);
|
|
14720
|
+
}
|
|
14721
|
+
}
|
|
14722
|
+
}
|
|
14723
|
+
}
|
|
14724
|
+
}
|
|
14725
|
+
}
|
|
14726
|
+
const runIdToUse = runIdFromTask ?? runId;
|
|
14727
|
+
const resumeDataToUse = resumeDataFromTask ?? resumeData;
|
|
14267
14728
|
const { memory: routingAgentMemoryOptions, ...routingAgentOptionsWithoutMemory } = routingAgentOptions || {};
|
|
14268
14729
|
const { networkWorkflow } = await createNetworkLoop({
|
|
14269
14730
|
networkName,
|
|
14270
14731
|
requestContext,
|
|
14271
|
-
runId,
|
|
14732
|
+
runId: runIdToUse,
|
|
14272
14733
|
agent: routingAgent,
|
|
14273
14734
|
routingAgentOptions: routingAgentOptionsWithoutMemory,
|
|
14274
14735
|
generateId: generateId2,
|
|
@@ -14293,7 +14754,7 @@ async function networkLoop({
|
|
|
14293
14754
|
execute: async ({ inputData, writer }) => {
|
|
14294
14755
|
const configuredScorers = validation?.scorers || [];
|
|
14295
14756
|
const memory = await routingAgent.getMemory({ requestContext });
|
|
14296
|
-
const recallResult = memory ? await memory.recall({ threadId: inputData.threadId ||
|
|
14757
|
+
const recallResult = memory ? await memory.recall({ threadId: inputData.threadId || runIdToUse }) : { messages: [] };
|
|
14297
14758
|
const completionContext = {
|
|
14298
14759
|
iteration: inputData.iteration,
|
|
14299
14760
|
maxIterations,
|
|
@@ -14306,7 +14767,7 @@ async function networkLoop({
|
|
|
14306
14767
|
primitivePrompt: inputData.prompt,
|
|
14307
14768
|
primitiveResult: inputData.result,
|
|
14308
14769
|
networkName,
|
|
14309
|
-
runId,
|
|
14770
|
+
runId: runIdToUse,
|
|
14310
14771
|
threadId: inputData.threadId,
|
|
14311
14772
|
resourceId: inputData.threadResourceId,
|
|
14312
14773
|
customContext: requestContext?.toJSON?.()
|
|
@@ -14315,7 +14776,7 @@ async function networkLoop({
|
|
|
14315
14776
|
await writer?.write({
|
|
14316
14777
|
type: "network-validation-start",
|
|
14317
14778
|
payload: {
|
|
14318
|
-
runId,
|
|
14779
|
+
runId: runIdToUse,
|
|
14319
14780
|
iteration: inputData.iteration,
|
|
14320
14781
|
checksCount: hasConfiguredScorers ? configuredScorers.length : 1
|
|
14321
14782
|
},
|
|
@@ -14341,7 +14802,7 @@ async function networkLoop({
|
|
|
14341
14802
|
{
|
|
14342
14803
|
writer,
|
|
14343
14804
|
stepId: generateId2(),
|
|
14344
|
-
runId
|
|
14805
|
+
runId: runIdToUse
|
|
14345
14806
|
}
|
|
14346
14807
|
);
|
|
14347
14808
|
generatedFinalResult = structuredResult.text;
|
|
@@ -14350,13 +14811,13 @@ async function networkLoop({
|
|
|
14350
14811
|
generatedFinalResult = await generateFinalResult(routingAgentToUse, completionContext, {
|
|
14351
14812
|
writer,
|
|
14352
14813
|
stepId: generateId2(),
|
|
14353
|
-
runId
|
|
14814
|
+
runId: runIdToUse
|
|
14354
14815
|
});
|
|
14355
14816
|
}
|
|
14356
14817
|
await saveFinalResultIfProvided({
|
|
14357
14818
|
memory: await routingAgent.getMemory({ requestContext }),
|
|
14358
14819
|
finalResult: generatedFinalResult,
|
|
14359
|
-
threadId: inputData.threadId ||
|
|
14820
|
+
threadId: inputData.threadId || runIdToUse,
|
|
14360
14821
|
resourceId: inputData.threadResourceId || networkName,
|
|
14361
14822
|
generateId: generateId2
|
|
14362
14823
|
});
|
|
@@ -14370,7 +14831,7 @@ async function networkLoop({
|
|
|
14370
14831
|
const defaultResult = await runDefaultCompletionCheck(routingAgentToUse, completionContext, {
|
|
14371
14832
|
writer,
|
|
14372
14833
|
stepId: generateId2(),
|
|
14373
|
-
runId
|
|
14834
|
+
runId: runIdToUse
|
|
14374
14835
|
});
|
|
14375
14836
|
completionResult = {
|
|
14376
14837
|
complete: defaultResult.passed,
|
|
@@ -14400,13 +14861,13 @@ async function networkLoop({
|
|
|
14400
14861
|
await saveFinalResultIfProvided({
|
|
14401
14862
|
memory: await routingAgent.getMemory({ requestContext }),
|
|
14402
14863
|
finalResult: generatedFinalResult || defaultResult.finalResult,
|
|
14403
|
-
threadId: inputData.threadId ||
|
|
14864
|
+
threadId: inputData.threadId || runIdToUse,
|
|
14404
14865
|
resourceId: inputData.threadResourceId || networkName,
|
|
14405
14866
|
generateId: generateId2
|
|
14406
14867
|
});
|
|
14407
14868
|
}
|
|
14408
14869
|
}
|
|
14409
|
-
const maxIterationReached = inputData.iteration >= maxIterations;
|
|
14870
|
+
const maxIterationReached = maxIterations && inputData.iteration >= maxIterations;
|
|
14410
14871
|
await writer?.write({
|
|
14411
14872
|
type: "network-validation-end",
|
|
14412
14873
|
payload: {
|
|
@@ -14420,7 +14881,7 @@ async function networkLoop({
|
|
|
14420
14881
|
maxIterationReached: !!maxIterationReached
|
|
14421
14882
|
},
|
|
14422
14883
|
from: "NETWORK" /* NETWORK */,
|
|
14423
|
-
runId
|
|
14884
|
+
runId: runIdToUse
|
|
14424
14885
|
});
|
|
14425
14886
|
const isComplete = completionResult.complete;
|
|
14426
14887
|
if (onIterationComplete) {
|
|
@@ -14457,7 +14918,7 @@ async function networkLoop({
|
|
|
14457
14918
|
}
|
|
14458
14919
|
},
|
|
14459
14920
|
createdAt: /* @__PURE__ */ new Date(),
|
|
14460
|
-
threadId: inputData.threadId ||
|
|
14921
|
+
threadId: inputData.threadId || runIdToUse,
|
|
14461
14922
|
resourceId: inputData.threadResourceId || networkName
|
|
14462
14923
|
}
|
|
14463
14924
|
]
|
|
@@ -14514,13 +14975,13 @@ async function networkLoop({
|
|
|
14514
14975
|
const finalData = {
|
|
14515
14976
|
...restInputData,
|
|
14516
14977
|
...structuredObject !== void 0 ? { object: structuredObject } : {},
|
|
14517
|
-
...inputData.iteration >= maxIterations ? { completionReason: `Max iterations reached: ${maxIterations}` } : {}
|
|
14978
|
+
...maxIterations && inputData.iteration >= maxIterations ? { completionReason: `Max iterations reached: ${maxIterations}` } : {}
|
|
14518
14979
|
};
|
|
14519
14980
|
await writer?.write({
|
|
14520
14981
|
type: "network-execution-event-finish",
|
|
14521
14982
|
payload: finalData,
|
|
14522
14983
|
from: "NETWORK" /* NETWORK */,
|
|
14523
|
-
runId
|
|
14984
|
+
runId: runIdToUse
|
|
14524
14985
|
});
|
|
14525
14986
|
return finalData;
|
|
14526
14987
|
}
|
|
@@ -14565,11 +15026,16 @@ async function networkLoop({
|
|
|
14565
15026
|
}).dountil(iterationWithValidation, async ({ inputData }) => {
|
|
14566
15027
|
const llmComplete = inputData.isComplete === true;
|
|
14567
15028
|
const validationOk = inputData.validationPassed !== false;
|
|
14568
|
-
const maxReached = Boolean(inputData.iteration >= maxIterations);
|
|
15029
|
+
const maxReached = Boolean(maxIterations && inputData.iteration >= maxIterations);
|
|
14569
15030
|
return llmComplete && validationOk || maxReached;
|
|
14570
15031
|
}).then(finalStep).commit();
|
|
15032
|
+
const mastraInstance = routingAgent.getMastraInstance();
|
|
15033
|
+
if (mastraInstance) {
|
|
15034
|
+
mainWorkflow.__registerMastra(mastraInstance);
|
|
15035
|
+
networkWorkflow.__registerMastra(mastraInstance);
|
|
15036
|
+
}
|
|
14571
15037
|
const run = await mainWorkflow.createRun({
|
|
14572
|
-
runId
|
|
15038
|
+
runId: runIdToUse
|
|
14573
15039
|
});
|
|
14574
15040
|
const { thread } = await prepareMemoryStep({
|
|
14575
15041
|
requestContext,
|
|
@@ -14581,10 +15047,14 @@ async function networkLoop({
|
|
|
14581
15047
|
tracingContext: routingAgentOptions?.tracingContext,
|
|
14582
15048
|
memoryConfig: routingAgentMemoryOptions?.options
|
|
14583
15049
|
});
|
|
14584
|
-
const task = getLastMessage(messages);
|
|
14585
15050
|
return new MastraAgentNetworkStream({
|
|
14586
15051
|
run,
|
|
14587
15052
|
createStream: () => {
|
|
15053
|
+
if (resumeDataToUse) {
|
|
15054
|
+
return run.resumeStream({
|
|
15055
|
+
resumeData: resumeDataToUse
|
|
15056
|
+
}).fullStream;
|
|
15057
|
+
}
|
|
14588
15058
|
return run.stream({
|
|
14589
15059
|
inputData: {
|
|
14590
15060
|
task,
|
|
@@ -14862,29 +15332,29 @@ var AgentLegacyHandler = class {
|
|
|
14862
15332
|
});
|
|
14863
15333
|
}
|
|
14864
15334
|
const promises = [];
|
|
14865
|
-
|
|
14866
|
-
|
|
14867
|
-
|
|
14868
|
-
|
|
14869
|
-
|
|
14870
|
-
|
|
14871
|
-
|
|
14872
|
-
|
|
14873
|
-
|
|
14874
|
-
|
|
14875
|
-
|
|
14876
|
-
|
|
14877
|
-
|
|
14878
|
-
|
|
14879
|
-
|
|
14880
|
-
|
|
14881
|
-
|
|
14882
|
-
|
|
14883
|
-
|
|
14884
|
-
}
|
|
14885
|
-
}
|
|
14886
|
-
)
|
|
14887
|
-
|
|
15335
|
+
const config = memory.getMergedThreadConfig(memoryConfig2);
|
|
15336
|
+
const userMessage = this.capabilities.getMostRecentUserMessage(messageList.get.all.ui());
|
|
15337
|
+
const {
|
|
15338
|
+
shouldGenerate,
|
|
15339
|
+
model: titleModel,
|
|
15340
|
+
instructions: titleInstructions
|
|
15341
|
+
} = this.capabilities.resolveTitleGenerationConfig(config?.generateTitle);
|
|
15342
|
+
const rememberedUserMessages = messageList.get.remembered.db().filter((m) => m.role === "user");
|
|
15343
|
+
const isFirstUserMessage = rememberedUserMessages.length === 0;
|
|
15344
|
+
if (shouldGenerate && isFirstUserMessage && userMessage) {
|
|
15345
|
+
promises.push(
|
|
15346
|
+
this.capabilities.genTitle(userMessage, requestContext, { currentSpan: agentSpan }, titleModel, titleInstructions).then((title) => {
|
|
15347
|
+
if (title) {
|
|
15348
|
+
return memory.createThread({
|
|
15349
|
+
threadId: thread2.id,
|
|
15350
|
+
resourceId,
|
|
15351
|
+
memoryConfig: memoryConfig2,
|
|
15352
|
+
title,
|
|
15353
|
+
metadata: thread2.metadata
|
|
15354
|
+
});
|
|
15355
|
+
}
|
|
15356
|
+
})
|
|
15357
|
+
);
|
|
14888
15358
|
}
|
|
14889
15359
|
if (promises.length > 0) {
|
|
14890
15360
|
await Promise.all(promises);
|
|
@@ -14998,7 +15468,13 @@ var AgentLegacyHandler = class {
|
|
|
14998
15468
|
`[Agent:${this.capabilities.name}] - No memory is configured but resourceId and threadId were passed in args. This will not work.`
|
|
14999
15469
|
);
|
|
15000
15470
|
}
|
|
15001
|
-
const runId = args.runId || this.capabilities.mastra?.generateId(
|
|
15471
|
+
const runId = args.runId || this.capabilities.mastra?.generateId({
|
|
15472
|
+
idType: "run",
|
|
15473
|
+
source: "agent",
|
|
15474
|
+
entityId: this.capabilities.id,
|
|
15475
|
+
threadId: threadFromArgs?.id,
|
|
15476
|
+
resourceId
|
|
15477
|
+
}) || randomUUID();
|
|
15002
15478
|
const instructions = args.instructions || await this.capabilities.getInstructions({ requestContext });
|
|
15003
15479
|
const llm = await this.capabilities.getLLM({ requestContext });
|
|
15004
15480
|
const memory = await this.capabilities.getMemory({ requestContext });
|
|
@@ -15643,11 +16119,7 @@ function createMapResultsStep({
|
|
|
15643
16119
|
agentId,
|
|
15644
16120
|
methodType
|
|
15645
16121
|
}) {
|
|
15646
|
-
return async ({
|
|
15647
|
-
inputData,
|
|
15648
|
-
bail,
|
|
15649
|
-
tracingContext
|
|
15650
|
-
}) => {
|
|
16122
|
+
return async ({ inputData, bail, tracingContext }) => {
|
|
15651
16123
|
const toolsData = inputData["prepare-tools-step"];
|
|
15652
16124
|
const memoryData = inputData["prepare-memory-step"];
|
|
15653
16125
|
const result = {
|
|
@@ -15806,7 +16278,7 @@ var coreToolSchema = z.object({
|
|
|
15806
16278
|
// Zod schema or other schema types - validated at tool execution
|
|
15807
16279
|
]),
|
|
15808
16280
|
outputSchema: z.union([z.record(z.string(), z.any()), z.any()]).optional(),
|
|
15809
|
-
execute: z.function(z.tuple([z.any(), z.any()]), z.promise(z.any()))
|
|
16281
|
+
execute: z.optional(z.function(z.tuple([z.any(), z.any()]), z.promise(z.any()))),
|
|
15810
16282
|
type: z.union([z.literal("function"), z.literal("provider-defined"), z.undefined()]).optional(),
|
|
15811
16283
|
args: z.record(z.string(), z.any()).optional()
|
|
15812
16284
|
});
|
|
@@ -16021,12 +16493,10 @@ function createStreamStep({
|
|
|
16021
16493
|
}) {
|
|
16022
16494
|
return createStep({
|
|
16023
16495
|
id: "stream-text-step",
|
|
16496
|
+
// @ts-ignore
|
|
16024
16497
|
inputSchema: z.any(),
|
|
16025
16498
|
// tried to type this in various ways but it's too complex
|
|
16026
|
-
outputSchema: z.
|
|
16027
|
-
z.instanceof(MastraModelOutput),
|
|
16028
|
-
z.instanceof(AISDKV5OutputStream)
|
|
16029
|
-
]),
|
|
16499
|
+
outputSchema: z.instanceof(MastraModelOutput),
|
|
16030
16500
|
execute: async ({ inputData, tracingContext }) => {
|
|
16031
16501
|
const validatedInputData = inputData;
|
|
16032
16502
|
capabilities.logger.debug(`Starting agent ${capabilities.agentName} llm stream call`, {
|
|
@@ -16139,10 +16609,7 @@ function createPrepareStreamWorkflow({
|
|
|
16139
16609
|
return createWorkflow({
|
|
16140
16610
|
id: "execution-workflow",
|
|
16141
16611
|
inputSchema: z.object({}),
|
|
16142
|
-
outputSchema: z.
|
|
16143
|
-
z.instanceof(MastraModelOutput),
|
|
16144
|
-
z.instanceof(AISDKV5OutputStream)
|
|
16145
|
-
]),
|
|
16612
|
+
outputSchema: z.instanceof(MastraModelOutput),
|
|
16146
16613
|
steps: [prepareToolsStep, prepareMemoryStep2, streamStep],
|
|
16147
16614
|
options: {
|
|
16148
16615
|
tracingPolicy: {
|
|
@@ -16324,6 +16791,11 @@ var Agent = class extends MastraBase {
|
|
|
16324
16791
|
this.logger.error(mastraError.toString());
|
|
16325
16792
|
throw mastraError;
|
|
16326
16793
|
}
|
|
16794
|
+
Object.entries(agents || {}).forEach(([_agentName, agent]) => {
|
|
16795
|
+
if (this.#mastra) {
|
|
16796
|
+
agent.__registerMastra(this.#mastra);
|
|
16797
|
+
}
|
|
16798
|
+
});
|
|
16327
16799
|
return agents;
|
|
16328
16800
|
});
|
|
16329
16801
|
}
|
|
@@ -16793,9 +17265,7 @@ var Agent = class extends MastraBase {
|
|
|
16793
17265
|
* console.log(options.maxSteps); // 5
|
|
16794
17266
|
* ```
|
|
16795
17267
|
*/
|
|
16796
|
-
getDefaultOptions({
|
|
16797
|
-
requestContext = new RequestContext()
|
|
16798
|
-
} = {}) {
|
|
17268
|
+
getDefaultOptions({ requestContext = new RequestContext() } = {}) {
|
|
16799
17269
|
if (typeof this.#defaultOptions !== "function") {
|
|
16800
17270
|
return this.#defaultOptions;
|
|
16801
17271
|
}
|
|
@@ -17596,8 +18066,17 @@ var Agent = class extends MastraBase {
|
|
|
17596
18066
|
});
|
|
17597
18067
|
let result;
|
|
17598
18068
|
const slugify = await import('@sindresorhus/slugify');
|
|
17599
|
-
const subAgentThreadId = inputData.threadId || context?.mastra?.generateId(
|
|
17600
|
-
|
|
18069
|
+
const subAgentThreadId = inputData.threadId || context?.mastra?.generateId({
|
|
18070
|
+
idType: "thread",
|
|
18071
|
+
source: "agent",
|
|
18072
|
+
entityId: agentName,
|
|
18073
|
+
resourceId
|
|
18074
|
+
}) || randomUUID();
|
|
18075
|
+
const subAgentResourceId = inputData.resourceId || context?.mastra?.generateId({
|
|
18076
|
+
idType: "generic",
|
|
18077
|
+
source: "agent",
|
|
18078
|
+
entityId: agentName
|
|
18079
|
+
}) || `${slugify.default(this.id)}-${agentName}`;
|
|
17601
18080
|
if ((methodType === "generate" || methodType === "generateLegacy") && supportedLanguageModelSpecifications.includes(modelVersion)) {
|
|
17602
18081
|
if (!agent.hasOwnMemory() && this.#memory) {
|
|
17603
18082
|
agent.__setMemory(this.#memory);
|
|
@@ -17757,6 +18236,7 @@ var Agent = class extends MastraBase {
|
|
|
17757
18236
|
mastra: this.#mastra,
|
|
17758
18237
|
// manually wrap workflow tools with tracing, so that we can pass the
|
|
17759
18238
|
// current tool span onto the workflow to maintain continuity of the trace
|
|
18239
|
+
// @ts-ignore
|
|
17760
18240
|
execute: async (inputData, context) => {
|
|
17761
18241
|
try {
|
|
17762
18242
|
const { initialState, inputData: workflowInputData, suspendedToolRunId } = inputData;
|
|
@@ -17834,18 +18314,21 @@ var Agent = class extends MastraBase {
|
|
|
17834
18314
|
while (firstSuspendedStepPath.length > 0) {
|
|
17835
18315
|
const key = firstSuspendedStepPath.shift();
|
|
17836
18316
|
if (key) {
|
|
17837
|
-
if (!
|
|
18317
|
+
if (!wflowStep.steps[key]) {
|
|
17838
18318
|
this.logger.warn(`Suspended step '${key}' not found in workflow '${workflowName}'`);
|
|
17839
18319
|
break;
|
|
17840
18320
|
}
|
|
17841
|
-
wflowStep =
|
|
18321
|
+
wflowStep = wflowStep.steps[key];
|
|
17842
18322
|
}
|
|
17843
18323
|
}
|
|
17844
18324
|
const resumeSchema = wflowStep?.resumeSchema;
|
|
17845
18325
|
if (suspendPayload?.__workflow_meta) {
|
|
17846
18326
|
delete suspendPayload.__workflow_meta;
|
|
17847
18327
|
}
|
|
17848
|
-
return suspend?.(suspendPayload, {
|
|
18328
|
+
return suspend?.(suspendPayload, {
|
|
18329
|
+
resumeLabel: suspendedStepIds,
|
|
18330
|
+
resumeSchema: resumeSchema ? JSON.stringify(zodToJsonSchema(resumeSchema)) : void 0
|
|
18331
|
+
});
|
|
17849
18332
|
} else {
|
|
17850
18333
|
return {
|
|
17851
18334
|
error: `Workflow should never reach this path, workflow returned no status`,
|
|
@@ -18222,11 +18705,7 @@ var Agent = class extends MastraBase {
|
|
|
18222
18705
|
* Executes the agent call, handling tools, memory, and streaming.
|
|
18223
18706
|
* @internal
|
|
18224
18707
|
*/
|
|
18225
|
-
async #execute({
|
|
18226
|
-
methodType,
|
|
18227
|
-
resumeContext,
|
|
18228
|
-
...options
|
|
18229
|
-
}) {
|
|
18708
|
+
async #execute({ methodType, resumeContext, ...options }) {
|
|
18230
18709
|
const existingSnapshot = resumeContext?.snapshot;
|
|
18231
18710
|
let snapshotMemoryInfo;
|
|
18232
18711
|
if (existingSnapshot) {
|
|
@@ -18242,10 +18721,12 @@ var Agent = class extends MastraBase {
|
|
|
18242
18721
|
const resourceIdFromContext = requestContext.get(MASTRA_RESOURCE_ID_KEY);
|
|
18243
18722
|
const threadIdFromContext = requestContext.get(MASTRA_THREAD_ID_KEY);
|
|
18244
18723
|
const threadFromArgs = threadIdFromContext ? { id: threadIdFromContext } : resolveThreadIdFromArgs({
|
|
18245
|
-
|
|
18246
|
-
|
|
18724
|
+
memory: {
|
|
18725
|
+
...options.memory,
|
|
18726
|
+
thread: options.memory?.thread || snapshotMemoryInfo?.threadId
|
|
18727
|
+
}
|
|
18247
18728
|
});
|
|
18248
|
-
const resourceId = resourceIdFromContext || options.memory?.resource ||
|
|
18729
|
+
const resourceId = resourceIdFromContext || options.memory?.resource || snapshotMemoryInfo?.resourceId;
|
|
18249
18730
|
const memoryConfig = options.memory?.options;
|
|
18250
18731
|
if (resourceId && threadFromArgs && !this.hasOwnMemory()) {
|
|
18251
18732
|
this.logger.warn(
|
|
@@ -18253,7 +18734,7 @@ var Agent = class extends MastraBase {
|
|
|
18253
18734
|
);
|
|
18254
18735
|
}
|
|
18255
18736
|
const llm = await this.getLLM({ requestContext, model: options.model });
|
|
18256
|
-
if ("structuredOutput" in options && options.structuredOutput
|
|
18737
|
+
if ("structuredOutput" in options && options.structuredOutput?.schema) {
|
|
18257
18738
|
let structuredOutputModel = llm.getModel();
|
|
18258
18739
|
if (options.structuredOutput?.model) {
|
|
18259
18740
|
structuredOutputModel = await this.resolveModelConfig(
|
|
@@ -18274,14 +18755,18 @@ var Agent = class extends MastraBase {
|
|
|
18274
18755
|
const isReasoningModel = /^o[1-5]/.test(targetModelId);
|
|
18275
18756
|
const compatLayer = isReasoningModel ? new OpenAIReasoningSchemaCompatLayer(modelInfo) : new OpenAISchemaCompatLayer(modelInfo);
|
|
18276
18757
|
if (compatLayer.shouldApply() && options.structuredOutput.schema) {
|
|
18277
|
-
options.structuredOutput.schema = compatLayer.processZodType(
|
|
18278
|
-
options.structuredOutput.schema
|
|
18279
|
-
);
|
|
18758
|
+
options.structuredOutput.schema = compatLayer.processZodType(options.structuredOutput.schema);
|
|
18280
18759
|
}
|
|
18281
18760
|
}
|
|
18282
18761
|
}
|
|
18283
18762
|
}
|
|
18284
|
-
const runId = options.runId || this.#mastra?.generateId(
|
|
18763
|
+
const runId = options.runId || this.#mastra?.generateId({
|
|
18764
|
+
idType: "run",
|
|
18765
|
+
source: "agent",
|
|
18766
|
+
entityId: this.id,
|
|
18767
|
+
threadId: threadFromArgs?.id,
|
|
18768
|
+
resourceId
|
|
18769
|
+
}) || randomUUID();
|
|
18285
18770
|
const instructions = options.instructions || await this.getInstructions({ requestContext });
|
|
18286
18771
|
const agentSpan = getOrCreateSpan({
|
|
18287
18772
|
type: "agent_run" /* AGENT_RUN */,
|
|
@@ -18432,15 +18917,17 @@ var Agent = class extends MastraBase {
|
|
|
18432
18917
|
resourceId: thread.resourceId
|
|
18433
18918
|
});
|
|
18434
18919
|
}
|
|
18435
|
-
|
|
18436
|
-
|
|
18920
|
+
const config = memory.getMergedThreadConfig(memoryConfig);
|
|
18921
|
+
const {
|
|
18922
|
+
shouldGenerate,
|
|
18923
|
+
model: titleModel,
|
|
18924
|
+
instructions: titleInstructions
|
|
18925
|
+
} = this.resolveTitleGenerationConfig(config.generateTitle);
|
|
18926
|
+
const rememberedUserMessages = messageList.get.remembered.db().filter((m) => m.role === "user");
|
|
18927
|
+
const isFirstUserMessage = rememberedUserMessages.length === 0;
|
|
18928
|
+
if (shouldGenerate && isFirstUserMessage) {
|
|
18437
18929
|
const userMessage = this.getMostRecentUserMessage(messageList.get.all.ui());
|
|
18438
|
-
|
|
18439
|
-
shouldGenerate,
|
|
18440
|
-
model: titleModel,
|
|
18441
|
-
instructions: titleInstructions
|
|
18442
|
-
} = this.resolveTitleGenerationConfig(config.generateTitle);
|
|
18443
|
-
if (shouldGenerate && userMessage) {
|
|
18930
|
+
if (userMessage) {
|
|
18444
18931
|
const title = await this.genTitle(
|
|
18445
18932
|
userMessage,
|
|
18446
18933
|
requestContext,
|
|
@@ -18518,15 +19005,53 @@ var Agent = class extends MastraBase {
|
|
|
18518
19005
|
}
|
|
18519
19006
|
});
|
|
18520
19007
|
}
|
|
19008
|
+
async network(messages, options) {
|
|
19009
|
+
const requestContextToUse = options?.requestContext || new RequestContext();
|
|
19010
|
+
const defaultNetworkOptions = await this.getDefaultNetworkOptions({ requestContext: requestContextToUse });
|
|
19011
|
+
const mergedOptions = {
|
|
19012
|
+
...defaultNetworkOptions,
|
|
19013
|
+
...options,
|
|
19014
|
+
// Deep merge nested objects
|
|
19015
|
+
routing: { ...defaultNetworkOptions?.routing, ...options?.routing },
|
|
19016
|
+
completion: { ...defaultNetworkOptions?.completion, ...options?.completion }
|
|
19017
|
+
};
|
|
19018
|
+
const runId = mergedOptions?.runId || this.#mastra?.generateId() || randomUUID();
|
|
19019
|
+
const resourceIdFromContext = requestContextToUse.get(MASTRA_RESOURCE_ID_KEY);
|
|
19020
|
+
const threadIdFromContext = requestContextToUse.get(MASTRA_THREAD_ID_KEY);
|
|
19021
|
+
const threadId = threadIdFromContext || (typeof mergedOptions?.memory?.thread === "string" ? mergedOptions?.memory?.thread : mergedOptions?.memory?.thread?.id);
|
|
19022
|
+
const resourceId = resourceIdFromContext || mergedOptions?.memory?.resource;
|
|
19023
|
+
return await networkLoop({
|
|
19024
|
+
networkName: this.name,
|
|
19025
|
+
requestContext: requestContextToUse,
|
|
19026
|
+
runId,
|
|
19027
|
+
routingAgent: this,
|
|
19028
|
+
routingAgentOptions: {
|
|
19029
|
+
modelSettings: mergedOptions?.modelSettings,
|
|
19030
|
+
memory: mergedOptions?.memory
|
|
19031
|
+
},
|
|
19032
|
+
generateId: (context) => this.#mastra?.generateId(context) || randomUUID(),
|
|
19033
|
+
maxIterations: mergedOptions?.maxSteps || 1,
|
|
19034
|
+
messages,
|
|
19035
|
+
threadId,
|
|
19036
|
+
resourceId,
|
|
19037
|
+
validation: mergedOptions?.completion,
|
|
19038
|
+
routing: mergedOptions?.routing,
|
|
19039
|
+
onIterationComplete: mergedOptions?.onIterationComplete,
|
|
19040
|
+
autoResumeSuspendedTools: mergedOptions?.autoResumeSuspendedTools,
|
|
19041
|
+
mastra: this.#mastra,
|
|
19042
|
+
structuredOutput: mergedOptions?.structuredOutput
|
|
19043
|
+
});
|
|
19044
|
+
}
|
|
18521
19045
|
/**
|
|
18522
|
-
*
|
|
19046
|
+
* Resumes a suspended network loop where multiple agents can collaborate to handle messages.
|
|
18523
19047
|
* The routing agent delegates tasks to appropriate sub-agents based on the conversation.
|
|
18524
19048
|
*
|
|
18525
19049
|
* @experimental
|
|
18526
19050
|
*
|
|
18527
19051
|
* @example
|
|
18528
19052
|
* ```typescript
|
|
18529
|
-
* const result = await agent.
|
|
19053
|
+
* const result = await agent.resumeNetwork({ approved: true }, {
|
|
19054
|
+
* runId: 'previous-run-id',
|
|
18530
19055
|
* memory: {
|
|
18531
19056
|
* thread: 'user-123',
|
|
18532
19057
|
* resource: 'my-app'
|
|
@@ -18539,7 +19064,8 @@ var Agent = class extends MastraBase {
|
|
|
18539
19064
|
* }
|
|
18540
19065
|
* ```
|
|
18541
19066
|
*/
|
|
18542
|
-
async
|
|
19067
|
+
async resumeNetwork(resumeData, options) {
|
|
19068
|
+
const runId = options.runId;
|
|
18543
19069
|
const requestContextToUse = options?.requestContext || new RequestContext();
|
|
18544
19070
|
const defaultNetworkOptions = await this.getDefaultNetworkOptions({ requestContext: requestContextToUse });
|
|
18545
19071
|
const mergedOptions = {
|
|
@@ -18549,7 +19075,6 @@ var Agent = class extends MastraBase {
|
|
|
18549
19075
|
routing: { ...defaultNetworkOptions?.routing, ...options?.routing },
|
|
18550
19076
|
completion: { ...defaultNetworkOptions?.completion, ...options?.completion }
|
|
18551
19077
|
};
|
|
18552
|
-
const runId = mergedOptions?.runId || this.#mastra?.generateId() || randomUUID();
|
|
18553
19078
|
const resourceIdFromContext = requestContextToUse.get(MASTRA_RESOURCE_ID_KEY);
|
|
18554
19079
|
const threadIdFromContext = requestContextToUse.get(MASTRA_THREAD_ID_KEY);
|
|
18555
19080
|
const threadId = threadIdFromContext || (typeof mergedOptions?.memory?.thread === "string" ? mergedOptions?.memory?.thread : mergedOptions?.memory?.thread?.id);
|
|
@@ -18563,17 +19088,55 @@ var Agent = class extends MastraBase {
|
|
|
18563
19088
|
modelSettings: mergedOptions?.modelSettings,
|
|
18564
19089
|
memory: mergedOptions?.memory
|
|
18565
19090
|
},
|
|
18566
|
-
generateId: () => this.#mastra?.generateId() || randomUUID(),
|
|
19091
|
+
generateId: (context) => this.#mastra?.generateId(context) || randomUUID(),
|
|
18567
19092
|
maxIterations: mergedOptions?.maxSteps || 1,
|
|
18568
|
-
messages,
|
|
19093
|
+
messages: [],
|
|
18569
19094
|
threadId,
|
|
18570
19095
|
resourceId,
|
|
19096
|
+
resumeData,
|
|
18571
19097
|
validation: mergedOptions?.completion,
|
|
18572
19098
|
routing: mergedOptions?.routing,
|
|
18573
19099
|
onIterationComplete: mergedOptions?.onIterationComplete,
|
|
18574
|
-
|
|
19100
|
+
autoResumeSuspendedTools: mergedOptions?.autoResumeSuspendedTools,
|
|
19101
|
+
mastra: this.#mastra
|
|
18575
19102
|
});
|
|
18576
19103
|
}
|
|
19104
|
+
/**
|
|
19105
|
+
* Approves a pending network tool call and resumes execution.
|
|
19106
|
+
* Used when `tool.requireApproval` is enabled to allow the agent to proceed with a tool call.
|
|
19107
|
+
*
|
|
19108
|
+
* @example
|
|
19109
|
+
* ```typescript
|
|
19110
|
+
* const stream = await agent.approveNetworkToolCall({
|
|
19111
|
+
* runId: 'pending-run-id'
|
|
19112
|
+
* });
|
|
19113
|
+
*
|
|
19114
|
+
* for await (const chunk of stream) {
|
|
19115
|
+
* console.log(chunk);
|
|
19116
|
+
* }
|
|
19117
|
+
* ```
|
|
19118
|
+
*/
|
|
19119
|
+
async approveNetworkToolCall(options) {
|
|
19120
|
+
return this.resumeNetwork({ approved: true }, options);
|
|
19121
|
+
}
|
|
19122
|
+
/**
|
|
19123
|
+
* Declines a pending network tool call and resumes execution.
|
|
19124
|
+
* Used when `tool.requireApproval` is enabled to allow the agent to proceed with a tool call.
|
|
19125
|
+
*
|
|
19126
|
+
* @example
|
|
19127
|
+
* ```typescript
|
|
19128
|
+
* const stream = await agent.declineNetworkToolCall({
|
|
19129
|
+
* runId: 'pending-run-id'
|
|
19130
|
+
* });
|
|
19131
|
+
*
|
|
19132
|
+
* for await (const chunk of stream) {
|
|
19133
|
+
* console.log(chunk);
|
|
19134
|
+
* }
|
|
19135
|
+
* ```
|
|
19136
|
+
*/
|
|
19137
|
+
async declineNetworkToolCall(options) {
|
|
19138
|
+
return this.resumeNetwork({ approved: false }, options);
|
|
19139
|
+
}
|
|
18577
19140
|
async generate(messages, options) {
|
|
18578
19141
|
const defaultOptions = await this.getDefaultOptions({
|
|
18579
19142
|
requestContext: options?.requestContext
|
|
@@ -18693,19 +19256,6 @@ var Agent = class extends MastraBase {
|
|
|
18693
19256
|
}
|
|
18694
19257
|
return result.result;
|
|
18695
19258
|
}
|
|
18696
|
-
/**
|
|
18697
|
-
* Resumes a previously suspended stream execution.
|
|
18698
|
-
* Used to continue execution after a suspension point (e.g., tool approval, workflow suspend).
|
|
18699
|
-
*
|
|
18700
|
-
* @example
|
|
18701
|
-
* ```typescript
|
|
18702
|
-
* // Resume after suspension
|
|
18703
|
-
* const stream = await agent.resumeStream(
|
|
18704
|
-
* { approved: true },
|
|
18705
|
-
* { runId: 'previous-run-id' }
|
|
18706
|
-
* );
|
|
18707
|
-
* ```
|
|
18708
|
-
*/
|
|
18709
19259
|
async resumeStream(resumeData, streamOptions) {
|
|
18710
19260
|
const defaultOptions = await this.getDefaultOptions({
|
|
18711
19261
|
requestContext: streamOptions?.requestContext
|
|
@@ -20273,35 +20823,71 @@ var TokenLimiterProcessor = class _TokenLimiterProcessor {
|
|
|
20273
20823
|
* Process input messages to limit them to the configured token limit.
|
|
20274
20824
|
* This filters historical messages to fit within the token budget,
|
|
20275
20825
|
* prioritizing the most recent messages.
|
|
20826
|
+
*
|
|
20827
|
+
* Uses messageList.get.all.db() to access ALL messages (memory + input),
|
|
20828
|
+
* not just the input messages passed in the messages parameter.
|
|
20829
|
+
* System messages are accessed via args.systemMessages (they're stored separately).
|
|
20830
|
+
* Removes filtered messages directly from messageList and returns it.
|
|
20276
20831
|
*/
|
|
20277
20832
|
async processInput(args) {
|
|
20278
|
-
const {
|
|
20833
|
+
const { messageList, systemMessages: coreSystemMessages } = args;
|
|
20834
|
+
const messages = messageList?.get.all.db() ?? args.messages;
|
|
20279
20835
|
const limit = this.maxTokens;
|
|
20280
20836
|
if (!messages || messages.length === 0) {
|
|
20281
|
-
|
|
20837
|
+
throw new TripWire("TokenLimiterProcessor: No messages to process. Cannot send LLM a request with no messages.", {
|
|
20838
|
+
retry: false
|
|
20839
|
+
});
|
|
20282
20840
|
}
|
|
20283
|
-
const systemMessages = messages.filter((msg) => msg.role === "system");
|
|
20284
|
-
const nonSystemMessages = messages.filter((msg) => msg.role !== "system");
|
|
20285
20841
|
let systemTokens = 0;
|
|
20286
|
-
|
|
20287
|
-
|
|
20842
|
+
if (coreSystemMessages && coreSystemMessages.length > 0) {
|
|
20843
|
+
for (const msg of coreSystemMessages) {
|
|
20844
|
+
systemTokens += this.countCoreSystemMessageTokens(msg);
|
|
20845
|
+
}
|
|
20288
20846
|
}
|
|
20847
|
+
const nonSystemMessages = messages;
|
|
20289
20848
|
if (systemTokens + _TokenLimiterProcessor.TOKENS_PER_CONVERSATION >= limit) {
|
|
20290
|
-
|
|
20849
|
+
throw new TripWire(
|
|
20850
|
+
"TokenLimiterProcessor: System messages alone exceed token limit. Requests cannot be completed by removing system messages.",
|
|
20851
|
+
{ retry: false, metadata: { systemTokens, limit } }
|
|
20852
|
+
);
|
|
20291
20853
|
}
|
|
20292
20854
|
const remainingBudget = limit - systemTokens - _TokenLimiterProcessor.TOKENS_PER_CONVERSATION;
|
|
20293
|
-
const
|
|
20855
|
+
const messagesToKeep = [];
|
|
20294
20856
|
let currentTokens = 0;
|
|
20295
20857
|
for (let i = nonSystemMessages.length - 1; i >= 0; i--) {
|
|
20296
20858
|
const message = nonSystemMessages[i];
|
|
20297
20859
|
if (!message) continue;
|
|
20298
20860
|
const messageTokens = this.countInputMessageTokens(message);
|
|
20299
20861
|
if (currentTokens + messageTokens <= remainingBudget) {
|
|
20300
|
-
|
|
20862
|
+
messagesToKeep.unshift(message);
|
|
20301
20863
|
currentTokens += messageTokens;
|
|
20302
20864
|
}
|
|
20303
20865
|
}
|
|
20304
|
-
|
|
20866
|
+
if (messageList) {
|
|
20867
|
+
const keepIds = new Set(messagesToKeep.map((m) => m.id));
|
|
20868
|
+
const idsToRemove = messages.filter((m) => !keepIds.has(m.id)).map((m) => m.id);
|
|
20869
|
+
if (idsToRemove.length > 0) {
|
|
20870
|
+
messageList.removeByIds(idsToRemove);
|
|
20871
|
+
}
|
|
20872
|
+
return messageList;
|
|
20873
|
+
}
|
|
20874
|
+
return messagesToKeep;
|
|
20875
|
+
}
|
|
20876
|
+
/**
|
|
20877
|
+
* Count tokens for a system message (CoreMessageV4 from args.systemMessages).
|
|
20878
|
+
* This method only accepts system messages with string content and will throw otherwise.
|
|
20879
|
+
*/
|
|
20880
|
+
countCoreSystemMessageTokens(message) {
|
|
20881
|
+
if (message.role !== "system") {
|
|
20882
|
+
throw new Error(
|
|
20883
|
+
`countCoreSystemMessageTokens can only be used with system messages, received role: ${message.role}`
|
|
20884
|
+
);
|
|
20885
|
+
}
|
|
20886
|
+
if (typeof message.content !== "string") {
|
|
20887
|
+
throw new Error("countCoreSystemMessageTokens: System message content must be a string");
|
|
20888
|
+
}
|
|
20889
|
+
const tokenString = message.role + message.content;
|
|
20890
|
+
return this.encoder.encode(tokenString).length + _TokenLimiterProcessor.TOKENS_PER_MESSAGE;
|
|
20305
20891
|
}
|
|
20306
20892
|
/**
|
|
20307
20893
|
* Count tokens for an input message, including overhead for message structure
|
|
@@ -21209,6 +21795,9 @@ var SemanticRecall = class {
|
|
|
21209
21795
|
embedderOptions;
|
|
21210
21796
|
// xxhash-wasm hasher instance (initialized as a promise)
|
|
21211
21797
|
hasher = xxhash();
|
|
21798
|
+
// Cache for index dimension validation (per-process)
|
|
21799
|
+
// Prevents redundant API calls when index already validated
|
|
21800
|
+
indexValidationCache = /* @__PURE__ */ new Map();
|
|
21212
21801
|
constructor(options) {
|
|
21213
21802
|
this.storage = options.storage;
|
|
21214
21803
|
this.vector = options.vector;
|
|
@@ -21434,17 +22023,19 @@ ${result}
|
|
|
21434
22023
|
}
|
|
21435
22024
|
/**
|
|
21436
22025
|
* Ensure vector index exists with correct dimensions
|
|
22026
|
+
* Uses in-memory cache to avoid redundant validation calls
|
|
21437
22027
|
*/
|
|
21438
22028
|
async ensureVectorIndex(indexName, dimension) {
|
|
21439
|
-
const
|
|
21440
|
-
|
|
21441
|
-
|
|
21442
|
-
await this.vector.createIndex({
|
|
21443
|
-
indexName,
|
|
21444
|
-
dimension,
|
|
21445
|
-
metric: "cosine"
|
|
21446
|
-
});
|
|
22029
|
+
const cached = this.indexValidationCache.get(indexName);
|
|
22030
|
+
if (cached?.dimension === dimension) {
|
|
22031
|
+
return;
|
|
21447
22032
|
}
|
|
22033
|
+
await this.vector.createIndex({
|
|
22034
|
+
indexName,
|
|
22035
|
+
dimension,
|
|
22036
|
+
metric: "cosine"
|
|
22037
|
+
});
|
|
22038
|
+
this.indexValidationCache.set(indexName, { dimension });
|
|
21448
22039
|
}
|
|
21449
22040
|
/**
|
|
21450
22041
|
* Process output messages to create embeddings for messages being saved
|
|
@@ -21822,7 +22413,11 @@ https://mastra.ai/en/docs/memory/overview`
|
|
|
21822
22413
|
saveThread = true
|
|
21823
22414
|
}) {
|
|
21824
22415
|
const thread = {
|
|
21825
|
-
id: threadId || this.generateId(
|
|
22416
|
+
id: threadId || this.generateId({
|
|
22417
|
+
idType: "thread",
|
|
22418
|
+
source: "memory",
|
|
22419
|
+
resourceId
|
|
22420
|
+
}),
|
|
21826
22421
|
title: title || `New Thread ${(/* @__PURE__ */ new Date()).toISOString()}`,
|
|
21827
22422
|
resourceId,
|
|
21828
22423
|
createdAt: /* @__PURE__ */ new Date(),
|
|
@@ -21848,10 +22443,11 @@ https://mastra.ai/en/docs/memory/overview`
|
|
|
21848
22443
|
}
|
|
21849
22444
|
/**
|
|
21850
22445
|
* Generates a unique identifier
|
|
22446
|
+
* @param context - Optional context information for deterministic ID generation
|
|
21851
22447
|
* @returns A unique string ID
|
|
21852
22448
|
*/
|
|
21853
|
-
generateId() {
|
|
21854
|
-
return this.#mastra?.generateId() || crypto.randomUUID();
|
|
22449
|
+
generateId(context) {
|
|
22450
|
+
return this.#mastra?.generateId(context) || crypto.randomUUID();
|
|
21855
22451
|
}
|
|
21856
22452
|
/**
|
|
21857
22453
|
* Get input processors for this memory instance
|
|
@@ -22181,7 +22777,7 @@ var MockMemory = class extends MastraMemory {
|
|
|
22181
22777
|
const schema = workingMemoryConfig.schema;
|
|
22182
22778
|
let convertedSchema;
|
|
22183
22779
|
if (isZodObject(schema)) {
|
|
22184
|
-
convertedSchema = zodToJsonSchema(schema);
|
|
22780
|
+
convertedSchema = zodToJsonSchema$1(schema);
|
|
22185
22781
|
} else {
|
|
22186
22782
|
convertedSchema = schema;
|
|
22187
22783
|
}
|
|
@@ -22243,6 +22839,6 @@ var MockMemory = class extends MastraMemory {
|
|
|
22243
22839
|
}
|
|
22244
22840
|
};
|
|
22245
22841
|
|
|
22246
|
-
export {
|
|
22247
|
-
//# sourceMappingURL=chunk-
|
|
22248
|
-
//# sourceMappingURL=chunk-
|
|
22842
|
+
export { Agent, BatchPartsProcessor, ChunkFrom, DefaultExecutionEngine, EventEmitterPubSub, ExecutionEngine, FilePartSchema, ImagePartSchema, LanguageDetector, MastraAgentNetworkStream, MastraMemory, MastraModelOutput, MastraScorer, MemoryProcessor, MessageContentSchema, MessageHistory, MessagePartSchema, MockMemory, ModerationProcessor, PIIDetector, ProcessorInputPhaseSchema, ProcessorInputStepPhaseSchema, ProcessorMessageContentSchema, ProcessorMessageSchema, ProcessorOutputResultPhaseSchema, ProcessorOutputStepPhaseSchema, ProcessorOutputStreamPhaseSchema, ProcessorRunner, ProcessorState, ProcessorStepInputSchema, ProcessorStepOutputSchema, ProcessorStepSchema, PromptInjectionDetector, ReasoningPartSchema, Run, SemanticRecall, SourcePartSchema, StepStartPartSchema, StructuredOutputProcessor, SystemPromptScrubber, TextPartSchema, TokenLimiterProcessor, ToolCallFilter, ToolInvocationPartSchema, TripWire, UnicodeNormalizer, WORKING_MEMORY_END_TAG, WORKING_MEMORY_START_TAG, Workflow, WorkflowRunOutput, WorkingMemory, augmentWithInit, cloneStep, cloneWorkflow, convertFullStreamChunkToMastra, convertFullStreamChunkToUIMessageStream, convertMastraChunkToAISDKv5, createDeprecationProxy, createScorer, createStep, createTimeTravelExecutionParams, createWorkflow, extractWorkingMemoryContent, extractWorkingMemoryTags, formatCheckFeedback, formatCompletionFeedback, formatValidationFeedback, generateFinalResult, generateStructuredFinalResult, getResumeLabelsByStepId, getStepIds, getStepResult, getZodErrors, globalEmbeddingCache, hydrateSerializedStepErrors, isProcessor, isProcessorWorkflow, isSupportedLanguageModel, loop, mapVariable, memoryDefaultOptions, parseMemoryRequestContext, removeWorkingMemoryTags, resolveThreadIdFromArgs, runChecks, runCompletionScorers, runCountDeprecationMessage, runDefaultCompletionCheck, runValidation, supportedLanguageModelSpecifications, tryGenerateWithJsonFallback, tryStreamWithJsonFallback, validateStepInput, validateStepResumeData, validateStepStateData, validateStepSuspendData };
|
|
22843
|
+
//# sourceMappingURL=chunk-UVOQLIWL.js.map
|
|
22844
|
+
//# sourceMappingURL=chunk-UVOQLIWL.js.map
|