@mastra/server 1.79.0-alpha.10 → 1.79.0-alpha.12
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/dist/{a2a-CHBSYHxu.js → a2a-BqLB3McP.js} +17 -16
- package/dist/a2a-BqLB3McP.js.map +1 -0
- package/dist/{a2a-B465DD1u.cjs → a2a-Uood_0DN.cjs} +19 -18
- package/dist/a2a-Uood_0DN.cjs.map +1 -0
- package/dist/agent-builder-CuBD1tpv.cjs +728 -0
- package/dist/agent-builder-CuBD1tpv.cjs.map +1 -0
- package/dist/agent-builder-VhM8ADW-.js +627 -0
- package/dist/agent-builder-VhM8ADW-.js.map +1 -0
- package/dist/{agents-X1E7fW3p.js → agents-BHLTMBff.js} +2 -2
- package/dist/{agents-X1E7fW3p.js.map → agents-BHLTMBff.js.map} +1 -1
- package/dist/agents-BOWEUKyV.cjs +3127 -0
- package/dist/agents-BOWEUKyV.cjs.map +1 -0
- package/dist/agents-DRQ3ScbX.js +2828 -0
- package/dist/agents-DRQ3ScbX.js.map +1 -0
- package/dist/{agents-DoNMSCMt.cjs → agents-T-OIM9IK.cjs} +2 -2
- package/dist/{agents-DoNMSCMt.cjs.map → agents-T-OIM9IK.cjs.map} +1 -1
- package/dist/{api-schema-manifest-CWRIJP-B.js → api-schema-manifest-CI90M4sX.js} +3 -3
- package/dist/{api-schema-manifest-CWRIJP-B.js.map → api-schema-manifest-CI90M4sX.js.map} +1 -1
- package/dist/{api-schema-manifest-DUseI2VG.cjs → api-schema-manifest-DIlNfbyw.cjs} +4 -4
- package/dist/{api-schema-manifest-DUseI2VG.cjs.map → api-schema-manifest-DIlNfbyw.cjs.map} +1 -1
- package/dist/{background-tasks-CabImVak.cjs → background-tasks-B3VAKTJh.cjs} +3 -3
- package/dist/{background-tasks-CabImVak.cjs.map → background-tasks-B3VAKTJh.cjs.map} +1 -1
- package/dist/{background-tasks-oBaLtnCn.js → background-tasks-Du2zYOPl.js} +2 -2
- package/dist/{background-tasks-oBaLtnCn.js.map → background-tasks-Du2zYOPl.js.map} +1 -1
- package/dist/{builder-registry-DOkLe8ES.js → builder-registry-DLdu9bWH.js} +3 -3
- package/dist/{builder-registry-DOkLe8ES.js.map → builder-registry-DLdu9bWH.js.map} +1 -1
- package/dist/{builder-registry-D0frV8lQ.cjs → builder-registry-DaFAaMTf.cjs} +3 -3
- package/dist/{builder-registry-D0frV8lQ.cjs.map → builder-registry-DaFAaMTf.cjs.map} +1 -1
- package/dist/{channels-CBIopVWd.cjs → channels-BnVRmnzK.cjs} +6 -3
- package/dist/{channels-CBIopVWd.cjs.map → channels-BnVRmnzK.cjs.map} +1 -1
- package/dist/{channels-BOxgHvzI.js → channels-Db-4pXVZ.js} +6 -3
- package/dist/{channels-BOxgHvzI.js.map → channels-Db-4pXVZ.js.map} +1 -1
- package/dist/conversations-8BWryNlF.js +165 -0
- package/dist/conversations-8BWryNlF.js.map +1 -0
- package/dist/conversations-C5MkQBB8.cjs +194 -0
- package/dist/conversations-C5MkQBB8.cjs.map +1 -0
- package/dist/{conversations-Bj5TLNqF.cjs → conversations-DasqEDCF.cjs} +3 -3
- package/dist/{conversations-Bj5TLNqF.cjs.map → conversations-DasqEDCF.cjs.map} +1 -1
- package/dist/{dist-9c3PXXpk.cjs → dist-B-bEVWlJ.cjs} +4733 -1251
- package/dist/dist-B-bEVWlJ.cjs.map +1 -0
- package/dist/dist-B3kC8Yd0.cjs +3 -0
- package/dist/{dist-CQ3FSKT-.cjs → dist-B9ery9Zw.cjs} +38 -35
- package/dist/{dist-CQ3FSKT-.cjs.map → dist-B9ery9Zw.cjs.map} +1 -1
- package/dist/{dist-BxMmGD3n.js → dist-BBOnrL_A.js} +10 -12
- package/dist/{dist-BxMmGD3n.js.map → dist-BBOnrL_A.js.map} +1 -1
- package/dist/{dist-DOWsEmo6.js → dist-BIrQLUV9.js} +20 -20
- package/dist/{dist-DOWsEmo6.js.map → dist-BIrQLUV9.js.map} +1 -1
- package/dist/dist-BM9J-PTK.js +1 -0
- package/dist/{dist-DC1Pewf5.cjs → dist-Bo3GdQwf.cjs} +21 -21
- package/dist/{dist-DC1Pewf5.cjs.map → dist-Bo3GdQwf.cjs.map} +1 -1
- package/dist/{dist-BwYL7Ykb.js → dist-CREG82cy.js} +37 -34
- package/dist/{dist-BwYL7Ykb.js.map → dist-CREG82cy.js.map} +1 -1
- package/dist/{dist-rDRetJVY.cjs → dist-CeTLA-e5.cjs} +2 -3
- package/dist/{dist-rDRetJVY.cjs.map → dist-CeTLA-e5.cjs.map} +1 -1
- package/dist/{dist-CBRJax5e.js → dist-DLld1qjf.js} +25 -31
- package/dist/{dist-CBRJax5e.js.map → dist-DLld1qjf.js.map} +1 -1
- package/dist/{dist-B_bet8uz.js → dist-DjkPkAzV.js} +2 -3
- package/dist/{dist-B_bet8uz.js.map → dist-DjkPkAzV.js.map} +1 -1
- package/dist/{dist-UKEksCGq.cjs → dist-DsrJXwic.cjs} +11 -13
- package/dist/{dist-UKEksCGq.cjs.map → dist-DsrJXwic.cjs.map} +1 -1
- package/dist/{dist-DGCnbhNe.js → dist-k77XQGUn.js} +4493 -1043
- package/dist/dist-k77XQGUn.js.map +1 -0
- package/dist/{dist-3FPW9nVj.cjs → dist-lT2rqyY9.cjs} +26 -32
- package/dist/{dist-3FPW9nVj.cjs.map → dist-lT2rqyY9.cjs.map} +1 -1
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/assets/SOURCE_MAP.json +1 -1
- package/dist/{dynamic-workflows-Rr_6ac1y.js → dynamic-workflows-CTUO0SFu.js} +3 -3
- package/dist/{dynamic-workflows-Rr_6ac1y.js.map → dynamic-workflows-CTUO0SFu.js.map} +1 -1
- package/dist/{dynamic-workflows-DXlkr-jK.cjs → dynamic-workflows-HwPX3mcf.cjs} +3 -3
- package/dist/{dynamic-workflows-DXlkr-jK.cjs.map → dynamic-workflows-HwPX3mcf.cjs.map} +1 -1
- package/dist/{editor-builder-BclcHxN6.cjs → editor-builder-BDtiWw0f.cjs} +2 -2
- package/dist/{editor-builder-BclcHxN6.cjs.map → editor-builder-BDtiWw0f.cjs.map} +1 -1
- package/dist/{editor-builder-D16kc1P6.js → editor-builder-ClFlGXoX.js} +4 -4
- package/dist/{editor-builder-D16kc1P6.js.map → editor-builder-ClFlGXoX.js.map} +1 -1
- package/dist/{editor-builder-s9WqPJgA.js → editor-builder-DnLCfqnY.js} +2 -2
- package/dist/{editor-builder-s9WqPJgA.js.map → editor-builder-DnLCfqnY.js.map} +1 -1
- package/dist/{editor-builder-DXHiPX1A.cjs → editor-builder-DtpP1FtW.cjs} +5 -5
- package/dist/{editor-builder-DXHiPX1A.cjs.map → editor-builder-DtpP1FtW.cjs.map} +1 -1
- package/dist/{helpers-ElhPeCSK.cjs → helpers-CAcEhq38.cjs} +21 -17
- package/dist/{helpers-ElhPeCSK.cjs.map → helpers-CAcEhq38.cjs.map} +1 -1
- package/dist/{helpers-DLhX1fqc.js → helpers-vrqddDd5.js} +21 -17
- package/dist/{helpers-DLhX1fqc.js.map → helpers-vrqddDd5.js.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/logs-CiSw7r0s.cjs +119 -0
- package/dist/logs-CiSw7r0s.cjs.map +1 -0
- package/dist/logs-CxfPk-iL.js +96 -0
- package/dist/logs-CxfPk-iL.js.map +1 -0
- package/dist/mcp-CWDfSu7w.js +474 -0
- package/dist/mcp-CWDfSu7w.js.map +1 -0
- package/dist/mcp-CWGJRqkC.cjs +563 -0
- package/dist/mcp-CWGJRqkC.cjs.map +1 -0
- package/dist/{mcp-DzpwLXEY.js → mcp-Drqt0GqD.js} +79 -4
- package/dist/mcp-Drqt0GqD.js.map +1 -0
- package/dist/{mcp-ShaKO7gA.cjs → mcp-ziWVk7Ol.cjs} +126 -3
- package/dist/mcp-ziWVk7Ol.cjs.map +1 -0
- package/dist/memory-BHtTSzvJ.js +1739 -0
- package/dist/memory-BHtTSzvJ.js.map +1 -0
- package/dist/memory-CwwkVDh1.cjs +1906 -0
- package/dist/memory-CwwkVDh1.cjs.map +1 -0
- package/dist/observability-BBMCMeT-.cjs +502 -0
- package/dist/observability-BBMCMeT-.cjs.map +1 -0
- package/dist/observability-ZRgRcvoX.js +431 -0
- package/dist/observability-ZRgRcvoX.js.map +1 -0
- package/dist/{observability-new-endpoints-BU8JYPfh.js → observability-new-endpoints-fjoZzEtk.js} +10 -9
- package/dist/{observability-new-endpoints-BU8JYPfh.js.map → observability-new-endpoints-fjoZzEtk.js.map} +1 -1
- package/dist/{observability-new-endpoints-AMp9bnMV.cjs → observability-new-endpoints-tG3-odLa.cjs} +11 -10
- package/dist/observability-new-endpoints-tG3-odLa.cjs.map +1 -0
- package/dist/plans-CiPgWBhO.cjs +68 -0
- package/dist/plans-CiPgWBhO.cjs.map +1 -0
- package/dist/plans-DCepEY7n.js +57 -0
- package/dist/plans-DCepEY7n.js.map +1 -0
- package/dist/{probe-image-size-DBGjhUtJ.cjs → probe-image-size-Alv3gwKl.cjs} +194 -184
- package/dist/probe-image-size-Alv3gwKl.cjs.map +1 -0
- package/dist/{probe-image-size-Dmoxv93t.js → probe-image-size-BdfbUHxx.js} +158 -148
- package/dist/probe-image-size-BdfbUHxx.js.map +1 -0
- package/dist/responses-4FwMNxoJ.js +628 -0
- package/dist/responses-4FwMNxoJ.js.map +1 -0
- package/dist/responses-CCRijwDF.cjs +651 -0
- package/dist/responses-CCRijwDF.cjs.map +1 -0
- package/dist/{responses-CKNdSRkS.cjs → responses-CfcIc53b.cjs} +2 -2
- package/dist/{responses-CKNdSRkS.cjs.map → responses-CfcIc53b.cjs.map} +1 -1
- package/dist/{rolldown-runtime-Bd6kNlEP.cjs → rolldown-runtime-BwC_XMyb.cjs} +2 -2
- package/dist/{rolldown-runtime-maW3aOIk.js → rolldown-runtime-D3Hj5m0v.js} +2 -2
- package/dist/{route-builder-BNZs643f.cjs → route-builder-B2Qhhd7C.cjs} +52 -66
- package/dist/route-builder-B2Qhhd7C.cjs.map +1 -0
- package/dist/{route-builder-BfQYtclb.js → route-builder-CjkWxv4E.js} +51 -65
- package/dist/route-builder-CjkWxv4E.js.map +1 -0
- package/dist/{routes-rwufkyUe.js → routes-BC20mdNN.js} +30 -26
- package/dist/routes-BC20mdNN.js.map +1 -0
- package/dist/{routes-Dl6_kWm7.js → routes-CKfXiwRc.js} +5 -3
- package/dist/routes-CKfXiwRc.js.map +1 -0
- package/dist/{routes-DPojsNf1.cjs → routes-DGLJyqjD.cjs} +203 -199
- package/dist/routes-DGLJyqjD.cjs.map +1 -0
- package/dist/{routes-BULZI-PU.cjs → routes-jXksmX9G.cjs} +5 -3
- package/dist/routes-jXksmX9G.cjs.map +1 -0
- package/dist/{schedules-Bj-giFbc.cjs → schedules-GokZKBYg.cjs} +6 -4
- package/dist/schedules-GokZKBYg.cjs.map +1 -0
- package/dist/{schedules-BQYgaz66.js → schedules-_3zPKyqm.js} +5 -3
- package/dist/schedules-_3zPKyqm.js.map +1 -0
- package/dist/{schema-e0VHpMt0-C0452jOk.cjs → schema-CzbEIyhE-20gGIWkz.cjs} +83 -88
- package/dist/schema-CzbEIyhE-20gGIWkz.cjs.map +1 -0
- package/dist/{schema-e0VHpMt0-CVP5Hnxy.js → schema-CzbEIyhE-BsMcj9Ws.js} +82 -87
- package/dist/schema-CzbEIyhE-BsMcj9Ws.js.map +1 -0
- package/dist/scores-D9UgETt_.js +288 -0
- package/dist/scores-D9UgETt_.js.map +1 -0
- package/dist/scores-DRdtS7NT.cjs +329 -0
- package/dist/scores-DRdtS7NT.cjs.map +1 -0
- package/dist/server/a2a/store.cjs +1 -1
- package/dist/server/auth/index.cjs +2 -2
- package/dist/server/auth/index.js +1 -1
- package/dist/server/browser-stream/index.cjs +9 -11
- package/dist/server/browser-stream/index.cjs.map +1 -1
- package/dist/server/browser-stream/index.js +8 -10
- package/dist/server/browser-stream/index.js.map +1 -1
- package/dist/server/handlers/a2a.cjs +2 -2
- package/dist/server/handlers/a2a.js +1 -2
- package/dist/server/handlers/agent-builder.cjs +18 -648
- package/dist/server/handlers/agent-builder.js +1 -627
- package/dist/server/handlers/agent-controller.cjs +5 -5
- package/dist/server/handlers/agent-controller.cjs.map +1 -1
- package/dist/server/handlers/agent-controller.js +11 -9
- package/dist/server/handlers/agent-controller.js.map +1 -1
- package/dist/server/handlers/agent-versions.cjs +15 -8
- package/dist/server/handlers/agent-versions.cjs.map +1 -1
- package/dist/server/handlers/agent-versions.js +14 -7
- package/dist/server/handlers/agent-versions.js.map +1 -1
- package/dist/server/handlers/agents.cjs +51 -2860
- package/dist/server/handlers/agents.js +1 -2806
- package/dist/server/handlers/auth.cjs +14 -12
- package/dist/server/handlers/auth.cjs.map +1 -1
- package/dist/server/handlers/auth.js +20 -16
- package/dist/server/handlers/auth.js.map +1 -1
- package/dist/server/handlers/author-enrichment.cjs +1 -1
- package/dist/server/handlers/authorship.cjs +1 -1
- package/dist/server/handlers/authorship.cjs.map +1 -1
- package/dist/server/handlers/background-tasks.cjs +2 -2
- package/dist/server/handlers/background-tasks.js +1 -2
- package/dist/server/handlers/builder-registry.cjs +2 -2
- package/dist/server/handlers/builder-registry.js +1 -2
- package/dist/server/handlers/channels.cjs +2 -2
- package/dist/server/handlers/channels.js +1 -2
- package/dist/server/handlers/conversations.cjs +6 -171
- package/dist/server/handlers/conversations.js +1 -162
- package/dist/server/handlers/datasets.cjs +2 -2
- package/dist/server/handlers/datasets.cjs.map +1 -1
- package/dist/server/handlers/datasets.js +1 -1
- package/dist/server/handlers/dynamic-workflows.cjs +2 -2
- package/dist/server/handlers/dynamic-workflows.js +1 -2
- package/dist/server/handlers/editor-builder.cjs +2 -2
- package/dist/server/handlers/editor-builder.js +1 -2
- package/dist/server/handlers/error.cjs +18 -13
- package/dist/server/handlers/error.cjs.map +1 -1
- package/dist/server/handlers/error.js +17 -12
- package/dist/server/handlers/error.js.map +1 -1
- package/dist/server/handlers/favorites-enrichment.cjs +2 -2
- package/dist/server/handlers/favorites-enrichment.js +1 -1
- package/dist/server/handlers/gateway-memory-client.cjs +1 -1
- package/dist/server/handlers/logs.cjs +5 -104
- package/dist/server/handlers/logs.js +1 -96
- package/dist/server/handlers/mcp-client-versions.cjs +15 -8
- package/dist/server/handlers/mcp-client-versions.cjs.map +1 -1
- package/dist/server/handlers/mcp-client-versions.js +14 -7
- package/dist/server/handlers/mcp-client-versions.js.map +1 -1
- package/dist/server/handlers/mcp.cjs +16 -289
- package/dist/server/handlers/mcp.d.ts +219 -0
- package/dist/server/handlers/mcp.d.ts.map +1 -1
- package/dist/server/handlers/mcp.js +1 -274
- package/dist/server/handlers/memory.cjs +29 -1763
- package/dist/server/handlers/memory.js +1 -1731
- package/dist/server/handlers/observability-list-query-schemas.cjs +1 -1
- package/dist/server/handlers/observability-new-endpoints.cjs +2 -2
- package/dist/server/handlers/observability-new-endpoints.js +1 -2
- package/dist/server/handlers/observability-shared.cjs +2 -2
- package/dist/server/handlers/observability-shared.js +1 -1
- package/dist/server/handlers/observability-storage-schemas.cjs +1 -1
- package/dist/server/handlers/observability.cjs +14 -445
- package/dist/server/handlers/observability.js +3 -429
- package/dist/server/handlers/plans.cjs +3 -63
- package/dist/server/handlers/plans.js +1 -57
- package/dist/server/handlers/processor-providers.cjs +2 -2
- package/dist/server/handlers/processor-providers.cjs.map +1 -1
- package/dist/server/handlers/processor-providers.js +1 -1
- package/dist/server/handlers/processors.cjs +13 -15
- package/dist/server/handlers/processors.cjs.map +1 -1
- package/dist/server/handlers/processors.js +12 -14
- package/dist/server/handlers/processors.js.map +1 -1
- package/dist/server/handlers/prompt-block-versions.cjs +15 -8
- package/dist/server/handlers/prompt-block-versions.cjs.map +1 -1
- package/dist/server/handlers/prompt-block-versions.js +14 -7
- package/dist/server/handlers/prompt-block-versions.js.map +1 -1
- package/dist/server/handlers/responses.adapter.cjs +1 -1
- package/dist/server/handlers/responses.adapter.cjs.map +1 -1
- package/dist/server/handlers/responses.cjs +5 -632
- package/dist/server/handlers/responses.js +1 -624
- package/dist/server/handlers/responses.storage.cjs +2 -2
- package/dist/server/handlers/schedules-workflows-shim.cjs +1 -1
- package/dist/server/handlers/schedules.cjs +2 -2
- package/dist/server/handlers/schedules.d.ts +16 -0
- package/dist/server/handlers/schedules.d.ts.map +1 -1
- package/dist/server/handlers/schedules.js +1 -2
- package/dist/server/handlers/scorer-versions.cjs +15 -8
- package/dist/server/handlers/scorer-versions.cjs.map +1 -1
- package/dist/server/handlers/scorer-versions.js +14 -7
- package/dist/server/handlers/scorer-versions.js.map +1 -1
- package/dist/server/handlers/scores.cjs +8 -299
- package/dist/server/handlers/scores.js +1 -288
- package/dist/server/handlers/skills-sh-shared.cjs +1 -1
- package/dist/server/handlers/stored-agent-favorites.cjs +4 -4
- package/dist/server/handlers/stored-agent-favorites.js +3 -3
- package/dist/server/handlers/stored-agents.cjs +19 -13
- package/dist/server/handlers/stored-agents.cjs.map +1 -1
- package/dist/server/handlers/stored-agents.js +18 -12
- package/dist/server/handlers/stored-agents.js.map +1 -1
- package/dist/server/handlers/stored-mcp-clients.cjs +8 -6
- package/dist/server/handlers/stored-mcp-clients.cjs.map +1 -1
- package/dist/server/handlers/stored-mcp-clients.js +7 -5
- package/dist/server/handlers/stored-mcp-clients.js.map +1 -1
- package/dist/server/handlers/stored-prompt-blocks.cjs +3 -3
- package/dist/server/handlers/stored-prompt-blocks.js +2 -2
- package/dist/server/handlers/stored-scorers.cjs +3 -3
- package/dist/server/handlers/stored-scorers.js +2 -2
- package/dist/server/handlers/stored-skill-favorites.cjs +4 -4
- package/dist/server/handlers/stored-skill-favorites.js +3 -3
- package/dist/server/handlers/stored-skills.cjs +6 -5
- package/dist/server/handlers/stored-skills.cjs.map +1 -1
- package/dist/server/handlers/stored-skills.js +5 -4
- package/dist/server/handlers/stored-skills.js.map +1 -1
- package/dist/server/handlers/stored-workspaces.cjs +3 -3
- package/dist/server/handlers/stored-workspaces.js +2 -2
- package/dist/server/handlers/system.cjs +3 -3
- package/dist/server/handlers/system.cjs.map +1 -1
- package/dist/server/handlers/system.js +2 -2
- package/dist/server/handlers/test-utils.cjs +1 -1
- package/dist/server/handlers/tool-providers.cjs +2 -2
- package/dist/server/handlers/tool-providers.js +1 -1
- package/dist/server/handlers/tool-schema-overrides.cjs +1 -1
- package/dist/server/handlers/tools.cjs +7 -267
- package/dist/server/handlers/tools.js +1 -257
- package/dist/server/handlers/utils.cjs +2 -2
- package/dist/server/handlers/utils.js +1 -2
- package/dist/server/handlers/validate-agent-instructions.cjs +2 -2
- package/dist/server/handlers/validate-agent-instructions.js +1 -1
- package/dist/server/handlers/validate-avatar.cjs +2 -2
- package/dist/server/handlers/validate-avatar.cjs.map +1 -1
- package/dist/server/handlers/validate-avatar.js +1 -1
- package/dist/server/handlers/validate-avatar.js.map +1 -1
- package/dist/server/handlers/vector.cjs +17 -334
- package/dist/server/handlers/vector.js +1 -314
- package/dist/server/handlers/version-helpers.cjs +1 -1
- package/dist/server/handlers/voice.cjs +9 -35
- package/dist/server/handlers/voice.js +1 -23
- package/dist/server/handlers/workflow-builder.cjs +2 -2
- package/dist/server/handlers/workflow-builder.js +1 -2
- package/dist/server/handlers/workflows.cjs +30 -1293
- package/dist/server/handlers/workflows.js +1 -1257
- package/dist/server/handlers/workspace.cjs +27 -1176
- package/dist/server/handlers/workspace.js +1 -1146
- package/dist/server/handlers.cjs +33 -33
- package/dist/server/handlers.js +17 -17
- package/dist/server/schemas/index.cjs +7 -7
- package/dist/server/schemas/index.js +4 -4
- package/dist/server/schemas/mcp.d.ts +102 -0
- package/dist/server/schemas/mcp.d.ts.map +1 -1
- package/dist/server/schemas/schedules.d.ts +5 -0
- package/dist/server/schemas/schedules.d.ts.map +1 -1
- package/dist/server/server-adapter/index.cjs +5 -5
- package/dist/server/server-adapter/index.cjs.map +1 -1
- package/dist/server/server-adapter/index.js +4 -4
- package/dist/server/server-adapter/index.js.map +1 -1
- package/dist/server/server-adapter/routes/mcp.d.ts +214 -0
- package/dist/server/server-adapter/routes/mcp.d.ts.map +1 -1
- package/dist/tools-CmFSfDMn.js +256 -0
- package/dist/tools-CmFSfDMn.js.map +1 -0
- package/dist/tools-SPJtxG9N.cjs +291 -0
- package/dist/tools-SPJtxG9N.cjs.map +1 -0
- package/dist/{utils-DCgeTrq2.cjs → utils-CF76qzZR.cjs} +12 -17
- package/dist/{utils-DCgeTrq2.cjs.map → utils-CF76qzZR.cjs.map} +1 -1
- package/dist/{utils-DCAUeb6M.js → utils-aoLN3Wfi.js} +11 -16
- package/dist/{utils-DCAUeb6M.js.map → utils-aoLN3Wfi.js.map} +1 -1
- package/dist/{utils-Du-EpvDs.cjs → utils-dDLIDg8O.cjs} +2 -2
- package/dist/{utils-Du-EpvDs.cjs.map → utils-dDLIDg8O.cjs.map} +1 -1
- package/dist/vector-BKDD1kwc.cjs +409 -0
- package/dist/vector-BKDD1kwc.cjs.map +1 -0
- package/dist/vector-TWv4t-4g.js +314 -0
- package/dist/vector-TWv4t-4g.js.map +1 -0
- package/dist/voice-BnGwlZ75.cjs +70 -0
- package/dist/voice-BnGwlZ75.cjs.map +1 -0
- package/dist/voice-DjG8tBAD.js +23 -0
- package/dist/voice-DjG8tBAD.js.map +1 -0
- package/dist/{workflow-builder-Brj3IArM.cjs → workflow-builder-C9-8ZOWF.cjs} +5 -5
- package/dist/{workflow-builder-Brj3IArM.cjs.map → workflow-builder-C9-8ZOWF.cjs.map} +1 -1
- package/dist/{workflow-builder-DOa1Vx6w.js → workflow-builder-CjlLoQvo.js} +10 -8
- package/dist/{workflow-builder-DOa1Vx6w.js.map → workflow-builder-CjlLoQvo.js.map} +1 -1
- package/dist/workflows-DjqeJcdJ.cjs +1446 -0
- package/dist/workflows-DjqeJcdJ.cjs.map +1 -0
- package/dist/workflows-bb-otd2o.js +1273 -0
- package/dist/workflows-bb-otd2o.js.map +1 -0
- package/dist/workspace-B6kzp-bo.js +1154 -0
- package/dist/workspace-B6kzp-bo.js.map +1 -0
- package/dist/workspace-COKR1SxH.cjs +1309 -0
- package/dist/workspace-COKR1SxH.cjs.map +1 -0
- package/package.json +4 -4
- package/dist/a2a-B465DD1u.cjs.map +0 -1
- package/dist/a2a-CHBSYHxu.js.map +0 -1
- package/dist/dist-9c3PXXpk.cjs.map +0 -1
- package/dist/dist-B5OwHWTo.cjs +0 -2294
- package/dist/dist-B5OwHWTo.cjs.map +0 -1
- package/dist/dist-DGCnbhNe.js.map +0 -1
- package/dist/dist-DcoIg_tp.js +0 -2293
- package/dist/dist-DcoIg_tp.js.map +0 -1
- package/dist/mcp-DzpwLXEY.js.map +0 -1
- package/dist/mcp-ShaKO7gA.cjs.map +0 -1
- package/dist/observability-new-endpoints-AMp9bnMV.cjs.map +0 -1
- package/dist/probe-image-size-DBGjhUtJ.cjs.map +0 -1
- package/dist/probe-image-size-Dmoxv93t.js.map +0 -1
- package/dist/route-builder-BNZs643f.cjs.map +0 -1
- package/dist/route-builder-BfQYtclb.js.map +0 -1
- package/dist/routes-BULZI-PU.cjs.map +0 -1
- package/dist/routes-DPojsNf1.cjs.map +0 -1
- package/dist/routes-Dl6_kWm7.js.map +0 -1
- package/dist/routes-rwufkyUe.js.map +0 -1
- package/dist/schedules-BQYgaz66.js.map +0 -1
- package/dist/schedules-Bj-giFbc.cjs.map +0 -1
- package/dist/schema-Drf2W04o.js +0 -2
- package/dist/schema-EQanefYq.cjs +0 -1
- package/dist/schema-e0VHpMt0-C0452jOk.cjs.map +0 -1
- package/dist/schema-e0VHpMt0-CVP5Hnxy.js.map +0 -1
- package/dist/server/handlers/agent-builder.cjs.map +0 -1
- package/dist/server/handlers/agent-builder.js.map +0 -1
- package/dist/server/handlers/agents.cjs.map +0 -1
- package/dist/server/handlers/agents.js.map +0 -1
- package/dist/server/handlers/conversations.cjs.map +0 -1
- package/dist/server/handlers/conversations.js.map +0 -1
- package/dist/server/handlers/logs.cjs.map +0 -1
- package/dist/server/handlers/logs.js.map +0 -1
- package/dist/server/handlers/mcp.cjs.map +0 -1
- package/dist/server/handlers/mcp.js.map +0 -1
- package/dist/server/handlers/memory.cjs.map +0 -1
- package/dist/server/handlers/memory.js.map +0 -1
- package/dist/server/handlers/observability.cjs.map +0 -1
- package/dist/server/handlers/observability.js.map +0 -1
- package/dist/server/handlers/plans.cjs.map +0 -1
- package/dist/server/handlers/plans.js.map +0 -1
- package/dist/server/handlers/responses.cjs.map +0 -1
- package/dist/server/handlers/responses.js.map +0 -1
- package/dist/server/handlers/scores.cjs.map +0 -1
- package/dist/server/handlers/scores.js.map +0 -1
- package/dist/server/handlers/tools.cjs.map +0 -1
- package/dist/server/handlers/tools.js.map +0 -1
- package/dist/server/handlers/vector.cjs.map +0 -1
- package/dist/server/handlers/vector.js.map +0 -1
- package/dist/server/handlers/voice.cjs.map +0 -1
- package/dist/server/handlers/voice.js.map +0 -1
- package/dist/server/handlers/workflows.cjs.map +0 -1
- package/dist/server/handlers/workflows.js.map +0 -1
- package/dist/server/handlers/workspace.cjs.map +0 -1
- package/dist/server/handlers/workspace.js.map +0 -1
- package/dist/sync-Ai_ZDz7U.js +0 -1700
- package/dist/sync-Ai_ZDz7U.js.map +0 -1
- package/dist/sync-BrO5MtSe.cjs +0 -1729
- package/dist/sync-BrO5MtSe.cjs.map +0 -1
|
@@ -0,0 +1,2828 @@
|
|
|
1
|
+
import { r as __exportAll } from "./rolldown-runtime-D3Hj5m0v.js";
|
|
2
|
+
import { t as HTTPException } from "./http-exception-CyfxZB6W.js";
|
|
3
|
+
import { A as observeAgentResponseSchema, B as sendAgentSignalBodySchema, C as listAgentsResponseSchema, D as modelConfigIdPathParams, F as recoverBodySchema, H as sendToolApprovalResponseSchema, I as reorderAgentModelListBodySchema, L as resumeStreamBodySchema, M as providersResponseSchema, N as queueAgentMessageBodySchema, O as modelManagementResponseSchema, P as queueAgentSignalBodySchema, Q as toolCallResponseSchema, R as resumeStreamUntilIdleBodySchema, S as generateResponseSchema, T as listSuspendedRunsResponseSchema, V as sendToolApprovalBodySchema, W as serializedAgentSchema, X as streamUntilIdleBodySchema, Y as streamResponseSchema, Z as subscribeAgentThreadBodySchema, _ as enhanceInstructionsBodySchema, a as agentIdPathParams, c as agentSkillPathParams, d as approveNetworkToolCallBodySchema, et as updateAgentModelBodySchema, f as approveToolCallBodySchema, g as declineToolCallBodySchema, h as declineNetworkToolCallBodySchema, i as agentExecutionLegacyBodySchema, k as observeAgentBodySchema, m as cancelPendingAgentSignalsResponseSchema, n as abortAgentThreadResponseSchema, p as cancelPendingAgentSignalsBodySchema, r as agentExecutionBodySchema, t as abortAgentThreadBodySchema, tt as updateAgentModelInModelListBodySchema, u as agentVersionQuerySchema, v as enhanceInstructionsResponseSchema, w as listSuspendedRunsQuerySchema, z as sendAgentMessageBodySchema } from "./agents-BHLTMBff.js";
|
|
4
|
+
import { n as standardSchemaToJSONSchema, r as toStandardSchema } from "./schema-CzbEIyhE-BsMcj9Ws.js";
|
|
5
|
+
import { n as createRoute } from "./route-builder-CjkWxv4E.js";
|
|
6
|
+
import { c as toSlug, l as stringify } from "./utils-aoLN3Wfi.js";
|
|
7
|
+
import { g as resolveToolConfig, i as MASTRA_IS_STUDIO_KEY, o as MASTRA_RESOURCE_ID_KEY, p as WORKSPACE_TOOLS } from "./constants-DazK_RZj.js";
|
|
8
|
+
import { handleError } from "./server/handlers/error.js";
|
|
9
|
+
import { a as getEffectiveThreadId, d as sanitizeBody, f as stripClientCredentialHeaders, g as MastraFGAPermissions, h as validateThreadOwnership, i as getEffectiveResourceId, m as validateRunOwnership, n as enforceThreadAccess, p as validateBody, r as getContextResourceId, s as mergeBodyRequestContext, t as applyEffectiveThreadId, u as requireEffectiveResourceId } from "./utils-BBJlS81s.js";
|
|
10
|
+
import { r as createStoredAgentResponseSchema } from "./stored-agents-BtaEzKfr.js";
|
|
11
|
+
import { O as skillDisambiguationQuerySchema, h as getAgentSkillResponseSchema } from "./workspace-4dBGFdV2.js";
|
|
12
|
+
import { stripInjectedToolOverrideFields } from "./server/handlers/tool-schema-overrides.js";
|
|
13
|
+
import { z } from "zod/v4";
|
|
14
|
+
import { zodToJsonSchema } from "@mastra/core/utils/zod-to-json";
|
|
15
|
+
import { Agent, isDurableAgentLike } from "@mastra/core/agent";
|
|
16
|
+
import { AGENT_STREAM_TOPIC, DurableStepIds } from "@mastra/core/agent/durable";
|
|
17
|
+
import { MASTRA_VERSIONS_KEY, mergeVersionOverrides } from "@mastra/core/di";
|
|
18
|
+
import { ErrorCategory, ErrorDomain, MastraError } from "@mastra/core/error";
|
|
19
|
+
import { ModelRouterLanguageModel, PROVIDER_REGISTRY, defaultGateways, parseModelString } from "@mastra/core/llm";
|
|
20
|
+
//#region src/server/handlers/agents.ts
|
|
21
|
+
var agents_exports = /* @__PURE__ */ __exportAll({
|
|
22
|
+
ABORT_AGENT_THREAD_ROUTE: () => ABORT_AGENT_THREAD_ROUTE,
|
|
23
|
+
APPROVE_NETWORK_TOOL_CALL_ROUTE: () => APPROVE_NETWORK_TOOL_CALL_ROUTE,
|
|
24
|
+
APPROVE_TOOL_CALL_GENERATE_ROUTE: () => APPROVE_TOOL_CALL_GENERATE_ROUTE,
|
|
25
|
+
APPROVE_TOOL_CALL_ROUTE: () => APPROVE_TOOL_CALL_ROUTE,
|
|
26
|
+
CANCEL_AGENT_PENDING_SIGNALS_ROUTE: () => CANCEL_AGENT_PENDING_SIGNALS_ROUTE,
|
|
27
|
+
CLONE_AGENT_ROUTE: () => CLONE_AGENT_ROUTE,
|
|
28
|
+
DECLINE_NETWORK_TOOL_CALL_ROUTE: () => DECLINE_NETWORK_TOOL_CALL_ROUTE,
|
|
29
|
+
DECLINE_TOOL_CALL_GENERATE_ROUTE: () => DECLINE_TOOL_CALL_GENERATE_ROUTE,
|
|
30
|
+
DECLINE_TOOL_CALL_ROUTE: () => DECLINE_TOOL_CALL_ROUTE,
|
|
31
|
+
ENHANCE_INSTRUCTIONS_ROUTE: () => ENHANCE_INSTRUCTIONS_ROUTE,
|
|
32
|
+
GENERATE_AGENT_ROUTE: () => GENERATE_AGENT_ROUTE,
|
|
33
|
+
GENERATE_AGENT_VNEXT_ROUTE: () => GENERATE_AGENT_VNEXT_ROUTE,
|
|
34
|
+
GENERATE_LEGACY_ROUTE: () => GENERATE_LEGACY_ROUTE,
|
|
35
|
+
GET_AGENT_BY_ID_ROUTE: () => GET_AGENT_BY_ID_ROUTE,
|
|
36
|
+
GET_AGENT_SKILL_ROUTE: () => GET_AGENT_SKILL_ROUTE,
|
|
37
|
+
GET_PROVIDERS_ROUTE: () => GET_PROVIDERS_ROUTE,
|
|
38
|
+
LIST_AGENTS_ROUTE: () => LIST_AGENTS_ROUTE,
|
|
39
|
+
LIST_SUSPENDED_RUNS_ROUTE: () => LIST_SUSPENDED_RUNS_ROUTE,
|
|
40
|
+
OBSERVE_AGENT_STREAM_ROUTE: () => OBSERVE_AGENT_STREAM_ROUTE,
|
|
41
|
+
QUEUE_AGENT_MESSAGE_ROUTE: () => QUEUE_AGENT_MESSAGE_ROUTE,
|
|
42
|
+
QUEUE_AGENT_SIGNAL_ROUTE: () => QUEUE_AGENT_SIGNAL_ROUTE,
|
|
43
|
+
RECOVER_ROUTE: () => RECOVER_ROUTE,
|
|
44
|
+
REORDER_AGENT_MODEL_LIST_ROUTE: () => REORDER_AGENT_MODEL_LIST_ROUTE,
|
|
45
|
+
RESET_AGENT_MODEL_ROUTE: () => RESET_AGENT_MODEL_ROUTE,
|
|
46
|
+
RESUME_STREAM_ROUTE: () => RESUME_STREAM_ROUTE,
|
|
47
|
+
RESUME_STREAM_UNTIL_IDLE_ROUTE: () => RESUME_STREAM_UNTIL_IDLE_ROUTE,
|
|
48
|
+
SEND_AGENT_MESSAGE_ROUTE: () => SEND_AGENT_MESSAGE_ROUTE,
|
|
49
|
+
SEND_AGENT_SIGNAL_ROUTE: () => SEND_AGENT_SIGNAL_ROUTE,
|
|
50
|
+
SEND_TOOL_APPROVAL_ROUTE: () => SEND_TOOL_APPROVAL_ROUTE,
|
|
51
|
+
STREAM_GENERATE_LEGACY_ROUTE: () => STREAM_GENERATE_LEGACY_ROUTE,
|
|
52
|
+
STREAM_GENERATE_ROUTE: () => STREAM_GENERATE_ROUTE,
|
|
53
|
+
STREAM_GENERATE_VNEXT_DEPRECATED_ROUTE: () => STREAM_GENERATE_VNEXT_DEPRECATED_ROUTE,
|
|
54
|
+
STREAM_NETWORK_ROUTE: () => STREAM_NETWORK_ROUTE,
|
|
55
|
+
STREAM_UI_MESSAGE_DEPRECATED_ROUTE: () => STREAM_UI_MESSAGE_DEPRECATED_ROUTE,
|
|
56
|
+
STREAM_UI_MESSAGE_VNEXT_DEPRECATED_ROUTE: () => STREAM_UI_MESSAGE_VNEXT_DEPRECATED_ROUTE,
|
|
57
|
+
STREAM_UNTIL_IDLE_GENERATE_ROUTE: () => STREAM_UNTIL_IDLE_GENERATE_ROUTE,
|
|
58
|
+
STREAM_VNEXT_DEPRECATED_ROUTE: () => STREAM_VNEXT_DEPRECATED_ROUTE,
|
|
59
|
+
SUBSCRIBE_AGENT_THREAD_ROUTE: () => SUBSCRIBE_AGENT_THREAD_ROUTE,
|
|
60
|
+
UPDATE_AGENT_MODEL_IN_MODEL_LIST_ROUTE: () => UPDATE_AGENT_MODEL_IN_MODEL_LIST_ROUTE,
|
|
61
|
+
UPDATE_AGENT_MODEL_ROUTE: () => UPDATE_AGENT_MODEL_ROUTE,
|
|
62
|
+
buildProvidersList: () => buildProvidersList,
|
|
63
|
+
extractVersionOptions: () => extractVersionOptions,
|
|
64
|
+
getAgentFromSystem: () => getAgentFromSystem,
|
|
65
|
+
getBrowserToolsFromAgent: () => getBrowserToolsFromAgent,
|
|
66
|
+
getSerializedAgentTools: () => getSerializedAgentTools,
|
|
67
|
+
getSerializedProcessors: () => getSerializedProcessors,
|
|
68
|
+
getSerializedSkillsFromAgent: () => getSerializedSkillsFromAgent,
|
|
69
|
+
getWorkspaceToolsFromAgent: () => getWorkspaceToolsFromAgent,
|
|
70
|
+
isProviderConnected: () => isProviderConnected
|
|
71
|
+
});
|
|
72
|
+
/**
|
|
73
|
+
* Merge incoming version overrides onto a RequestContext.
|
|
74
|
+
* Reads any existing overrides, shallow-merges per category, and writes back.
|
|
75
|
+
*/
|
|
76
|
+
function stashVersionOverrides(ctx, versions) {
|
|
77
|
+
if (!versions) return;
|
|
78
|
+
const existingRaw = ctx.get(MASTRA_VERSIONS_KEY);
|
|
79
|
+
const merged = mergeVersionOverrides(existingRaw && typeof existingRaw === "object" && !Array.isArray(existingRaw) ? existingRaw : void 0, versions);
|
|
80
|
+
if (merged) ctx.set(MASTRA_VERSIONS_KEY, merged);
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Ensure `defaultStatus` is set on the version overrides in the RequestContext
|
|
84
|
+
* so sub-agents inherit the same draft/published semantics as the parent.
|
|
85
|
+
*
|
|
86
|
+
* When the parent agent is resolved via a specific versionId (editor context),
|
|
87
|
+
* sub-agents should default to `draft`. When resolved with published (main
|
|
88
|
+
* chat), sub-agents default to `published`. An explicit `defaultStatus` from
|
|
89
|
+
* the request body takes precedence.
|
|
90
|
+
*/
|
|
91
|
+
function ensureDefaultVersionStatus(ctx, versionOptions) {
|
|
92
|
+
const existingRaw = ctx.get(MASTRA_VERSIONS_KEY);
|
|
93
|
+
if (existingRaw?.defaultStatus) return;
|
|
94
|
+
const inferredStatus = versionOptions ? "draft" : "published";
|
|
95
|
+
const updated = {
|
|
96
|
+
...existingRaw,
|
|
97
|
+
defaultStatus: inferredStatus
|
|
98
|
+
};
|
|
99
|
+
ctx.set(MASTRA_VERSIONS_KEY, updated);
|
|
100
|
+
}
|
|
101
|
+
function getIsStudioFromContext(requestContext) {
|
|
102
|
+
return requestContext.get(MASTRA_IS_STUDIO_KEY) === true;
|
|
103
|
+
}
|
|
104
|
+
function normalizePublicExecutionOptions(options, serverRequestContext) {
|
|
105
|
+
if (!options || typeof options !== "object" || Array.isArray(options)) return void 0;
|
|
106
|
+
const { actor: _actor, scopes: _scopes, requestContext, ...normalized } = options;
|
|
107
|
+
stripClientCredentialHeaders(normalized);
|
|
108
|
+
mergeBodyRequestContext(serverRequestContext, requestContext);
|
|
109
|
+
return {
|
|
110
|
+
...normalized,
|
|
111
|
+
requestContext: serverRequestContext
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
function hasSuspendedToolCall(snapshot, toolCallId) {
|
|
115
|
+
const resumeTarget = snapshot.resumeLabels?.[toolCallId];
|
|
116
|
+
const resumeStep = resumeTarget?.stepId ? snapshot.context?.[resumeTarget.stepId] : void 0;
|
|
117
|
+
if (resumeStep?.status === "suspended" && (resumeStep.suspendPayload?.requireToolApproval || resumeStep.suspendPayload?.toolCallSuspended || resumeStep.suspendPayload?.toolCallId)) return true;
|
|
118
|
+
const visit = (value) => {
|
|
119
|
+
if (!value || typeof value !== "object") return false;
|
|
120
|
+
if (Array.isArray(value)) return value.some(visit);
|
|
121
|
+
const record = value;
|
|
122
|
+
const payload = record.suspendPayload;
|
|
123
|
+
if (record.status === "suspended" && (payload?.requireToolApproval?.toolCallId === toolCallId || payload?.toolCallId === toolCallId)) return true;
|
|
124
|
+
return Object.values(record).some(visit);
|
|
125
|
+
};
|
|
126
|
+
return visit(snapshot.context);
|
|
127
|
+
}
|
|
128
|
+
const DURABLE_SNAPSHOT_WAIT_TIMEOUT_MS = 1e4;
|
|
129
|
+
const DURABLE_SNAPSHOT_WAIT_INTERVAL_MS = 25;
|
|
130
|
+
function getDurableLoopWorkflowName(agent) {
|
|
131
|
+
return agent.durableLoopWorkflowName ?? DurableStepIds.AGENTIC_LOOP;
|
|
132
|
+
}
|
|
133
|
+
async function validateDurableToolCallAccess({ mastra, agent, runId, toolCallId, requestContext, threadId, abortSignal }) {
|
|
134
|
+
if (!isDurableAgentLike(agent)) return;
|
|
135
|
+
const workflowsStore = await mastra.getStorage()?.getStore("workflows");
|
|
136
|
+
if (!workflowsStore) throw new HTTPException(403, { message: "Access denied: durable run belongs to a different resource" });
|
|
137
|
+
const workflowName = getDurableLoopWorkflowName(agent);
|
|
138
|
+
const contextResourceId = getContextResourceId(requestContext);
|
|
139
|
+
const deadline = Date.now() + DURABLE_SNAPSHOT_WAIT_TIMEOUT_MS;
|
|
140
|
+
while (true) {
|
|
141
|
+
const workflowRun = await workflowsStore.getWorkflowRunById({
|
|
142
|
+
workflowName,
|
|
143
|
+
runId
|
|
144
|
+
});
|
|
145
|
+
let snapshot = workflowRun?.snapshot;
|
|
146
|
+
if (typeof snapshot === "string") try {
|
|
147
|
+
snapshot = JSON.parse(snapshot);
|
|
148
|
+
} catch {
|
|
149
|
+
snapshot = void 0;
|
|
150
|
+
}
|
|
151
|
+
const input = snapshot?.context?.input;
|
|
152
|
+
const persistedResourceIds = new Set([
|
|
153
|
+
workflowRun?.resourceId,
|
|
154
|
+
input?.state?.resourceId,
|
|
155
|
+
input?.messageListState?.memoryInfo?.resourceId,
|
|
156
|
+
input?.requestContextEntries?.[MASTRA_RESOURCE_ID_KEY]
|
|
157
|
+
].filter((resourceId) => typeof resourceId === "string" && resourceId.length > 0));
|
|
158
|
+
const [persistedResourceId] = persistedResourceIds;
|
|
159
|
+
if (persistedResourceIds.size > 1 || contextResourceId && persistedResourceId && persistedResourceId !== contextResourceId) throw new HTTPException(403, { message: "Access denied: durable run belongs to a different resource" });
|
|
160
|
+
const ready = !!workflowRun && !!snapshot && snapshot.status === "suspended" && (toolCallId === void 0 || hasSuspendedToolCall(snapshot, toolCallId));
|
|
161
|
+
if (ready || Date.now() >= deadline || abortSignal?.aborted) {
|
|
162
|
+
if (!workflowRun) throw new HTTPException(403, { message: "Access denied: durable run belongs to a different resource" });
|
|
163
|
+
const persistedThreadId = input?.state?.threadId ?? input?.messageListState?.memoryInfo?.threadId;
|
|
164
|
+
if (threadId && persistedThreadId !== threadId) throw new HTTPException(403, { message: "Access denied: durable run belongs to a different thread" });
|
|
165
|
+
if (!ready || input?.agentId !== agent.id) throw new HTTPException(403, { message: "Access denied: tool call is not suspended on this durable run" });
|
|
166
|
+
await validateRunOwnership({ resourceId: persistedResourceId }, contextResourceId, mastra);
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
await new Promise((resolve) => setTimeout(resolve, DURABLE_SNAPSHOT_WAIT_INTERVAL_MS));
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Providers whose apiKeyEnvVar entries are aliases for the same credential (any one
|
|
174
|
+
* suffices), rather than distinct required values (all needed — the default assumption).
|
|
175
|
+
* Keep this list to cases with a confirmed alias relationship; see the "google" entry in
|
|
176
|
+
* PROVIDER_OVERRIDES in packages/core/src/llm/model/gateways/models-dev.ts and #17343.
|
|
177
|
+
*/
|
|
178
|
+
const ALIASED_API_KEY_ENV_VAR_PROVIDERS = /* @__PURE__ */ new Set(["google"]);
|
|
179
|
+
/**
|
|
180
|
+
* Checks if a provider has its required API key environment variable(s) configured.
|
|
181
|
+
* Handles provider IDs with suffixes (e.g., "openai.chat" -> "openai").
|
|
182
|
+
* Also handles custom gateway providers that are stored with gateway prefix (e.g., "acme/acme-openai").
|
|
183
|
+
* @param providerId - The provider identifier (may include a suffix like ".chat" or be from a custom gateway)
|
|
184
|
+
* @param customProviders - Optional record of custom gateway providers to check
|
|
185
|
+
* @returns true if all required environment variables are set (or, for aliased providers, if any one is set), false otherwise
|
|
186
|
+
*/
|
|
187
|
+
function isProviderConnected(providerId, customProviders) {
|
|
188
|
+
if (providerId === "google-vertex" || providerId.startsWith("google.vertex")) return !!(process.env.GOOGLE_VERTEX_PROJECT && process.env.GOOGLE_VERTEX_LOCATION);
|
|
189
|
+
const cleanId = providerId.includes(".") ? providerId.split(".")[0] : providerId;
|
|
190
|
+
let provider = PROVIDER_REGISTRY[cleanId];
|
|
191
|
+
if (!provider && customProviders) provider = customProviders[cleanId];
|
|
192
|
+
if (!provider && !cleanId.includes("/")) {
|
|
193
|
+
const matchingKey = Object.keys(PROVIDER_REGISTRY).find((key) => {
|
|
194
|
+
const parts = key.split("/");
|
|
195
|
+
return parts.length === 2 && parts[1] === cleanId;
|
|
196
|
+
});
|
|
197
|
+
if (matchingKey) provider = PROVIDER_REGISTRY[matchingKey];
|
|
198
|
+
if (!provider && customProviders) {
|
|
199
|
+
const customMatchingKey = Object.keys(customProviders).find((key) => {
|
|
200
|
+
const parts = key.split("/");
|
|
201
|
+
return parts.length === 2 && parts[1] === cleanId;
|
|
202
|
+
});
|
|
203
|
+
if (customMatchingKey) provider = customProviders[customMatchingKey];
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
if (!provider) return false;
|
|
207
|
+
const envVars = Array.isArray(provider.apiKeyEnvVar) ? provider.apiKeyEnvVar : [provider.apiKeyEnvVar];
|
|
208
|
+
if (ALIASED_API_KEY_ENV_VAR_PROVIDERS.has(cleanId)) return envVars.some((envVar) => !!process.env[envVar]);
|
|
209
|
+
return envVars.every((envVar) => !!process.env[envVar]);
|
|
210
|
+
}
|
|
211
|
+
function resolveLazySchema(schema) {
|
|
212
|
+
if (typeof schema === "function" && !("~standard" in schema)) return resolveLazySchema(schema());
|
|
213
|
+
return schema;
|
|
214
|
+
}
|
|
215
|
+
function schemaToJsonSchema(schema) {
|
|
216
|
+
if (!schema) return;
|
|
217
|
+
return standardSchemaToJSONSchema(toStandardSchema(schema), { target: "draft-2020-12" });
|
|
218
|
+
}
|
|
219
|
+
function getAgentModelRef(agentModel, llm) {
|
|
220
|
+
if (typeof agentModel === "string") {
|
|
221
|
+
const { provider, modelId } = parseModelString(agentModel);
|
|
222
|
+
return {
|
|
223
|
+
provider: provider ?? llm?.getProvider(),
|
|
224
|
+
modelId
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
const model = llm?.getModel();
|
|
228
|
+
if (model instanceof ModelRouterLanguageModel && model.gatewayId !== "models.dev" && model.gatewayId !== model.provider) return {
|
|
229
|
+
provider: model.gatewayId,
|
|
230
|
+
modelId: `${model.provider}/${model.modelId}`
|
|
231
|
+
};
|
|
232
|
+
return {
|
|
233
|
+
provider: llm?.getProvider(),
|
|
234
|
+
modelId: llm?.getModelId()
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
async function getSerializedAgentTools(tools, partial = false) {
|
|
238
|
+
return Object.entries(tools || {}).reduce((acc, [key, tool]) => {
|
|
239
|
+
const toolId = "id" in tool && typeof tool.id === "string" && tool.id.length > 0 ? tool.id : `tool-${key}`;
|
|
240
|
+
let inputSchemaForReturn = void 0;
|
|
241
|
+
let outputSchemaForReturn = void 0;
|
|
242
|
+
let requestContextSchemaForReturn = void 0;
|
|
243
|
+
if (!partial) try {
|
|
244
|
+
const inputSchema = schemaToJsonSchema(resolveLazySchema("inputSchema" in tool ? tool.inputSchema : void 0));
|
|
245
|
+
if (inputSchema !== void 0) inputSchemaForReturn = stringify(stripInjectedToolOverrideFields(inputSchema));
|
|
246
|
+
const outputSchema = schemaToJsonSchema(resolveLazySchema("outputSchema" in tool ? tool.outputSchema : void 0));
|
|
247
|
+
if (outputSchema !== void 0) outputSchemaForReturn = stringify(outputSchema);
|
|
248
|
+
const requestContextSchema = schemaToJsonSchema(resolveLazySchema("requestContextSchema" in tool ? tool.requestContextSchema : void 0));
|
|
249
|
+
if (requestContextSchema !== void 0) requestContextSchemaForReturn = stringify(requestContextSchema);
|
|
250
|
+
} catch (error) {
|
|
251
|
+
console.error(`Error getting serialized tool`, {
|
|
252
|
+
toolId,
|
|
253
|
+
error
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
acc[key] = {
|
|
257
|
+
...tool,
|
|
258
|
+
id: toolId,
|
|
259
|
+
inputSchema: inputSchemaForReturn,
|
|
260
|
+
outputSchema: outputSchemaForReturn,
|
|
261
|
+
requestContextSchema: requestContextSchemaForReturn
|
|
262
|
+
};
|
|
263
|
+
return acc;
|
|
264
|
+
}, {});
|
|
265
|
+
}
|
|
266
|
+
function getSerializedProcessors(processors) {
|
|
267
|
+
return processors.map((processor) => {
|
|
268
|
+
return {
|
|
269
|
+
id: processor.id,
|
|
270
|
+
name: processor.name || processor.constructor.name
|
|
271
|
+
};
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Extract skills from an agent (both inline and workspace skills).
|
|
276
|
+
* Uses agent.listSkills() which merges agent-level and workspace-level skills.
|
|
277
|
+
*/
|
|
278
|
+
async function getSerializedSkillsFromAgent(agent, requestContext) {
|
|
279
|
+
try {
|
|
280
|
+
return (await agent.listSkills({ requestContext })).map((skill) => ({
|
|
281
|
+
name: skill.name,
|
|
282
|
+
description: skill.description,
|
|
283
|
+
license: skill.license,
|
|
284
|
+
path: skill.path
|
|
285
|
+
}));
|
|
286
|
+
} catch {
|
|
287
|
+
return [];
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Get the list of available workspace tools for an agent.
|
|
292
|
+
*
|
|
293
|
+
* Tries to use core's `createWorkspaceTools` for an accurate tool list that
|
|
294
|
+
* respects runtime availability (e.g. `@ast-grep/napi` for ast_edit).
|
|
295
|
+
* Falls back to inlined config-based logic for older core versions that don't
|
|
296
|
+
* export `createWorkspaceTools`.
|
|
297
|
+
*/
|
|
298
|
+
async function getWorkspaceToolsFromAgent(agent, requestContext) {
|
|
299
|
+
try {
|
|
300
|
+
const workspace = await agent.getWorkspace({ requestContext });
|
|
301
|
+
if (!workspace) return [];
|
|
302
|
+
try {
|
|
303
|
+
const mod = await import("@mastra/core/workspace");
|
|
304
|
+
if (typeof mod.createWorkspaceTools === "function") return Object.keys(await mod.createWorkspaceTools(workspace));
|
|
305
|
+
} catch {}
|
|
306
|
+
const tools = [];
|
|
307
|
+
const isReadOnly = workspace.filesystem?.readOnly ?? false;
|
|
308
|
+
const toolsConfig = workspace.getToolsConfig();
|
|
309
|
+
const configContext = {
|
|
310
|
+
workspace,
|
|
311
|
+
requestContext: requestContext ? Object.fromEntries(requestContext.entries()) : {}
|
|
312
|
+
};
|
|
313
|
+
const isEnabled = async (toolName) => {
|
|
314
|
+
return (await resolveToolConfig(toolsConfig, toolName, configContext)).enabled;
|
|
315
|
+
};
|
|
316
|
+
if (workspace.filesystem) {
|
|
317
|
+
if (await isEnabled(WORKSPACE_TOOLS.FILESYSTEM.READ_FILE)) tools.push(WORKSPACE_TOOLS.FILESYSTEM.READ_FILE);
|
|
318
|
+
if (await isEnabled(WORKSPACE_TOOLS.FILESYSTEM.LIST_FILES)) tools.push(WORKSPACE_TOOLS.FILESYSTEM.LIST_FILES);
|
|
319
|
+
if (await isEnabled(WORKSPACE_TOOLS.FILESYSTEM.FILE_STAT)) tools.push(WORKSPACE_TOOLS.FILESYSTEM.FILE_STAT);
|
|
320
|
+
if (!isReadOnly) {
|
|
321
|
+
if (await isEnabled(WORKSPACE_TOOLS.FILESYSTEM.WRITE_FILE)) tools.push(WORKSPACE_TOOLS.FILESYSTEM.WRITE_FILE);
|
|
322
|
+
if (await isEnabled(WORKSPACE_TOOLS.FILESYSTEM.EDIT_FILE)) tools.push(WORKSPACE_TOOLS.FILESYSTEM.EDIT_FILE);
|
|
323
|
+
if (await isEnabled(WORKSPACE_TOOLS.FILESYSTEM.DELETE)) tools.push(WORKSPACE_TOOLS.FILESYSTEM.DELETE);
|
|
324
|
+
if (await isEnabled(WORKSPACE_TOOLS.FILESYSTEM.MKDIR)) tools.push(WORKSPACE_TOOLS.FILESYSTEM.MKDIR);
|
|
325
|
+
}
|
|
326
|
+
if (await isEnabled(WORKSPACE_TOOLS.FILESYSTEM.GREP)) tools.push(WORKSPACE_TOOLS.FILESYSTEM.GREP);
|
|
327
|
+
}
|
|
328
|
+
if (workspace.canBM25 || workspace.canVector) {
|
|
329
|
+
if (await isEnabled(WORKSPACE_TOOLS.SEARCH.SEARCH)) tools.push(WORKSPACE_TOOLS.SEARCH.SEARCH);
|
|
330
|
+
if (!isReadOnly && await isEnabled(WORKSPACE_TOOLS.SEARCH.INDEX)) tools.push(WORKSPACE_TOOLS.SEARCH.INDEX);
|
|
331
|
+
}
|
|
332
|
+
if (workspace.sandbox) {
|
|
333
|
+
if (workspace.sandbox.executeCommand && await isEnabled(WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND)) tools.push(WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND);
|
|
334
|
+
}
|
|
335
|
+
return tools;
|
|
336
|
+
} catch {
|
|
337
|
+
return [];
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* Get the list of browser tool names for an agent.
|
|
342
|
+
* Returns the tool names from the agent's browser provider if configured.
|
|
343
|
+
*/
|
|
344
|
+
function getBrowserToolsFromAgent(agent, onError) {
|
|
345
|
+
try {
|
|
346
|
+
const browser = agent.browser;
|
|
347
|
+
if (!browser) return [];
|
|
348
|
+
return Object.keys(browser.getTools());
|
|
349
|
+
} catch (error) {
|
|
350
|
+
onError?.(error);
|
|
351
|
+
return [];
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
function createBrowserToolsErrorLogger(logger, agentId) {
|
|
355
|
+
return (error) => logger.warn("Failed to get browser tools for agent", {
|
|
356
|
+
agentId,
|
|
357
|
+
error
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
async function getSerializedAgentDefinition({ agent, requestContext, logger }) {
|
|
361
|
+
let serializedAgentAgents = {};
|
|
362
|
+
if ("listAgents" in agent) try {
|
|
363
|
+
const agents = await agent.listAgents({ requestContext });
|
|
364
|
+
serializedAgentAgents = Object.entries(agents || {}).reduce((acc, [key, agent]) => {
|
|
365
|
+
acc[key] = {
|
|
366
|
+
id: agent.id,
|
|
367
|
+
name: agent.name ?? key
|
|
368
|
+
};
|
|
369
|
+
return acc;
|
|
370
|
+
}, {});
|
|
371
|
+
} catch (error) {
|
|
372
|
+
logger?.warn("Error getting sub-agents for agent", {
|
|
373
|
+
agentName: agent.name,
|
|
374
|
+
error
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
return serializedAgentAgents;
|
|
378
|
+
}
|
|
379
|
+
async function formatAgentList({ id, mastra, agent, requestContext, partial = false }) {
|
|
380
|
+
const logger = mastra.getLogger();
|
|
381
|
+
const description = agent.getDescription();
|
|
382
|
+
let metadata;
|
|
383
|
+
if (typeof agent.getMetadata === "function") try {
|
|
384
|
+
metadata = await agent.getMetadata({ requestContext });
|
|
385
|
+
} catch (error) {
|
|
386
|
+
logger.warn(`Failed to get metadata for agent ${agent.name}`, { error });
|
|
387
|
+
}
|
|
388
|
+
let instructions;
|
|
389
|
+
try {
|
|
390
|
+
instructions = await agent.getInstructions({ requestContext });
|
|
391
|
+
} catch (error) {
|
|
392
|
+
logger.warn("Error getting instructions for agent", {
|
|
393
|
+
agentName: agent.name,
|
|
394
|
+
error
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
let tools = {};
|
|
398
|
+
try {
|
|
399
|
+
tools = await agent.listTools({ requestContext });
|
|
400
|
+
} catch (error) {
|
|
401
|
+
logger.warn("Error listing tools for agent", {
|
|
402
|
+
agentName: agent.name,
|
|
403
|
+
error
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
let llm;
|
|
407
|
+
try {
|
|
408
|
+
llm = await agent.getLLM({ requestContext });
|
|
409
|
+
} catch (error) {
|
|
410
|
+
logger.warn("Error getting LLM for agent", {
|
|
411
|
+
agentName: agent.name,
|
|
412
|
+
error
|
|
413
|
+
});
|
|
414
|
+
}
|
|
415
|
+
let defaultGenerateOptionsLegacy;
|
|
416
|
+
try {
|
|
417
|
+
defaultGenerateOptionsLegacy = await agent.getDefaultGenerateOptionsLegacy({ requestContext });
|
|
418
|
+
} catch (error) {
|
|
419
|
+
logger.warn("Error getting default generate options for agent", {
|
|
420
|
+
agentName: agent.name,
|
|
421
|
+
error
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
let defaultStreamOptionsLegacy;
|
|
425
|
+
try {
|
|
426
|
+
defaultStreamOptionsLegacy = await agent.getDefaultStreamOptionsLegacy({ requestContext });
|
|
427
|
+
} catch (error) {
|
|
428
|
+
logger.warn("Error getting default stream options for agent", {
|
|
429
|
+
agentName: agent.name,
|
|
430
|
+
error
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
let defaultOptions;
|
|
434
|
+
try {
|
|
435
|
+
defaultOptions = await agent.getDefaultOptions({ requestContext });
|
|
436
|
+
} catch (error) {
|
|
437
|
+
logger.warn("Error getting default options for agent", {
|
|
438
|
+
agentName: agent.name,
|
|
439
|
+
error
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
const serializedAgentTools = await getSerializedAgentTools(tools, partial);
|
|
443
|
+
let serializedAgentWorkflows = {};
|
|
444
|
+
if ("listWorkflows" in agent) try {
|
|
445
|
+
const workflows = await agent.listWorkflows({ requestContext });
|
|
446
|
+
serializedAgentWorkflows = Object.entries(workflows || {}).reduce((acc, [key, workflow]) => {
|
|
447
|
+
return {
|
|
448
|
+
...acc,
|
|
449
|
+
[key]: { name: workflow.name || "Unnamed workflow" }
|
|
450
|
+
};
|
|
451
|
+
}, {});
|
|
452
|
+
} catch (error) {
|
|
453
|
+
logger.error("Error getting workflows for agent", {
|
|
454
|
+
agentName: agent.name,
|
|
455
|
+
error
|
|
456
|
+
});
|
|
457
|
+
}
|
|
458
|
+
const serializedAgentAgents = await getSerializedAgentDefinition({
|
|
459
|
+
agent,
|
|
460
|
+
requestContext,
|
|
461
|
+
logger
|
|
462
|
+
});
|
|
463
|
+
let serializedInputProcessors = [];
|
|
464
|
+
let serializedOutputProcessors = [];
|
|
465
|
+
try {
|
|
466
|
+
const configuredProcessorWorkflows = await agent.getConfiguredProcessorWorkflows();
|
|
467
|
+
const inputProcessorWorkflows = configuredProcessorWorkflows.filter((w) => w.id.endsWith("-input-processor"));
|
|
468
|
+
const outputProcessorWorkflows = configuredProcessorWorkflows.filter((w) => w.id.endsWith("-output-processor"));
|
|
469
|
+
serializedInputProcessors = getSerializedProcessors(inputProcessorWorkflows);
|
|
470
|
+
serializedOutputProcessors = getSerializedProcessors(outputProcessorWorkflows);
|
|
471
|
+
} catch (error) {
|
|
472
|
+
logger.error("Error getting configured processors for agent", {
|
|
473
|
+
agentName: agent.name,
|
|
474
|
+
error
|
|
475
|
+
});
|
|
476
|
+
}
|
|
477
|
+
const serializedSkills = await getSerializedSkillsFromAgent(agent, requestContext);
|
|
478
|
+
const workspaceTools = await getWorkspaceToolsFromAgent(agent, requestContext);
|
|
479
|
+
const browserTools = getBrowserToolsFromAgent(agent, createBrowserToolsErrorLogger(logger, agent.id));
|
|
480
|
+
let workspaceId;
|
|
481
|
+
let workspaceBrowser = false;
|
|
482
|
+
try {
|
|
483
|
+
const workspace = await agent.getWorkspace({ requestContext });
|
|
484
|
+
workspaceId = workspace?.id;
|
|
485
|
+
workspaceBrowser = Boolean(workspace?.browser);
|
|
486
|
+
} catch {}
|
|
487
|
+
const hasBrowser = browserTools.length > 0 || workspaceBrowser;
|
|
488
|
+
const model = llm?.getModel();
|
|
489
|
+
const supportsMemory = typeof agent.supportsMemory === "function" ? agent.supportsMemory() : true;
|
|
490
|
+
let models;
|
|
491
|
+
try {
|
|
492
|
+
models = await agent.getModelList(requestContext);
|
|
493
|
+
} catch (error) {
|
|
494
|
+
logger.warn("Error getting model list for agent", {
|
|
495
|
+
agentName: agent.name,
|
|
496
|
+
error
|
|
497
|
+
});
|
|
498
|
+
}
|
|
499
|
+
const modelList = models?.map((md) => ({
|
|
500
|
+
...md,
|
|
501
|
+
model: {
|
|
502
|
+
modelId: md.model.modelId,
|
|
503
|
+
provider: md.model.provider,
|
|
504
|
+
modelVersion: md.model.specificationVersion
|
|
505
|
+
}
|
|
506
|
+
}));
|
|
507
|
+
let serializedRequestContextSchema;
|
|
508
|
+
if (agent.requestContextSchema) try {
|
|
509
|
+
serializedRequestContextSchema = stringify(zodToJsonSchema(agent.requestContextSchema));
|
|
510
|
+
} catch (error) {
|
|
511
|
+
logger.error("Error serializing requestContextSchema for agent", {
|
|
512
|
+
agentName: agent.name,
|
|
513
|
+
error
|
|
514
|
+
});
|
|
515
|
+
}
|
|
516
|
+
return {
|
|
517
|
+
id: agent.id || id,
|
|
518
|
+
name: agent.name,
|
|
519
|
+
description,
|
|
520
|
+
metadata,
|
|
521
|
+
instructions,
|
|
522
|
+
agents: serializedAgentAgents,
|
|
523
|
+
tools: serializedAgentTools,
|
|
524
|
+
workflows: serializedAgentWorkflows,
|
|
525
|
+
skills: serializedSkills,
|
|
526
|
+
workspaceTools,
|
|
527
|
+
browserTools,
|
|
528
|
+
hasBrowser,
|
|
529
|
+
workspaceId,
|
|
530
|
+
inputProcessors: serializedInputProcessors,
|
|
531
|
+
outputProcessors: serializedOutputProcessors,
|
|
532
|
+
...getAgentModelRef(agent.model, llm),
|
|
533
|
+
modelVersion: model?.specificationVersion,
|
|
534
|
+
supportsMemory,
|
|
535
|
+
defaultOptions,
|
|
536
|
+
modelList,
|
|
537
|
+
modelListEditable: modelList ? typeof agent.model !== "function" : void 0,
|
|
538
|
+
defaultGenerateOptionsLegacy,
|
|
539
|
+
defaultStreamOptionsLegacy,
|
|
540
|
+
requestContextSchema: serializedRequestContextSchema,
|
|
541
|
+
source: agent.source ?? "code",
|
|
542
|
+
editor: agent.__getEditorConfig?.(),
|
|
543
|
+
...agent.toRawConfig()?.status ? { status: agent.toRawConfig().status } : {},
|
|
544
|
+
...agent.toRawConfig()?.activeVersionId ? { activeVersionId: agent.toRawConfig().activeVersionId } : {},
|
|
545
|
+
hasDraft: !!(agent.toRawConfig()?.resolvedVersionId && agent.toRawConfig()?.activeVersionId && agent.toRawConfig().resolvedVersionId !== agent.toRawConfig().activeVersionId)
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
function extractVersionOptions(requestContext, bodyRequestContext) {
|
|
549
|
+
const agentVersionId = requestContext?.get("agentVersionId");
|
|
550
|
+
if (typeof agentVersionId === "string" && agentVersionId) return { versionId: agentVersionId };
|
|
551
|
+
const bodyVersionId = bodyRequestContext?.agentVersionId;
|
|
552
|
+
if (typeof bodyVersionId === "string" && bodyVersionId) return { versionId: bodyVersionId };
|
|
553
|
+
}
|
|
554
|
+
async function getAgentFromSystem({ mastra, agentId, versionOptions, requestContext }) {
|
|
555
|
+
const logger = mastra.getLogger();
|
|
556
|
+
if (!agentId) throw new HTTPException(400, { message: "Agent ID is required" });
|
|
557
|
+
let agent;
|
|
558
|
+
try {
|
|
559
|
+
agent = mastra.getAgentById(agentId);
|
|
560
|
+
} catch (error) {
|
|
561
|
+
logger.debug("Error getting agent from mastra, searching agents for agent", error);
|
|
562
|
+
}
|
|
563
|
+
if (!agent) {
|
|
564
|
+
logger.debug("Agent not found, looking through sub-agents", { agentId });
|
|
565
|
+
const agents = mastra.listAgents();
|
|
566
|
+
if (Object.keys(agents || {}).length) for (const [_, ag] of Object.entries(agents)) try {
|
|
567
|
+
const subAgent = (await ag.listAgents())[agentId];
|
|
568
|
+
if (subAgent instanceof Agent) {
|
|
569
|
+
agent = subAgent;
|
|
570
|
+
break;
|
|
571
|
+
}
|
|
572
|
+
} catch (error) {
|
|
573
|
+
logger.debug("Error getting agent from agent", error);
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
if (agent && mastra.getEditor) try {
|
|
577
|
+
const editorAgent = mastra.getEditor()?.agent;
|
|
578
|
+
if (editorAgent) agent = await editorAgent.applyStoredOverrides(agent, versionOptions ?? { status: "published" }, requestContext);
|
|
579
|
+
} catch (error) {
|
|
580
|
+
logger.debug("Error applying stored overrides to code agent", error);
|
|
581
|
+
}
|
|
582
|
+
if (!agent) {
|
|
583
|
+
logger.debug("Agent not found in code-defined agents, looking in stored agents", { agentId });
|
|
584
|
+
try {
|
|
585
|
+
agent = await mastra.getEditor()?.agent.getById(agentId, versionOptions) ?? null;
|
|
586
|
+
} catch (error) {
|
|
587
|
+
logger.debug("Error getting stored agent", error);
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
if (!agent) throw new HTTPException(404, { message: `Agent with id ${agentId} not found` });
|
|
591
|
+
return agent;
|
|
592
|
+
}
|
|
593
|
+
async function formatAgent({ mastra, agent, requestContext, isStudio }) {
|
|
594
|
+
const logger = mastra.getLogger();
|
|
595
|
+
const description = agent.getDescription();
|
|
596
|
+
let metadata;
|
|
597
|
+
if (typeof agent.getMetadata === "function") try {
|
|
598
|
+
metadata = await agent.getMetadata({ requestContext });
|
|
599
|
+
} catch (error) {
|
|
600
|
+
logger.warn(`Failed to get metadata for agent ${agent.name}`, { error });
|
|
601
|
+
}
|
|
602
|
+
let tools = {};
|
|
603
|
+
try {
|
|
604
|
+
tools = await agent.listTools({ requestContext });
|
|
605
|
+
} catch (error) {
|
|
606
|
+
logger.warn("Error listing tools for agent", {
|
|
607
|
+
agentName: agent.name,
|
|
608
|
+
error
|
|
609
|
+
});
|
|
610
|
+
}
|
|
611
|
+
const serializedAgentTools = await getSerializedAgentTools(tools);
|
|
612
|
+
let serializedAgentWorkflows = {};
|
|
613
|
+
if ("listWorkflows" in agent) try {
|
|
614
|
+
const workflows = await agent.listWorkflows({ requestContext });
|
|
615
|
+
serializedAgentWorkflows = Object.entries(workflows || {}).reduce((acc, [key, workflow]) => {
|
|
616
|
+
return {
|
|
617
|
+
...acc,
|
|
618
|
+
[key]: {
|
|
619
|
+
name: workflow.name || "Unnamed workflow",
|
|
620
|
+
steps: Object.entries(workflow.steps).reduce((acc, [key, step]) => {
|
|
621
|
+
return {
|
|
622
|
+
...acc,
|
|
623
|
+
[key]: {
|
|
624
|
+
id: step.id,
|
|
625
|
+
description: step.description
|
|
626
|
+
}
|
|
627
|
+
};
|
|
628
|
+
}, {})
|
|
629
|
+
}
|
|
630
|
+
};
|
|
631
|
+
}, {});
|
|
632
|
+
} catch (error) {
|
|
633
|
+
logger.error("Error getting workflows for agent", {
|
|
634
|
+
agentName: agent.name,
|
|
635
|
+
error
|
|
636
|
+
});
|
|
637
|
+
}
|
|
638
|
+
const instructionsRequestContext = isStudio ? new Proxy(requestContext, { get(target, prop) {
|
|
639
|
+
if (prop === "get") return function(key) {
|
|
640
|
+
return target.get(key) ?? `<${key}>`;
|
|
641
|
+
};
|
|
642
|
+
return Reflect.get(target, prop);
|
|
643
|
+
} }) : requestContext;
|
|
644
|
+
let instructions;
|
|
645
|
+
try {
|
|
646
|
+
instructions = await agent.getInstructions({ requestContext: instructionsRequestContext });
|
|
647
|
+
} catch (error) {
|
|
648
|
+
logger.warn("Error getting instructions for agent", {
|
|
649
|
+
agentName: agent.name,
|
|
650
|
+
error
|
|
651
|
+
});
|
|
652
|
+
}
|
|
653
|
+
let llm;
|
|
654
|
+
try {
|
|
655
|
+
llm = await agent.getLLM({ requestContext });
|
|
656
|
+
} catch (error) {
|
|
657
|
+
logger.warn("Error getting LLM for agent", {
|
|
658
|
+
agentName: agent.name,
|
|
659
|
+
error
|
|
660
|
+
});
|
|
661
|
+
}
|
|
662
|
+
let defaultGenerateOptionsLegacy;
|
|
663
|
+
try {
|
|
664
|
+
defaultGenerateOptionsLegacy = await agent.getDefaultGenerateOptionsLegacy({ requestContext });
|
|
665
|
+
} catch (error) {
|
|
666
|
+
logger.warn("Error getting default generate options for agent", {
|
|
667
|
+
agentName: agent.name,
|
|
668
|
+
error
|
|
669
|
+
});
|
|
670
|
+
}
|
|
671
|
+
let defaultStreamOptionsLegacy;
|
|
672
|
+
try {
|
|
673
|
+
defaultStreamOptionsLegacy = await agent.getDefaultStreamOptionsLegacy({ requestContext });
|
|
674
|
+
} catch (error) {
|
|
675
|
+
logger.warn("Error getting default stream options for agent", {
|
|
676
|
+
agentName: agent.name,
|
|
677
|
+
error
|
|
678
|
+
});
|
|
679
|
+
}
|
|
680
|
+
let defaultOptions;
|
|
681
|
+
try {
|
|
682
|
+
defaultOptions = await agent.getDefaultOptions({ requestContext });
|
|
683
|
+
} catch (error) {
|
|
684
|
+
logger.warn("Error getting default options for agent", {
|
|
685
|
+
agentName: agent.name,
|
|
686
|
+
error
|
|
687
|
+
});
|
|
688
|
+
}
|
|
689
|
+
const model = llm?.getModel();
|
|
690
|
+
const supportsMemory = typeof agent.supportsMemory === "function" ? agent.supportsMemory() : true;
|
|
691
|
+
let models;
|
|
692
|
+
try {
|
|
693
|
+
models = await agent.getModelList(requestContext);
|
|
694
|
+
} catch (error) {
|
|
695
|
+
logger.warn("Error getting model list for agent", {
|
|
696
|
+
agentName: agent.name,
|
|
697
|
+
error
|
|
698
|
+
});
|
|
699
|
+
}
|
|
700
|
+
const modelList = models?.map((md) => ({
|
|
701
|
+
...md,
|
|
702
|
+
model: {
|
|
703
|
+
modelId: md.model.modelId,
|
|
704
|
+
provider: md.model.provider,
|
|
705
|
+
modelVersion: md.model.specificationVersion
|
|
706
|
+
}
|
|
707
|
+
}));
|
|
708
|
+
const serializedAgentAgents = await getSerializedAgentDefinition({
|
|
709
|
+
agent,
|
|
710
|
+
requestContext,
|
|
711
|
+
logger
|
|
712
|
+
});
|
|
713
|
+
let serializedInputProcessors = [];
|
|
714
|
+
let serializedOutputProcessors = [];
|
|
715
|
+
try {
|
|
716
|
+
const configuredProcessorWorkflows = await agent.getConfiguredProcessorWorkflows();
|
|
717
|
+
const inputProcessorWorkflows = configuredProcessorWorkflows.filter((w) => w.id.endsWith("-input-processor"));
|
|
718
|
+
const outputProcessorWorkflows = configuredProcessorWorkflows.filter((w) => w.id.endsWith("-output-processor"));
|
|
719
|
+
serializedInputProcessors = getSerializedProcessors(inputProcessorWorkflows);
|
|
720
|
+
serializedOutputProcessors = getSerializedProcessors(outputProcessorWorkflows);
|
|
721
|
+
} catch (error) {
|
|
722
|
+
logger.error("Error getting configured processors for agent", {
|
|
723
|
+
agentName: agent.name,
|
|
724
|
+
error
|
|
725
|
+
});
|
|
726
|
+
}
|
|
727
|
+
const serializedSkills = await getSerializedSkillsFromAgent(agent, requestContext);
|
|
728
|
+
const workspaceTools = await getWorkspaceToolsFromAgent(agent, requestContext);
|
|
729
|
+
const browserTools = getBrowserToolsFromAgent(agent, createBrowserToolsErrorLogger(logger, agent.id));
|
|
730
|
+
let workspaceId;
|
|
731
|
+
let workspaceBrowser = false;
|
|
732
|
+
try {
|
|
733
|
+
const workspace = await agent.getWorkspace({ requestContext });
|
|
734
|
+
workspaceId = workspace?.id;
|
|
735
|
+
workspaceBrowser = Boolean(workspace?.browser);
|
|
736
|
+
} catch {}
|
|
737
|
+
const hasBrowser = browserTools.length > 0 || workspaceBrowser;
|
|
738
|
+
let serializedRequestContextSchema;
|
|
739
|
+
if (agent.requestContextSchema) try {
|
|
740
|
+
serializedRequestContextSchema = stringify(zodToJsonSchema(agent.requestContextSchema));
|
|
741
|
+
} catch (error) {
|
|
742
|
+
logger.error("Error serializing requestContextSchema for agent", {
|
|
743
|
+
agentName: agent.name,
|
|
744
|
+
error
|
|
745
|
+
});
|
|
746
|
+
}
|
|
747
|
+
return {
|
|
748
|
+
name: agent.name,
|
|
749
|
+
description,
|
|
750
|
+
metadata,
|
|
751
|
+
instructions,
|
|
752
|
+
tools: serializedAgentTools,
|
|
753
|
+
agents: serializedAgentAgents,
|
|
754
|
+
workflows: serializedAgentWorkflows,
|
|
755
|
+
skills: serializedSkills,
|
|
756
|
+
workspaceTools,
|
|
757
|
+
browserTools,
|
|
758
|
+
hasBrowser,
|
|
759
|
+
workspaceId,
|
|
760
|
+
inputProcessors: serializedInputProcessors,
|
|
761
|
+
outputProcessors: serializedOutputProcessors,
|
|
762
|
+
...getAgentModelRef(agent.model, llm),
|
|
763
|
+
modelVersion: model?.specificationVersion,
|
|
764
|
+
supportsMemory,
|
|
765
|
+
modelList,
|
|
766
|
+
modelListEditable: modelList ? typeof agent.model !== "function" : void 0,
|
|
767
|
+
defaultOptions,
|
|
768
|
+
defaultGenerateOptionsLegacy,
|
|
769
|
+
defaultStreamOptionsLegacy,
|
|
770
|
+
requestContextSchema: serializedRequestContextSchema,
|
|
771
|
+
source: agent.source ?? "code",
|
|
772
|
+
editor: agent.__getEditorConfig?.(),
|
|
773
|
+
...agent.toRawConfig()?.status ? { status: agent.toRawConfig().status } : {}
|
|
774
|
+
};
|
|
775
|
+
}
|
|
776
|
+
const LIST_AGENTS_ROUTE = createRoute({
|
|
777
|
+
method: "GET",
|
|
778
|
+
path: "/agents",
|
|
779
|
+
responseType: "json",
|
|
780
|
+
queryParamSchema: z.object({ partial: z.string().optional() }),
|
|
781
|
+
responseSchema: listAgentsResponseSchema,
|
|
782
|
+
summary: "List all agents",
|
|
783
|
+
description: "Returns a list of all available agents in the system (both code-defined and stored)",
|
|
784
|
+
tags: ["Agents"],
|
|
785
|
+
requiresAuth: true,
|
|
786
|
+
requiresPermission: MastraFGAPermissions.AGENTS_READ,
|
|
787
|
+
handler: async ({ mastra, requestContext, partial }) => {
|
|
788
|
+
try {
|
|
789
|
+
const codeAgents = mastra.listAgents();
|
|
790
|
+
const isPartial = partial === "true";
|
|
791
|
+
const editor = mastra.getEditor?.();
|
|
792
|
+
const logger = mastra.getLogger();
|
|
793
|
+
const serializedCodeAgentsMap = await Promise.allSettled(Object.entries(codeAgents).map(async ([id, agent]) => {
|
|
794
|
+
let mergedAgent = agent;
|
|
795
|
+
if (editor) try {
|
|
796
|
+
mergedAgent = await editor.agent.applyStoredOverrides(agent, void 0, requestContext);
|
|
797
|
+
} catch {}
|
|
798
|
+
return formatAgentList({
|
|
799
|
+
id,
|
|
800
|
+
mastra,
|
|
801
|
+
agent: mergedAgent,
|
|
802
|
+
requestContext,
|
|
803
|
+
partial: isPartial
|
|
804
|
+
});
|
|
805
|
+
}));
|
|
806
|
+
const serializedAgents = {};
|
|
807
|
+
for (let i = 0; i < serializedCodeAgentsMap.length; i++) {
|
|
808
|
+
const settled = serializedCodeAgentsMap[i];
|
|
809
|
+
if (settled.status === "fulfilled") {
|
|
810
|
+
const { id, ...rest } = settled.value;
|
|
811
|
+
serializedAgents[id] = {
|
|
812
|
+
id,
|
|
813
|
+
...rest
|
|
814
|
+
};
|
|
815
|
+
} else {
|
|
816
|
+
const agentId = Object.keys(codeAgents)[i];
|
|
817
|
+
logger.warn("Failed to serialize agent", {
|
|
818
|
+
agentId,
|
|
819
|
+
error: settled.reason
|
|
820
|
+
});
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
try {
|
|
824
|
+
const editor = mastra.getEditor();
|
|
825
|
+
let storedAgentsResult;
|
|
826
|
+
try {
|
|
827
|
+
storedAgentsResult = await editor?.agent.list();
|
|
828
|
+
} catch (error) {
|
|
829
|
+
console.error("Error listing stored agents:", error);
|
|
830
|
+
storedAgentsResult = null;
|
|
831
|
+
}
|
|
832
|
+
const codeAgentIds = /* @__PURE__ */ new Set();
|
|
833
|
+
for (const [key, agent] of Object.entries(codeAgents)) {
|
|
834
|
+
codeAgentIds.add(key);
|
|
835
|
+
if (agent?.id) codeAgentIds.add(agent.id);
|
|
836
|
+
}
|
|
837
|
+
if (storedAgentsResult?.agents) for (const storedAgentConfig of storedAgentsResult.agents) {
|
|
838
|
+
if (codeAgentIds.has(storedAgentConfig.id)) continue;
|
|
839
|
+
try {
|
|
840
|
+
const agent = await editor?.agent.getById(storedAgentConfig.id, { status: "draft" });
|
|
841
|
+
if (!agent) continue;
|
|
842
|
+
const serialized = await formatAgentList({
|
|
843
|
+
id: agent.id,
|
|
844
|
+
mastra,
|
|
845
|
+
agent,
|
|
846
|
+
requestContext,
|
|
847
|
+
partial: isPartial
|
|
848
|
+
});
|
|
849
|
+
if (!serializedAgents[serialized.id]) serializedAgents[serialized.id] = serialized;
|
|
850
|
+
} catch (agentError) {
|
|
851
|
+
mastra.getLogger().warn("Failed to serialize stored agent", {
|
|
852
|
+
agentId: storedAgentConfig.id,
|
|
853
|
+
error: agentError
|
|
854
|
+
});
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
} catch (storageError) {
|
|
858
|
+
mastra.getLogger().debug("Could not fetch stored agents", { error: storageError });
|
|
859
|
+
}
|
|
860
|
+
const fgaProvider = mastra.getServer?.()?.fga;
|
|
861
|
+
const user = requestContext?.get("user");
|
|
862
|
+
if (fgaProvider && user) {
|
|
863
|
+
const agentList = Object.values(serializedAgents);
|
|
864
|
+
const accessible = await fgaProvider.filterAccessible(user, agentList, "agent", MastraFGAPermissions.AGENTS_READ);
|
|
865
|
+
const accessibleSet = new Set(accessible.map((a) => a.id));
|
|
866
|
+
for (const id of Object.keys(serializedAgents)) if (!accessibleSet.has(id)) delete serializedAgents[id];
|
|
867
|
+
}
|
|
868
|
+
return serializedAgents;
|
|
869
|
+
} catch (error) {
|
|
870
|
+
return handleError(error, "Error getting agents");
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
});
|
|
874
|
+
const GET_AGENT_BY_ID_ROUTE = createRoute({
|
|
875
|
+
method: "GET",
|
|
876
|
+
path: "/agents/:agentId",
|
|
877
|
+
responseType: "json",
|
|
878
|
+
pathParamSchema: agentIdPathParams,
|
|
879
|
+
queryParamSchema: agentVersionQuerySchema,
|
|
880
|
+
responseSchema: serializedAgentSchema,
|
|
881
|
+
summary: "Get agent by ID",
|
|
882
|
+
description: "Returns details for a specific agent including configuration, tools, and memory settings. Use query params to control which stored config version is used for overrides: ?status=published (active version, default), ?status=draft (latest draft), or ?versionId=<id> (specific version). Use either status or versionId, not both.",
|
|
883
|
+
tags: ["Agents"],
|
|
884
|
+
requiresAuth: true,
|
|
885
|
+
requiresPermission: MastraFGAPermissions.AGENTS_READ,
|
|
886
|
+
handler: async ({ agentId, mastra, requestContext, status, versionId }) => {
|
|
887
|
+
try {
|
|
888
|
+
return await formatAgent({
|
|
889
|
+
mastra,
|
|
890
|
+
agent: await getAgentFromSystem({
|
|
891
|
+
mastra,
|
|
892
|
+
agentId,
|
|
893
|
+
versionOptions: versionId ? { versionId } : status ? { status } : void 0,
|
|
894
|
+
requestContext
|
|
895
|
+
}),
|
|
896
|
+
requestContext,
|
|
897
|
+
isStudio: getIsStudioFromContext(requestContext)
|
|
898
|
+
});
|
|
899
|
+
} catch (error) {
|
|
900
|
+
return handleError(error, "Error getting agent");
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
});
|
|
904
|
+
/**
|
|
905
|
+
* POST /agents/:agentId/clone - Clone an agent to a stored agent
|
|
906
|
+
*/
|
|
907
|
+
const CLONE_AGENT_ROUTE = createRoute({
|
|
908
|
+
method: "POST",
|
|
909
|
+
path: "/agents/:agentId/clone",
|
|
910
|
+
responseType: "json",
|
|
911
|
+
pathParamSchema: agentIdPathParams,
|
|
912
|
+
bodySchema: z.object({
|
|
913
|
+
newId: z.string().optional().describe("ID for the cloned agent. If not provided, derived from agent ID."),
|
|
914
|
+
newName: z.string().optional().describe("Name for the cloned agent. Defaults to \"{name} (Clone)\"."),
|
|
915
|
+
metadata: z.record(z.string(), z.unknown()).optional(),
|
|
916
|
+
authorId: z.string().optional()
|
|
917
|
+
}),
|
|
918
|
+
responseSchema: createStoredAgentResponseSchema,
|
|
919
|
+
summary: "Clone agent",
|
|
920
|
+
description: "Clones a code-defined or stored agent to a new stored agent in the database",
|
|
921
|
+
tags: ["Agents"],
|
|
922
|
+
requiresAuth: true,
|
|
923
|
+
handler: async ({ agentId, mastra, newId, newName, metadata, authorId, requestContext }) => {
|
|
924
|
+
try {
|
|
925
|
+
const editor = mastra.getEditor();
|
|
926
|
+
if (!editor) return handleError(/* @__PURE__ */ new Error("Editor is not configured on the Mastra instance"), "Error cloning agent");
|
|
927
|
+
const agent = await getAgentFromSystem({
|
|
928
|
+
mastra,
|
|
929
|
+
agentId,
|
|
930
|
+
versionOptions: extractVersionOptions(requestContext)
|
|
931
|
+
});
|
|
932
|
+
const cloneId = toSlug(newId || `${agentId}-clone`);
|
|
933
|
+
return await editor.agent.clone(agent, {
|
|
934
|
+
newId: cloneId,
|
|
935
|
+
newName,
|
|
936
|
+
metadata,
|
|
937
|
+
authorId,
|
|
938
|
+
requestContext
|
|
939
|
+
});
|
|
940
|
+
} catch (error) {
|
|
941
|
+
return handleError(error, "Error cloning agent");
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
});
|
|
945
|
+
const GENERATE_AGENT_ROUTE = createRoute({
|
|
946
|
+
method: "POST",
|
|
947
|
+
path: "/agents/:agentId/generate",
|
|
948
|
+
responseType: "json",
|
|
949
|
+
pathParamSchema: agentIdPathParams,
|
|
950
|
+
bodySchema: agentExecutionBodySchema,
|
|
951
|
+
responseSchema: generateResponseSchema,
|
|
952
|
+
summary: "Generate agent response",
|
|
953
|
+
description: "Executes an agent with the provided messages and returns the complete response",
|
|
954
|
+
tags: ["Agents"],
|
|
955
|
+
requiresAuth: true,
|
|
956
|
+
requiresPermission: MastraFGAPermissions.AGENTS_EXECUTE,
|
|
957
|
+
handler: async ({ agentId, mastra, abortSignal, requestContext: serverRequestContext, ...params }) => {
|
|
958
|
+
try {
|
|
959
|
+
sanitizeBody(params, [
|
|
960
|
+
"tools",
|
|
961
|
+
"actor",
|
|
962
|
+
"scopes"
|
|
963
|
+
]);
|
|
964
|
+
stripClientCredentialHeaders(params);
|
|
965
|
+
const { messages, memory: memoryOption, requestContext: bodyRequestContext, versions, ...rest } = params;
|
|
966
|
+
validateBody({ messages });
|
|
967
|
+
const versionOptions = extractVersionOptions(serverRequestContext, bodyRequestContext);
|
|
968
|
+
const agent = await getAgentFromSystem({
|
|
969
|
+
mastra,
|
|
970
|
+
agentId,
|
|
971
|
+
versionOptions,
|
|
972
|
+
requestContext: serverRequestContext
|
|
973
|
+
});
|
|
974
|
+
mergeBodyRequestContext(serverRequestContext, bodyRequestContext);
|
|
975
|
+
stashVersionOverrides(serverRequestContext, versions);
|
|
976
|
+
ensureDefaultVersionStatus(serverRequestContext, versionOptions);
|
|
977
|
+
let authorizedMemoryOption = memoryOption;
|
|
978
|
+
if (memoryOption) {
|
|
979
|
+
const clientThreadId = typeof memoryOption.thread === "string" ? memoryOption.thread : memoryOption.thread?.id;
|
|
980
|
+
const effectiveResourceId = getEffectiveResourceId(serverRequestContext, memoryOption.resource);
|
|
981
|
+
requireEffectiveResourceId(effectiveResourceId);
|
|
982
|
+
const effectiveThreadId = getEffectiveThreadId(serverRequestContext, clientThreadId);
|
|
983
|
+
if (effectiveThreadId) {
|
|
984
|
+
const memoryInstance = await agent.getMemory({ requestContext: serverRequestContext });
|
|
985
|
+
if (memoryInstance) {
|
|
986
|
+
const thread = await memoryInstance.getThreadById({ threadId: effectiveThreadId });
|
|
987
|
+
if (thread) await enforceThreadAccess({
|
|
988
|
+
mastra,
|
|
989
|
+
requestContext: serverRequestContext,
|
|
990
|
+
threadId: effectiveThreadId,
|
|
991
|
+
thread,
|
|
992
|
+
effectiveResourceId,
|
|
993
|
+
permission: MastraFGAPermissions.MEMORY_WRITE
|
|
994
|
+
});
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
authorizedMemoryOption = {
|
|
998
|
+
...memoryOption,
|
|
999
|
+
resource: effectiveResourceId ?? memoryOption.resource,
|
|
1000
|
+
thread: applyEffectiveThreadId(memoryOption.thread, effectiveThreadId)
|
|
1001
|
+
};
|
|
1002
|
+
}
|
|
1003
|
+
const { structuredOutput, ...restOptions } = rest;
|
|
1004
|
+
const options = {
|
|
1005
|
+
...restOptions,
|
|
1006
|
+
context: restOptions.context,
|
|
1007
|
+
requestContext: serverRequestContext,
|
|
1008
|
+
memory: authorizedMemoryOption,
|
|
1009
|
+
abortSignal
|
|
1010
|
+
};
|
|
1011
|
+
return structuredOutput ? await agent.generate(messages, {
|
|
1012
|
+
...options,
|
|
1013
|
+
structuredOutput
|
|
1014
|
+
}) : await agent.generate(messages, options);
|
|
1015
|
+
} catch (error) {
|
|
1016
|
+
return handleError(error, "Error generating from agent");
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
});
|
|
1020
|
+
const GENERATE_LEGACY_ROUTE = createRoute({
|
|
1021
|
+
method: "POST",
|
|
1022
|
+
path: "/agents/:agentId/generate-legacy",
|
|
1023
|
+
responseType: "json",
|
|
1024
|
+
pathParamSchema: agentIdPathParams,
|
|
1025
|
+
bodySchema: agentExecutionLegacyBodySchema,
|
|
1026
|
+
responseSchema: generateResponseSchema,
|
|
1027
|
+
summary: "[DEPRECATED] Generate with legacy format",
|
|
1028
|
+
description: "Legacy endpoint for generating agent responses. Use /agents/:agentId/generate instead.",
|
|
1029
|
+
tags: ["Agents", "Legacy"],
|
|
1030
|
+
requiresAuth: true,
|
|
1031
|
+
handler: async ({ mastra, agentId, abortSignal, requestContext, ...params }) => {
|
|
1032
|
+
try {
|
|
1033
|
+
const agent = await getAgentFromSystem({
|
|
1034
|
+
mastra,
|
|
1035
|
+
agentId,
|
|
1036
|
+
versionOptions: extractVersionOptions(requestContext),
|
|
1037
|
+
requestContext
|
|
1038
|
+
});
|
|
1039
|
+
sanitizeBody(params, [
|
|
1040
|
+
"tools",
|
|
1041
|
+
"actor",
|
|
1042
|
+
"scopes"
|
|
1043
|
+
]);
|
|
1044
|
+
stripClientCredentialHeaders(params);
|
|
1045
|
+
const { messages, resourceId, resourceid, threadId, ...rest } = params;
|
|
1046
|
+
const effectiveResourceId = getEffectiveResourceId(requestContext, resourceId ?? resourceid);
|
|
1047
|
+
const effectiveThreadId = getEffectiveThreadId(requestContext, threadId);
|
|
1048
|
+
validateBody({ messages });
|
|
1049
|
+
if (effectiveThreadId && !effectiveResourceId || !effectiveThreadId && effectiveResourceId) throw new HTTPException(400, { message: "Both threadId or resourceId must be provided" });
|
|
1050
|
+
if (effectiveThreadId) {
|
|
1051
|
+
const memory = await agent.getMemory({ requestContext });
|
|
1052
|
+
if (memory) {
|
|
1053
|
+
const thread = await memory.getThreadById({ threadId: effectiveThreadId });
|
|
1054
|
+
if (thread) await enforceThreadAccess({
|
|
1055
|
+
mastra,
|
|
1056
|
+
requestContext,
|
|
1057
|
+
threadId: effectiveThreadId,
|
|
1058
|
+
thread,
|
|
1059
|
+
effectiveResourceId,
|
|
1060
|
+
permission: MastraFGAPermissions.MEMORY_WRITE
|
|
1061
|
+
});
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
return await agent.generateLegacy(messages, {
|
|
1065
|
+
...rest,
|
|
1066
|
+
abortSignal,
|
|
1067
|
+
resourceId: effectiveResourceId ?? "",
|
|
1068
|
+
threadId: effectiveThreadId ?? ""
|
|
1069
|
+
});
|
|
1070
|
+
} catch (error) {
|
|
1071
|
+
return handleError(error, "Error generating from agent");
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
});
|
|
1075
|
+
const STREAM_GENERATE_LEGACY_ROUTE = createRoute({
|
|
1076
|
+
method: "POST",
|
|
1077
|
+
path: "/agents/:agentId/stream-legacy",
|
|
1078
|
+
responseType: "datastream-response",
|
|
1079
|
+
pathParamSchema: agentIdPathParams,
|
|
1080
|
+
bodySchema: agentExecutionLegacyBodySchema,
|
|
1081
|
+
responseSchema: streamResponseSchema,
|
|
1082
|
+
summary: "[DEPRECATED] Stream with legacy format",
|
|
1083
|
+
description: "Legacy endpoint for streaming agent responses. Use /agents/:agentId/stream instead.",
|
|
1084
|
+
tags: ["Agents", "Legacy"],
|
|
1085
|
+
requiresAuth: true,
|
|
1086
|
+
handler: async ({ mastra, agentId, abortSignal, requestContext, ...params }) => {
|
|
1087
|
+
try {
|
|
1088
|
+
const agent = await getAgentFromSystem({
|
|
1089
|
+
mastra,
|
|
1090
|
+
agentId,
|
|
1091
|
+
versionOptions: extractVersionOptions(requestContext),
|
|
1092
|
+
requestContext
|
|
1093
|
+
});
|
|
1094
|
+
sanitizeBody(params, [
|
|
1095
|
+
"tools",
|
|
1096
|
+
"actor",
|
|
1097
|
+
"scopes"
|
|
1098
|
+
]);
|
|
1099
|
+
stripClientCredentialHeaders(params);
|
|
1100
|
+
const { messages, resourceId, resourceid, threadId, ...rest } = params;
|
|
1101
|
+
const effectiveResourceId = getEffectiveResourceId(requestContext, resourceId ?? resourceid);
|
|
1102
|
+
const effectiveThreadId = getEffectiveThreadId(requestContext, threadId);
|
|
1103
|
+
validateBody({ messages });
|
|
1104
|
+
if (effectiveThreadId && !effectiveResourceId || !effectiveThreadId && effectiveResourceId) throw new HTTPException(400, { message: "Both threadId or resourceId must be provided" });
|
|
1105
|
+
if (effectiveThreadId) {
|
|
1106
|
+
const memory = await agent.getMemory({ requestContext });
|
|
1107
|
+
if (memory) {
|
|
1108
|
+
const thread = await memory.getThreadById({ threadId: effectiveThreadId });
|
|
1109
|
+
if (thread) await enforceThreadAccess({
|
|
1110
|
+
mastra,
|
|
1111
|
+
requestContext,
|
|
1112
|
+
threadId: effectiveThreadId,
|
|
1113
|
+
thread,
|
|
1114
|
+
effectiveResourceId,
|
|
1115
|
+
permission: MastraFGAPermissions.MEMORY_WRITE
|
|
1116
|
+
});
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
const streamResult = await agent.streamLegacy(messages, {
|
|
1120
|
+
...rest,
|
|
1121
|
+
abortSignal,
|
|
1122
|
+
resourceId: effectiveResourceId ?? "",
|
|
1123
|
+
threadId: effectiveThreadId ?? ""
|
|
1124
|
+
});
|
|
1125
|
+
return rest.output ? streamResult.toTextStreamResponse() : streamResult.toDataStreamResponse({
|
|
1126
|
+
sendUsage: true,
|
|
1127
|
+
sendReasoning: true,
|
|
1128
|
+
getErrorMessage: (error) => {
|
|
1129
|
+
if (error instanceof Error) return `An error occurred while processing your request. ${error.message.replace(/([A-Za-z]:)?[\/][^\s,)]+/g, "<path>").replace(/\s+at\s+[^\n]*/g, "").replace(/Response body:.*/s, "").trim() || "Unknown error"}`;
|
|
1130
|
+
return "An error occurred while processing your request.";
|
|
1131
|
+
}
|
|
1132
|
+
});
|
|
1133
|
+
} catch (error) {
|
|
1134
|
+
return handleError(error, "error streaming agent response");
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
});
|
|
1138
|
+
/**
|
|
1139
|
+
* Collect the full list of configured AI model providers (static registry +
|
|
1140
|
+
* gateway providers) in the shape returned by `GET /agents/providers`.
|
|
1141
|
+
*
|
|
1142
|
+
* Extracted so the agent-builder available-models endpoint can reuse the exact
|
|
1143
|
+
* same source data before applying the model policy.
|
|
1144
|
+
*/
|
|
1145
|
+
async function buildProvidersList(mastra) {
|
|
1146
|
+
const allProviders = {};
|
|
1147
|
+
const blockExternalProviders = process.env.AUTO_BLOCK_EXTERNAL_PROVIDERS === "true" || process.env.AUTO_BLOCK_EXTERNAL_PROVIDERS === "1";
|
|
1148
|
+
const defaultGatewayIds = new Set(defaultGateways.map((gateway) => gateway.id));
|
|
1149
|
+
if (!blockExternalProviders) for (const [id, provider] of Object.entries(PROVIDER_REGISTRY)) allProviders[id] = provider;
|
|
1150
|
+
const gateways = mastra ? Object.values(mastra.listGateways() ?? {}) : [];
|
|
1151
|
+
for (const gateway of gateways) {
|
|
1152
|
+
if (gateway.id === "models.dev") continue;
|
|
1153
|
+
if (blockExternalProviders && defaultGatewayIds.has(gateway.id)) continue;
|
|
1154
|
+
try {
|
|
1155
|
+
const gatewayProviders = await gateway.fetchProviders();
|
|
1156
|
+
for (const [providerId, config] of Object.entries(gatewayProviders)) {
|
|
1157
|
+
const prefixedId = providerId === gateway.id ? gateway.id : `${gateway.id}/${providerId}`;
|
|
1158
|
+
if (!(prefixedId in allProviders)) allProviders[prefixedId] = config;
|
|
1159
|
+
}
|
|
1160
|
+
} catch (error) {
|
|
1161
|
+
console.warn(`Failed to fetch providers from gateway "${gateway.id}":`, error);
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
return Object.entries(allProviders).map(([id, provider]) => {
|
|
1165
|
+
return {
|
|
1166
|
+
id,
|
|
1167
|
+
name: provider.name,
|
|
1168
|
+
label: readStringField(provider, "label") || provider.name,
|
|
1169
|
+
description: readStringField(provider, "description") || "",
|
|
1170
|
+
envVar: provider.apiKeyEnvVar,
|
|
1171
|
+
connected: isProviderConnected(id, allProviders) || isClaimedByGateway(id, provider.models, gateways),
|
|
1172
|
+
docUrl: provider.docUrl,
|
|
1173
|
+
models: [...provider.models]
|
|
1174
|
+
};
|
|
1175
|
+
});
|
|
1176
|
+
}
|
|
1177
|
+
function isClaimedByGateway(providerId, models, gateways) {
|
|
1178
|
+
const [firstModel] = models;
|
|
1179
|
+
if (!firstModel) return false;
|
|
1180
|
+
const routerId = `${providerId}/${firstModel}`;
|
|
1181
|
+
return gateways.some((gateway) => gateway.shouldEnable?.() !== false && gateway.handlesModel?.(routerId) === true);
|
|
1182
|
+
}
|
|
1183
|
+
function readStringField(source, field) {
|
|
1184
|
+
const value = source[field];
|
|
1185
|
+
return typeof value === "string" ? value : void 0;
|
|
1186
|
+
}
|
|
1187
|
+
const GET_PROVIDERS_ROUTE = createRoute({
|
|
1188
|
+
method: "GET",
|
|
1189
|
+
path: "/agents/providers",
|
|
1190
|
+
responseType: "json",
|
|
1191
|
+
responseSchema: providersResponseSchema,
|
|
1192
|
+
summary: "List AI providers",
|
|
1193
|
+
description: "Returns a list of all configured AI model providers",
|
|
1194
|
+
tags: ["Agents"],
|
|
1195
|
+
requiresAuth: true,
|
|
1196
|
+
requiresPermission: ["agents:read"],
|
|
1197
|
+
handler: async ({ mastra }) => {
|
|
1198
|
+
try {
|
|
1199
|
+
return { providers: await buildProvidersList(mastra) };
|
|
1200
|
+
} catch (error) {
|
|
1201
|
+
return handleError(error, "Error fetching providers");
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
});
|
|
1205
|
+
const GENERATE_AGENT_VNEXT_ROUTE = createRoute({
|
|
1206
|
+
method: "POST",
|
|
1207
|
+
path: "/agents/:agentId/generate/vnext",
|
|
1208
|
+
responseType: "json",
|
|
1209
|
+
pathParamSchema: agentIdPathParams,
|
|
1210
|
+
bodySchema: agentExecutionBodySchema,
|
|
1211
|
+
responseSchema: generateResponseSchema,
|
|
1212
|
+
summary: "Generate a response from an agent",
|
|
1213
|
+
description: "Generate a response from an agent",
|
|
1214
|
+
tags: ["Agents"],
|
|
1215
|
+
requiresAuth: true,
|
|
1216
|
+
handler: GENERATE_AGENT_ROUTE.handler
|
|
1217
|
+
});
|
|
1218
|
+
const STREAM_GENERATE_ROUTE = createRoute({
|
|
1219
|
+
method: "POST",
|
|
1220
|
+
path: "/agents/:agentId/stream",
|
|
1221
|
+
responseType: "stream",
|
|
1222
|
+
streamFormat: "sse",
|
|
1223
|
+
pathParamSchema: agentIdPathParams,
|
|
1224
|
+
bodySchema: agentExecutionBodySchema,
|
|
1225
|
+
responseSchema: streamResponseSchema,
|
|
1226
|
+
summary: "Stream agent response",
|
|
1227
|
+
description: "Executes an agent with the provided messages and streams the response in real-time",
|
|
1228
|
+
tags: ["Agents"],
|
|
1229
|
+
requiresAuth: true,
|
|
1230
|
+
requiresPermission: MastraFGAPermissions.AGENTS_EXECUTE,
|
|
1231
|
+
handler: async ({ mastra, agentId, abortSignal, requestContext: serverRequestContext, ...params }) => {
|
|
1232
|
+
try {
|
|
1233
|
+
sanitizeBody(params, [
|
|
1234
|
+
"tools",
|
|
1235
|
+
"actor",
|
|
1236
|
+
"scopes"
|
|
1237
|
+
]);
|
|
1238
|
+
stripClientCredentialHeaders(params);
|
|
1239
|
+
const { messages, memory: memoryOption, requestContext: bodyRequestContext, versions, ...rest } = params;
|
|
1240
|
+
validateBody({ messages });
|
|
1241
|
+
const versionOptions = extractVersionOptions(serverRequestContext, bodyRequestContext);
|
|
1242
|
+
const agent = await getAgentFromSystem({
|
|
1243
|
+
mastra,
|
|
1244
|
+
agentId,
|
|
1245
|
+
versionOptions,
|
|
1246
|
+
requestContext: serverRequestContext
|
|
1247
|
+
});
|
|
1248
|
+
mergeBodyRequestContext(serverRequestContext, bodyRequestContext);
|
|
1249
|
+
stashVersionOverrides(serverRequestContext, versions);
|
|
1250
|
+
ensureDefaultVersionStatus(serverRequestContext, versionOptions);
|
|
1251
|
+
let authorizedMemoryOption = memoryOption;
|
|
1252
|
+
if (memoryOption) {
|
|
1253
|
+
const clientThreadId = typeof memoryOption.thread === "string" ? memoryOption.thread : memoryOption.thread?.id;
|
|
1254
|
+
const effectiveResourceId = getEffectiveResourceId(serverRequestContext, memoryOption.resource);
|
|
1255
|
+
requireEffectiveResourceId(effectiveResourceId);
|
|
1256
|
+
const effectiveThreadId = getEffectiveThreadId(serverRequestContext, clientThreadId);
|
|
1257
|
+
if (effectiveThreadId) {
|
|
1258
|
+
const memoryInstance = await agent.getMemory({ requestContext: serverRequestContext });
|
|
1259
|
+
if (memoryInstance) {
|
|
1260
|
+
const thread = await memoryInstance.getThreadById({ threadId: effectiveThreadId });
|
|
1261
|
+
if (thread) await enforceThreadAccess({
|
|
1262
|
+
mastra,
|
|
1263
|
+
requestContext: serverRequestContext,
|
|
1264
|
+
threadId: effectiveThreadId,
|
|
1265
|
+
thread,
|
|
1266
|
+
effectiveResourceId,
|
|
1267
|
+
permission: MastraFGAPermissions.MEMORY_WRITE
|
|
1268
|
+
});
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
authorizedMemoryOption = {
|
|
1272
|
+
...memoryOption,
|
|
1273
|
+
resource: effectiveResourceId ?? memoryOption.resource,
|
|
1274
|
+
thread: applyEffectiveThreadId(memoryOption.thread, effectiveThreadId)
|
|
1275
|
+
};
|
|
1276
|
+
}
|
|
1277
|
+
const { structuredOutput, untilIdle, ...restOptions } = rest;
|
|
1278
|
+
const options = {
|
|
1279
|
+
...restOptions,
|
|
1280
|
+
requestContext: serverRequestContext,
|
|
1281
|
+
memory: authorizedMemoryOption,
|
|
1282
|
+
abortSignal
|
|
1283
|
+
};
|
|
1284
|
+
if (untilIdle) options.untilIdle = untilIdle;
|
|
1285
|
+
return (structuredOutput ? await agent.stream(messages, {
|
|
1286
|
+
...options,
|
|
1287
|
+
structuredOutput
|
|
1288
|
+
}) : await agent.stream(messages, options)).fullStream;
|
|
1289
|
+
} catch (error) {
|
|
1290
|
+
return handleError(error, "error streaming agent response");
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
});
|
|
1294
|
+
const sendAgentSignalResponseSchema = z.object({
|
|
1295
|
+
accepted: z.literal(true),
|
|
1296
|
+
runId: z.string(),
|
|
1297
|
+
signal: z.unknown().optional()
|
|
1298
|
+
});
|
|
1299
|
+
/**
|
|
1300
|
+
* Maps a rejected `result.accepted` (signal/message routing) to an HTTP error.
|
|
1301
|
+
*
|
|
1302
|
+
* `accepted` only rejects on a setup/misconfig failure surfaced before the run
|
|
1303
|
+
* starts (e.g. no model selected, request-context validation, FGA denied) — these
|
|
1304
|
+
* are tagged `ErrorCategory.USER` and are the caller's fault, so they map to 400.
|
|
1305
|
+
* Anything else falls through to `handleError` (500 by default, or the error's own
|
|
1306
|
+
* status). Run/generation errors never reject `accepted`; they surface on the
|
|
1307
|
+
* `wake` output stream instead.
|
|
1308
|
+
*/
|
|
1309
|
+
function handleSignalRoutingError(error, defaultMessage) {
|
|
1310
|
+
if (error instanceof MastraError && error.category === ErrorCategory.USER && !error.status && !error.details?.status) throw new HTTPException(400, {
|
|
1311
|
+
message: error.message,
|
|
1312
|
+
cause: error
|
|
1313
|
+
});
|
|
1314
|
+
return handleError(error, defaultMessage);
|
|
1315
|
+
}
|
|
1316
|
+
const sendAgentMessageResponseSchema = sendAgentSignalResponseSchema;
|
|
1317
|
+
const SEND_AGENT_SIGNAL_ROUTE = createRoute({
|
|
1318
|
+
method: "POST",
|
|
1319
|
+
path: "/agents/:agentId/signals",
|
|
1320
|
+
responseType: "json",
|
|
1321
|
+
pathParamSchema: agentIdPathParams,
|
|
1322
|
+
bodySchema: sendAgentSignalBodySchema,
|
|
1323
|
+
responseSchema: sendAgentSignalResponseSchema,
|
|
1324
|
+
summary: "Send agent signal",
|
|
1325
|
+
description: "Sends a signal to an active agent run or starts a memory thread run when the thread is idle",
|
|
1326
|
+
tags: ["Agents", "Streaming"],
|
|
1327
|
+
requiresAuth: true,
|
|
1328
|
+
requiresPermission: "agents:execute",
|
|
1329
|
+
handler: async ({ mastra, agentId, requestContext: serverRequestContext, signal, runId, resourceId, threadId, ifActive, ifIdle }) => {
|
|
1330
|
+
try {
|
|
1331
|
+
const idleStreamOptions = ifIdle?.streamOptions;
|
|
1332
|
+
const bodyRequestContext = idleStreamOptions?.requestContext;
|
|
1333
|
+
const normalizedIdleStreamOptions = normalizePublicExecutionOptions(idleStreamOptions, serverRequestContext);
|
|
1334
|
+
const versionOptions = extractVersionOptions(serverRequestContext, bodyRequestContext);
|
|
1335
|
+
const agent = await getAgentFromSystem({
|
|
1336
|
+
mastra,
|
|
1337
|
+
agentId,
|
|
1338
|
+
versionOptions,
|
|
1339
|
+
requestContext: serverRequestContext
|
|
1340
|
+
});
|
|
1341
|
+
stashVersionOverrides(serverRequestContext, normalizedIdleStreamOptions?.versions);
|
|
1342
|
+
ensureDefaultVersionStatus(serverRequestContext, versionOptions);
|
|
1343
|
+
const effectiveResourceId = getEffectiveResourceId(serverRequestContext, resourceId);
|
|
1344
|
+
const effectiveThreadId = getEffectiveThreadId(serverRequestContext, threadId);
|
|
1345
|
+
const ifIdleWithContext = { ifIdle: {
|
|
1346
|
+
...ifIdle ?? {},
|
|
1347
|
+
streamOptions: {
|
|
1348
|
+
...normalizedIdleStreamOptions ?? {},
|
|
1349
|
+
requestContext: serverRequestContext
|
|
1350
|
+
}
|
|
1351
|
+
} };
|
|
1352
|
+
if (effectiveThreadId && effectiveResourceId) {
|
|
1353
|
+
const memory = await agent.getMemory({ requestContext: serverRequestContext });
|
|
1354
|
+
if (memory) {
|
|
1355
|
+
const thread = await memory.getThreadById({ threadId: effectiveThreadId });
|
|
1356
|
+
await validateThreadOwnership(thread, effectiveResourceId);
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
if (typeof agent.sendSignal !== "function") throw new HTTPException(501, { message: "agent signals are not supported by this Mastra core version" });
|
|
1360
|
+
const agentSignal = signal;
|
|
1361
|
+
if (runId) {
|
|
1362
|
+
const result = await agent.sendSignal(agentSignal, {
|
|
1363
|
+
runId,
|
|
1364
|
+
...effectiveResourceId ? { resourceId: effectiveResourceId } : {},
|
|
1365
|
+
...effectiveThreadId ? { threadId: effectiveThreadId } : {},
|
|
1366
|
+
...ifActive ? { ifActive } : {}
|
|
1367
|
+
});
|
|
1368
|
+
const settled = await result.accepted;
|
|
1369
|
+
const settledRunId = "runId" in settled ? settled.runId : runId;
|
|
1370
|
+
return result.signal === void 0 ? {
|
|
1371
|
+
accepted: true,
|
|
1372
|
+
runId: settledRunId
|
|
1373
|
+
} : {
|
|
1374
|
+
accepted: true,
|
|
1375
|
+
runId: settledRunId,
|
|
1376
|
+
signal: result.signal
|
|
1377
|
+
};
|
|
1378
|
+
}
|
|
1379
|
+
if (!effectiveResourceId || !effectiveThreadId) throw new HTTPException(400, { message: "resourceId and threadId are required when runId is not provided" });
|
|
1380
|
+
const result = await agent.sendSignal(agentSignal, {
|
|
1381
|
+
resourceId: effectiveResourceId,
|
|
1382
|
+
threadId: effectiveThreadId,
|
|
1383
|
+
...ifActive ? { ifActive } : {},
|
|
1384
|
+
...ifIdleWithContext
|
|
1385
|
+
});
|
|
1386
|
+
const settled = await result.accepted;
|
|
1387
|
+
const settledRunId = "runId" in settled ? settled.runId : result.signal?.id;
|
|
1388
|
+
return result.signal === void 0 ? {
|
|
1389
|
+
accepted: true,
|
|
1390
|
+
runId: settledRunId
|
|
1391
|
+
} : {
|
|
1392
|
+
accepted: true,
|
|
1393
|
+
runId: settledRunId,
|
|
1394
|
+
signal: result.signal
|
|
1395
|
+
};
|
|
1396
|
+
} catch (error) {
|
|
1397
|
+
return handleSignalRoutingError(error, "error sending agent signal");
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
});
|
|
1401
|
+
async function handleAgentMessageRoute({ mastra, agentId, requestContext: serverRequestContext, runId, resourceId, threadId, ifActive, ifIdle, methodName, invoke }) {
|
|
1402
|
+
const idleStreamOptions = ifIdle?.streamOptions;
|
|
1403
|
+
const bodyRequestContext = idleStreamOptions?.requestContext;
|
|
1404
|
+
const normalizedIdleStreamOptions = normalizePublicExecutionOptions(idleStreamOptions, serverRequestContext);
|
|
1405
|
+
const versionOptions = extractVersionOptions(serverRequestContext, bodyRequestContext);
|
|
1406
|
+
const agent = await getAgentFromSystem({
|
|
1407
|
+
mastra,
|
|
1408
|
+
agentId,
|
|
1409
|
+
versionOptions,
|
|
1410
|
+
requestContext: serverRequestContext
|
|
1411
|
+
});
|
|
1412
|
+
stashVersionOverrides(serverRequestContext, normalizedIdleStreamOptions?.versions);
|
|
1413
|
+
ensureDefaultVersionStatus(serverRequestContext, versionOptions);
|
|
1414
|
+
const effectiveResourceId = getEffectiveResourceId(serverRequestContext, resourceId);
|
|
1415
|
+
const effectiveThreadId = getEffectiveThreadId(serverRequestContext, threadId);
|
|
1416
|
+
const ifIdleWithContext = { ifIdle: {
|
|
1417
|
+
...ifIdle ?? {},
|
|
1418
|
+
streamOptions: {
|
|
1419
|
+
...normalizedIdleStreamOptions ?? {},
|
|
1420
|
+
requestContext: serverRequestContext
|
|
1421
|
+
}
|
|
1422
|
+
} };
|
|
1423
|
+
if (effectiveThreadId && effectiveResourceId) {
|
|
1424
|
+
const memory = await agent.getMemory({ requestContext: serverRequestContext });
|
|
1425
|
+
if (memory) {
|
|
1426
|
+
const thread = await memory.getThreadById({ threadId: effectiveThreadId });
|
|
1427
|
+
await validateThreadOwnership(thread, effectiveResourceId);
|
|
1428
|
+
}
|
|
1429
|
+
}
|
|
1430
|
+
if (typeof agent[methodName] !== "function") throw new HTTPException(501, { message: `agent ${methodName} is not supported by this Mastra core version` });
|
|
1431
|
+
if (runId) {
|
|
1432
|
+
const result = await invoke(agent, {
|
|
1433
|
+
runId,
|
|
1434
|
+
...effectiveResourceId ? { resourceId: effectiveResourceId } : {},
|
|
1435
|
+
...effectiveThreadId ? { threadId: effectiveThreadId } : {},
|
|
1436
|
+
...ifActive ? { ifActive } : {}
|
|
1437
|
+
});
|
|
1438
|
+
const settled = await result.accepted;
|
|
1439
|
+
const settledRunId = settled && "runId" in settled ? settled.runId : runId;
|
|
1440
|
+
return result.signal === void 0 ? {
|
|
1441
|
+
accepted: true,
|
|
1442
|
+
runId: settledRunId
|
|
1443
|
+
} : {
|
|
1444
|
+
accepted: true,
|
|
1445
|
+
runId: settledRunId,
|
|
1446
|
+
signal: result.signal
|
|
1447
|
+
};
|
|
1448
|
+
}
|
|
1449
|
+
if (!effectiveResourceId || !effectiveThreadId) throw new HTTPException(400, { message: "resourceId and threadId are required when runId is not provided" });
|
|
1450
|
+
const result = await invoke(agent, {
|
|
1451
|
+
resourceId: effectiveResourceId,
|
|
1452
|
+
threadId: effectiveThreadId,
|
|
1453
|
+
...ifActive ? { ifActive } : {},
|
|
1454
|
+
...ifIdleWithContext
|
|
1455
|
+
});
|
|
1456
|
+
const settled = await result.accepted;
|
|
1457
|
+
const settledRunId = settled && "runId" in settled ? settled.runId : result.signal?.id;
|
|
1458
|
+
return result.signal === void 0 ? {
|
|
1459
|
+
accepted: true,
|
|
1460
|
+
runId: settledRunId
|
|
1461
|
+
} : {
|
|
1462
|
+
accepted: true,
|
|
1463
|
+
runId: settledRunId,
|
|
1464
|
+
signal: result.signal
|
|
1465
|
+
};
|
|
1466
|
+
}
|
|
1467
|
+
const SEND_AGENT_MESSAGE_ROUTE = createRoute({
|
|
1468
|
+
method: "POST",
|
|
1469
|
+
path: "/agents/:agentId/send-message",
|
|
1470
|
+
responseType: "json",
|
|
1471
|
+
pathParamSchema: agentIdPathParams,
|
|
1472
|
+
bodySchema: sendAgentMessageBodySchema,
|
|
1473
|
+
responseSchema: sendAgentMessageResponseSchema,
|
|
1474
|
+
summary: "Send agent message",
|
|
1475
|
+
description: "Sends a user message to an active agent run or starts a memory thread run when the thread is idle",
|
|
1476
|
+
tags: ["Agents", "Streaming"],
|
|
1477
|
+
requiresAuth: true,
|
|
1478
|
+
requiresPermission: "agents:execute",
|
|
1479
|
+
handler: async (params) => {
|
|
1480
|
+
try {
|
|
1481
|
+
return await handleAgentMessageRoute({
|
|
1482
|
+
...params,
|
|
1483
|
+
methodName: "sendMessage",
|
|
1484
|
+
invoke: (agent, target) => agent.sendMessage(params.message, target)
|
|
1485
|
+
});
|
|
1486
|
+
} catch (error) {
|
|
1487
|
+
return handleSignalRoutingError(error, "error sending agent message");
|
|
1488
|
+
}
|
|
1489
|
+
}
|
|
1490
|
+
});
|
|
1491
|
+
const QUEUE_AGENT_MESSAGE_ROUTE = createRoute({
|
|
1492
|
+
method: "POST",
|
|
1493
|
+
path: "/agents/:agentId/queue-message",
|
|
1494
|
+
responseType: "json",
|
|
1495
|
+
pathParamSchema: agentIdPathParams,
|
|
1496
|
+
bodySchema: queueAgentMessageBodySchema,
|
|
1497
|
+
responseSchema: sendAgentMessageResponseSchema,
|
|
1498
|
+
summary: "Queue agent message",
|
|
1499
|
+
description: "Queues a user message to run after the active thread run completes, or starts a memory thread run when idle",
|
|
1500
|
+
tags: ["Agents", "Streaming"],
|
|
1501
|
+
requiresAuth: true,
|
|
1502
|
+
requiresPermission: "agents:execute",
|
|
1503
|
+
handler: async (params) => {
|
|
1504
|
+
try {
|
|
1505
|
+
return await handleAgentMessageRoute({
|
|
1506
|
+
...params,
|
|
1507
|
+
methodName: "queueMessage",
|
|
1508
|
+
invoke: (agent, target) => agent.queueMessage(params.message, target)
|
|
1509
|
+
});
|
|
1510
|
+
} catch (error) {
|
|
1511
|
+
return handleSignalRoutingError(error, "error queueing agent message");
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1514
|
+
});
|
|
1515
|
+
const QUEUE_AGENT_SIGNAL_ROUTE = createRoute({
|
|
1516
|
+
method: "POST",
|
|
1517
|
+
path: "/agents/:agentId/queue-signal",
|
|
1518
|
+
responseType: "json",
|
|
1519
|
+
pathParamSchema: agentIdPathParams,
|
|
1520
|
+
bodySchema: queueAgentSignalBodySchema,
|
|
1521
|
+
responseSchema: sendAgentSignalResponseSchema,
|
|
1522
|
+
summary: "Queue agent signal",
|
|
1523
|
+
description: "Queues a typed signal to run after the active thread run completes, or starts a memory thread run when idle",
|
|
1524
|
+
tags: ["Agents", "Streaming"],
|
|
1525
|
+
requiresAuth: true,
|
|
1526
|
+
requiresPermission: "agents:execute",
|
|
1527
|
+
handler: async (params) => {
|
|
1528
|
+
try {
|
|
1529
|
+
return await handleAgentMessageRoute({
|
|
1530
|
+
...params,
|
|
1531
|
+
methodName: "queueSignal",
|
|
1532
|
+
invoke: (agent, target) => agent.queueSignal(params.signal, target)
|
|
1533
|
+
});
|
|
1534
|
+
} catch (error) {
|
|
1535
|
+
return handleSignalRoutingError(error, "error queueing agent signal");
|
|
1536
|
+
}
|
|
1537
|
+
}
|
|
1538
|
+
});
|
|
1539
|
+
const ABORT_AGENT_THREAD_ROUTE = createRoute({
|
|
1540
|
+
method: "POST",
|
|
1541
|
+
path: "/agents/:agentId/threads/abort",
|
|
1542
|
+
responseType: "json",
|
|
1543
|
+
pathParamSchema: agentIdPathParams,
|
|
1544
|
+
bodySchema: abortAgentThreadBodySchema,
|
|
1545
|
+
responseSchema: abortAgentThreadResponseSchema,
|
|
1546
|
+
summary: "Abort active agent thread run",
|
|
1547
|
+
description: "Aborts the currently active stream run for a memory thread without changing thread subscriptions",
|
|
1548
|
+
tags: ["Agents", "Streaming"],
|
|
1549
|
+
requiresAuth: true,
|
|
1550
|
+
requiresPermission: "agents:execute",
|
|
1551
|
+
handler: async ({ mastra, agentId, resourceId, threadId, clearPendingSignals, expectedRunId, requestContext: serverRequestContext }) => {
|
|
1552
|
+
try {
|
|
1553
|
+
const agent = await getAgentFromSystem({
|
|
1554
|
+
mastra,
|
|
1555
|
+
agentId,
|
|
1556
|
+
requestContext: serverRequestContext
|
|
1557
|
+
});
|
|
1558
|
+
if (typeof agent.abortThreadStream !== "function") throw new HTTPException(501, { message: "agent thread aborts are not supported by this Mastra core version" });
|
|
1559
|
+
if (clearPendingSignals && agent.__supportsThreadSignalCancellation !== true) throw new HTTPException(501, { message: "clear-on-abort requires a newer @mastra/core version. Upgrade @mastra/core alongside @mastra/server." });
|
|
1560
|
+
const effectiveResourceId = getEffectiveResourceId(serverRequestContext, resourceId);
|
|
1561
|
+
const effectiveThreadId = getEffectiveThreadId(serverRequestContext, threadId);
|
|
1562
|
+
if (!effectiveThreadId) throw new HTTPException(400, { message: "threadId is required" });
|
|
1563
|
+
const thread = await (await agent.getMemory({ requestContext: serverRequestContext }))?.getThreadById({ threadId: effectiveThreadId });
|
|
1564
|
+
await enforceThreadAccess({
|
|
1565
|
+
mastra,
|
|
1566
|
+
requestContext: serverRequestContext,
|
|
1567
|
+
threadId: effectiveThreadId,
|
|
1568
|
+
thread,
|
|
1569
|
+
effectiveResourceId,
|
|
1570
|
+
permission: MastraFGAPermissions.MEMORY_WRITE
|
|
1571
|
+
});
|
|
1572
|
+
return { aborted: await agent.abortThreadStream({
|
|
1573
|
+
resourceId: effectiveResourceId,
|
|
1574
|
+
threadId: effectiveThreadId,
|
|
1575
|
+
...clearPendingSignals === void 0 ? {} : { clearPendingSignals },
|
|
1576
|
+
expectedRunId
|
|
1577
|
+
}) };
|
|
1578
|
+
} catch (error) {
|
|
1579
|
+
return handleError(error, "error aborting agent thread");
|
|
1580
|
+
}
|
|
1581
|
+
}
|
|
1582
|
+
});
|
|
1583
|
+
const CANCEL_AGENT_PENDING_SIGNALS_ROUTE = createRoute({
|
|
1584
|
+
method: "POST",
|
|
1585
|
+
path: "/agents/:agentId/threads/signals/cancel",
|
|
1586
|
+
responseType: "json",
|
|
1587
|
+
pathParamSchema: agentIdPathParams,
|
|
1588
|
+
bodySchema: cancelPendingAgentSignalsBodySchema,
|
|
1589
|
+
responseSchema: cancelPendingAgentSignalsResponseSchema,
|
|
1590
|
+
summary: "Cancel pending thread signals",
|
|
1591
|
+
description: "Cancels selected pending thread signals and propagates requested IDs through PubSub",
|
|
1592
|
+
tags: ["Agents", "Streaming"],
|
|
1593
|
+
requiresAuth: true,
|
|
1594
|
+
requiresPermission: "agents:execute",
|
|
1595
|
+
handler: async ({ mastra, agentId, resourceId, threadId, signalIds, requestContext }) => {
|
|
1596
|
+
try {
|
|
1597
|
+
const agent = await getAgentFromSystem({
|
|
1598
|
+
mastra,
|
|
1599
|
+
agentId,
|
|
1600
|
+
requestContext
|
|
1601
|
+
});
|
|
1602
|
+
if (typeof agent.cancelQueuedMessages !== "function" || agent.__supportsThreadSignalCancellation !== true) throw new HTTPException(501, { message: "thread-wide cancellation requires a newer @mastra/core version. Upgrade @mastra/core alongside @mastra/server." });
|
|
1603
|
+
const effectiveResourceId = getEffectiveResourceId(requestContext, resourceId);
|
|
1604
|
+
const effectiveThreadId = getEffectiveThreadId(requestContext, threadId);
|
|
1605
|
+
if (!effectiveThreadId) throw new HTTPException(400, { message: "threadId is required" });
|
|
1606
|
+
const thread = await (await agent.getMemory({ requestContext }))?.getThreadById({ threadId: effectiveThreadId });
|
|
1607
|
+
await enforceThreadAccess({
|
|
1608
|
+
mastra,
|
|
1609
|
+
requestContext,
|
|
1610
|
+
threadId: effectiveThreadId,
|
|
1611
|
+
thread,
|
|
1612
|
+
effectiveResourceId,
|
|
1613
|
+
permission: MastraFGAPermissions.MEMORY_WRITE
|
|
1614
|
+
});
|
|
1615
|
+
return agent.cancelQueuedMessages({
|
|
1616
|
+
resourceId: effectiveResourceId,
|
|
1617
|
+
threadId: effectiveThreadId,
|
|
1618
|
+
signalIds
|
|
1619
|
+
});
|
|
1620
|
+
} catch (error) {
|
|
1621
|
+
return handleError(error, "error cancelling pending thread signals");
|
|
1622
|
+
}
|
|
1623
|
+
}
|
|
1624
|
+
});
|
|
1625
|
+
const SUBSCRIBE_AGENT_THREAD_ROUTE = createRoute({
|
|
1626
|
+
method: "POST",
|
|
1627
|
+
path: "/agents/:agentId/threads/subscribe",
|
|
1628
|
+
responseType: "stream",
|
|
1629
|
+
streamFormat: "sse",
|
|
1630
|
+
sseFlushOnConnect: true,
|
|
1631
|
+
pathParamSchema: agentIdPathParams,
|
|
1632
|
+
bodySchema: subscribeAgentThreadBodySchema,
|
|
1633
|
+
responseSchema: streamResponseSchema,
|
|
1634
|
+
summary: "Subscribe to agent thread runs",
|
|
1635
|
+
description: "Subscribes to future and active stream runs for a memory thread",
|
|
1636
|
+
tags: ["Agents", "Streaming"],
|
|
1637
|
+
requiresAuth: true,
|
|
1638
|
+
requiresPermission: "agents:execute",
|
|
1639
|
+
handler: async ({ mastra, agentId, resourceId, threadId, withInitialHistory, abortSignal, requestContext: serverRequestContext }) => {
|
|
1640
|
+
try {
|
|
1641
|
+
const agent = await getAgentFromSystem({
|
|
1642
|
+
mastra,
|
|
1643
|
+
agentId,
|
|
1644
|
+
requestContext: serverRequestContext
|
|
1645
|
+
});
|
|
1646
|
+
if (typeof agent.subscribeToThread !== "function") throw new HTTPException(501, { message: "agent thread subscriptions are not supported by this Mastra core version" });
|
|
1647
|
+
const effectiveResourceId = getEffectiveResourceId(serverRequestContext, resourceId);
|
|
1648
|
+
const effectiveThreadId = getEffectiveThreadId(serverRequestContext, threadId);
|
|
1649
|
+
if (!effectiveThreadId) throw new HTTPException(400, { message: "threadId is required" });
|
|
1650
|
+
if (withInitialHistory) {
|
|
1651
|
+
const memory = await agent.getMemory({ requestContext: serverRequestContext });
|
|
1652
|
+
if (memory) {
|
|
1653
|
+
const thread = await memory.getThreadById({ threadId: effectiveThreadId });
|
|
1654
|
+
await enforceThreadAccess({
|
|
1655
|
+
mastra,
|
|
1656
|
+
requestContext: serverRequestContext,
|
|
1657
|
+
threadId: effectiveThreadId,
|
|
1658
|
+
thread,
|
|
1659
|
+
effectiveResourceId
|
|
1660
|
+
});
|
|
1661
|
+
}
|
|
1662
|
+
} else if (effectiveResourceId) {
|
|
1663
|
+
const memory = await agent.getMemory({ requestContext: serverRequestContext });
|
|
1664
|
+
if (memory) {
|
|
1665
|
+
const thread = await memory.getThreadById({ threadId: effectiveThreadId });
|
|
1666
|
+
await validateThreadOwnership(thread, effectiveResourceId);
|
|
1667
|
+
}
|
|
1668
|
+
}
|
|
1669
|
+
const subscription = await agent.subscribeToThread({
|
|
1670
|
+
resourceId: effectiveResourceId,
|
|
1671
|
+
threadId: effectiveThreadId,
|
|
1672
|
+
...withInitialHistory ? {
|
|
1673
|
+
withInitialHistory,
|
|
1674
|
+
requestContext: serverRequestContext
|
|
1675
|
+
} : {}
|
|
1676
|
+
});
|
|
1677
|
+
let cleanedUp = false;
|
|
1678
|
+
let heartbeat;
|
|
1679
|
+
const clearHeartbeat = () => {
|
|
1680
|
+
if (heartbeat) {
|
|
1681
|
+
clearTimeout(heartbeat);
|
|
1682
|
+
heartbeat = void 0;
|
|
1683
|
+
}
|
|
1684
|
+
};
|
|
1685
|
+
const cleanup = (closeController) => {
|
|
1686
|
+
if (cleanedUp) return;
|
|
1687
|
+
cleanedUp = true;
|
|
1688
|
+
clearHeartbeat();
|
|
1689
|
+
subscription.unsubscribe();
|
|
1690
|
+
if (closeController) try {
|
|
1691
|
+
closeController.close();
|
|
1692
|
+
} catch {}
|
|
1693
|
+
};
|
|
1694
|
+
return new ReadableStream({
|
|
1695
|
+
async start(controller) {
|
|
1696
|
+
const scheduleHeartbeat = () => {
|
|
1697
|
+
if (cleanedUp) return;
|
|
1698
|
+
clearHeartbeat();
|
|
1699
|
+
heartbeat = setTimeout(() => {
|
|
1700
|
+
heartbeat = void 0;
|
|
1701
|
+
if (cleanedUp) return;
|
|
1702
|
+
try {
|
|
1703
|
+
controller.enqueue(": heartbeat\n\n");
|
|
1704
|
+
} catch {
|
|
1705
|
+
cleanup();
|
|
1706
|
+
return;
|
|
1707
|
+
}
|
|
1708
|
+
scheduleHeartbeat();
|
|
1709
|
+
}, 25e3);
|
|
1710
|
+
};
|
|
1711
|
+
const abortCleanup = () => cleanup(controller);
|
|
1712
|
+
abortSignal?.addEventListener("abort", abortCleanup, { once: true });
|
|
1713
|
+
scheduleHeartbeat();
|
|
1714
|
+
try {
|
|
1715
|
+
for await (const part of subscription.stream) {
|
|
1716
|
+
controller.enqueue(part);
|
|
1717
|
+
scheduleHeartbeat();
|
|
1718
|
+
}
|
|
1719
|
+
cleanup(controller);
|
|
1720
|
+
} catch (error) {
|
|
1721
|
+
cleanup();
|
|
1722
|
+
controller.error(error);
|
|
1723
|
+
} finally {
|
|
1724
|
+
clearHeartbeat();
|
|
1725
|
+
abortSignal?.removeEventListener("abort", abortCleanup);
|
|
1726
|
+
}
|
|
1727
|
+
},
|
|
1728
|
+
cancel() {
|
|
1729
|
+
cleanup();
|
|
1730
|
+
}
|
|
1731
|
+
});
|
|
1732
|
+
} catch (error) {
|
|
1733
|
+
return handleError(error, "error subscribing to agent thread");
|
|
1734
|
+
}
|
|
1735
|
+
}
|
|
1736
|
+
});
|
|
1737
|
+
const STREAM_UNTIL_IDLE_GENERATE_ROUTE = createRoute({
|
|
1738
|
+
method: "POST",
|
|
1739
|
+
path: "/agents/:agentId/stream-until-idle",
|
|
1740
|
+
responseType: "stream",
|
|
1741
|
+
streamFormat: "sse",
|
|
1742
|
+
pathParamSchema: agentIdPathParams,
|
|
1743
|
+
bodySchema: streamUntilIdleBodySchema,
|
|
1744
|
+
responseSchema: streamResponseSchema,
|
|
1745
|
+
summary: "Stream agent response until idle",
|
|
1746
|
+
description: "Executes an agent with the provided messages and streams the response in real-time, also listens for background task completions and streams them in real-time",
|
|
1747
|
+
tags: ["Agents"],
|
|
1748
|
+
requiresAuth: true,
|
|
1749
|
+
requiresPermission: MastraFGAPermissions.AGENTS_EXECUTE,
|
|
1750
|
+
handler: async ({ mastra, agentId, abortSignal, requestContext: serverRequestContext, ...params }) => {
|
|
1751
|
+
try {
|
|
1752
|
+
sanitizeBody(params, [
|
|
1753
|
+
"tools",
|
|
1754
|
+
"actor",
|
|
1755
|
+
"scopes"
|
|
1756
|
+
]);
|
|
1757
|
+
stripClientCredentialHeaders(params);
|
|
1758
|
+
const { messages, memory: memoryOption, requestContext: bodyRequestContext, ...rest } = params;
|
|
1759
|
+
validateBody({ messages });
|
|
1760
|
+
const agent = await getAgentFromSystem({
|
|
1761
|
+
mastra,
|
|
1762
|
+
agentId,
|
|
1763
|
+
versionOptions: extractVersionOptions(serverRequestContext, bodyRequestContext),
|
|
1764
|
+
requestContext: serverRequestContext
|
|
1765
|
+
});
|
|
1766
|
+
mergeBodyRequestContext(serverRequestContext, bodyRequestContext);
|
|
1767
|
+
let authorizedMemoryOption = memoryOption;
|
|
1768
|
+
if (memoryOption) {
|
|
1769
|
+
const clientThreadId = typeof memoryOption.thread === "string" ? memoryOption.thread : memoryOption.thread?.id;
|
|
1770
|
+
const effectiveResourceId = getEffectiveResourceId(serverRequestContext, memoryOption.resource);
|
|
1771
|
+
requireEffectiveResourceId(effectiveResourceId);
|
|
1772
|
+
const effectiveThreadId = getEffectiveThreadId(serverRequestContext, clientThreadId);
|
|
1773
|
+
if (effectiveThreadId && effectiveResourceId) {
|
|
1774
|
+
const memoryInstance = await agent.getMemory({ requestContext: serverRequestContext });
|
|
1775
|
+
if (memoryInstance) {
|
|
1776
|
+
const thread = await memoryInstance.getThreadById({ threadId: effectiveThreadId });
|
|
1777
|
+
await validateThreadOwnership(thread, effectiveResourceId);
|
|
1778
|
+
}
|
|
1779
|
+
}
|
|
1780
|
+
authorizedMemoryOption = {
|
|
1781
|
+
...memoryOption,
|
|
1782
|
+
resource: effectiveResourceId ?? memoryOption.resource,
|
|
1783
|
+
thread: applyEffectiveThreadId(memoryOption.thread, effectiveThreadId)
|
|
1784
|
+
};
|
|
1785
|
+
}
|
|
1786
|
+
const { structuredOutput, ...restOptions } = rest;
|
|
1787
|
+
const options = {
|
|
1788
|
+
...restOptions,
|
|
1789
|
+
context: restOptions.context,
|
|
1790
|
+
requestContext: serverRequestContext,
|
|
1791
|
+
memory: authorizedMemoryOption,
|
|
1792
|
+
abortSignal
|
|
1793
|
+
};
|
|
1794
|
+
return (structuredOutput ? await agent.streamUntilIdle(messages, {
|
|
1795
|
+
...options,
|
|
1796
|
+
structuredOutput
|
|
1797
|
+
}) : await agent.streamUntilIdle(messages, options)).fullStream;
|
|
1798
|
+
} catch (error) {
|
|
1799
|
+
return handleError(error, "error streaming agent response");
|
|
1800
|
+
}
|
|
1801
|
+
}
|
|
1802
|
+
});
|
|
1803
|
+
const STREAM_GENERATE_VNEXT_DEPRECATED_ROUTE = createRoute({
|
|
1804
|
+
method: "POST",
|
|
1805
|
+
path: "/agents/:agentId/stream/vnext",
|
|
1806
|
+
responseType: "stream",
|
|
1807
|
+
pathParamSchema: agentIdPathParams,
|
|
1808
|
+
bodySchema: agentExecutionBodySchema,
|
|
1809
|
+
responseSchema: streamResponseSchema,
|
|
1810
|
+
summary: "Stream a response from an agent",
|
|
1811
|
+
description: "[DEPRECATED] This endpoint is deprecated. Please use /stream instead.",
|
|
1812
|
+
tags: ["Agents"],
|
|
1813
|
+
requiresAuth: true,
|
|
1814
|
+
deprecated: true,
|
|
1815
|
+
handler: STREAM_GENERATE_ROUTE.handler
|
|
1816
|
+
});
|
|
1817
|
+
const OBSERVE_AGENT_STREAM_ROUTE = createRoute({
|
|
1818
|
+
method: "POST",
|
|
1819
|
+
path: "/agents/:agentId/observe",
|
|
1820
|
+
responseType: "stream",
|
|
1821
|
+
streamFormat: "sse",
|
|
1822
|
+
pathParamSchema: agentIdPathParams,
|
|
1823
|
+
bodySchema: observeAgentBodySchema,
|
|
1824
|
+
responseSchema: observeAgentResponseSchema,
|
|
1825
|
+
summary: "Observe agent stream",
|
|
1826
|
+
description: "Reconnect to an existing agent stream to receive missed events. Supports position-based resume with offset for efficient reconnection.",
|
|
1827
|
+
tags: ["Agents", "Streaming"],
|
|
1828
|
+
requiresAuth: true,
|
|
1829
|
+
handler: async ({ mastra, agentId, runId, offset, abortSignal }) => {
|
|
1830
|
+
try {
|
|
1831
|
+
const agent = await getAgentFromSystem({
|
|
1832
|
+
mastra,
|
|
1833
|
+
agentId
|
|
1834
|
+
});
|
|
1835
|
+
const durableAgent = isDurableAgentLike(agent) ? agent : void 0;
|
|
1836
|
+
const pubsub = durableAgent?.pubsub ?? mastra.pubsub;
|
|
1837
|
+
const topic = AGENT_STREAM_TOPIC(runId);
|
|
1838
|
+
const subscribe = (onEvent, onComplete) => {
|
|
1839
|
+
if (typeof durableAgent?.__subscribeToRunStream === "function") return durableAgent.__subscribeToRunStream(runId, {
|
|
1840
|
+
offset,
|
|
1841
|
+
onComplete
|
|
1842
|
+
}, onEvent);
|
|
1843
|
+
return (offset !== void 0 ? pubsub.subscribeFromOffset(topic, offset, onEvent) : pubsub.subscribeWithReplay(topic, onEvent)).then(() => () => pubsub.unsubscribe(topic, onEvent));
|
|
1844
|
+
};
|
|
1845
|
+
let closed = false;
|
|
1846
|
+
let unsubscribe;
|
|
1847
|
+
let idleTimer = null;
|
|
1848
|
+
let onAbort;
|
|
1849
|
+
const IDLE_TIMEOUT_MS = 3e5;
|
|
1850
|
+
function releaseSubscription(unsubscribeFromRun) {
|
|
1851
|
+
Promise.resolve().then(unsubscribeFromRun).catch((error) => console.error(`[ObserveAgentStream] Failed to unsubscribe from ${topic}:`, error));
|
|
1852
|
+
}
|
|
1853
|
+
function stop() {
|
|
1854
|
+
closed = true;
|
|
1855
|
+
if (idleTimer) {
|
|
1856
|
+
clearTimeout(idleTimer);
|
|
1857
|
+
idleTimer = null;
|
|
1858
|
+
}
|
|
1859
|
+
if (onAbort) {
|
|
1860
|
+
abortSignal?.removeEventListener("abort", onAbort);
|
|
1861
|
+
onAbort = void 0;
|
|
1862
|
+
}
|
|
1863
|
+
if (unsubscribe) {
|
|
1864
|
+
const unsubscribeFromRun = unsubscribe;
|
|
1865
|
+
unsubscribe = void 0;
|
|
1866
|
+
releaseSubscription(unsubscribeFromRun);
|
|
1867
|
+
}
|
|
1868
|
+
}
|
|
1869
|
+
function cleanup(controller) {
|
|
1870
|
+
if (closed) return;
|
|
1871
|
+
stop();
|
|
1872
|
+
controller.close();
|
|
1873
|
+
}
|
|
1874
|
+
function resetIdleTimer(controller) {
|
|
1875
|
+
if (closed) return;
|
|
1876
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
1877
|
+
idleTimer = setTimeout(() => cleanup(controller), IDLE_TIMEOUT_MS);
|
|
1878
|
+
}
|
|
1879
|
+
return new ReadableStream({
|
|
1880
|
+
start(controller) {
|
|
1881
|
+
if (abortSignal) {
|
|
1882
|
+
if (abortSignal.aborted) {
|
|
1883
|
+
cleanup(controller);
|
|
1884
|
+
return;
|
|
1885
|
+
}
|
|
1886
|
+
onAbort = () => cleanup(controller);
|
|
1887
|
+
abortSignal.addEventListener("abort", onAbort, { once: true });
|
|
1888
|
+
}
|
|
1889
|
+
resetIdleTimer(controller);
|
|
1890
|
+
Promise.resolve().then(() => {
|
|
1891
|
+
if (closed) return;
|
|
1892
|
+
return subscribe((event) => {
|
|
1893
|
+
if (closed) return;
|
|
1894
|
+
const type = event.type === "chunk" ? event.data?.type : event.type;
|
|
1895
|
+
controller.enqueue(event);
|
|
1896
|
+
if (type === "finish" || type === "error" || type === "abort") cleanup(controller);
|
|
1897
|
+
else resetIdleTimer(controller);
|
|
1898
|
+
}, () => cleanup(controller));
|
|
1899
|
+
}).then((unsubscribeFromRun) => {
|
|
1900
|
+
if (!unsubscribeFromRun) return;
|
|
1901
|
+
if (closed) releaseSubscription(unsubscribeFromRun);
|
|
1902
|
+
else unsubscribe = unsubscribeFromRun;
|
|
1903
|
+
}, (error) => {
|
|
1904
|
+
if (closed) return;
|
|
1905
|
+
console.error(`[ObserveAgentStream] Failed to subscribe to ${topic}:`, error);
|
|
1906
|
+
stop();
|
|
1907
|
+
controller.error(error);
|
|
1908
|
+
});
|
|
1909
|
+
},
|
|
1910
|
+
cancel() {
|
|
1911
|
+
stop();
|
|
1912
|
+
}
|
|
1913
|
+
});
|
|
1914
|
+
} catch (error) {
|
|
1915
|
+
return handleError(error, "error observing agent stream");
|
|
1916
|
+
}
|
|
1917
|
+
}
|
|
1918
|
+
});
|
|
1919
|
+
const APPROVE_TOOL_CALL_ROUTE = createRoute({
|
|
1920
|
+
method: "POST",
|
|
1921
|
+
path: "/agents/:agentId/approve-tool-call",
|
|
1922
|
+
responseType: "stream",
|
|
1923
|
+
streamFormat: "sse",
|
|
1924
|
+
pathParamSchema: agentIdPathParams,
|
|
1925
|
+
bodySchema: approveToolCallBodySchema,
|
|
1926
|
+
responseSchema: toolCallResponseSchema,
|
|
1927
|
+
summary: "Approve tool call",
|
|
1928
|
+
description: "Approves a pending tool call and continues agent execution",
|
|
1929
|
+
tags: ["Agents", "Tools"],
|
|
1930
|
+
requiresAuth: true,
|
|
1931
|
+
handler: async ({ mastra, agentId, abortSignal, requestContext, ...params }) => {
|
|
1932
|
+
try {
|
|
1933
|
+
const agent = await getAgentFromSystem({
|
|
1934
|
+
mastra,
|
|
1935
|
+
agentId,
|
|
1936
|
+
versionOptions: extractVersionOptions(requestContext)
|
|
1937
|
+
});
|
|
1938
|
+
if (!params.runId) throw new HTTPException(400, { message: "Run id is required" });
|
|
1939
|
+
if (!params.toolCallId) throw new HTTPException(400, { message: "Tool call id is required" });
|
|
1940
|
+
sanitizeBody(params, [
|
|
1941
|
+
"tools",
|
|
1942
|
+
"actor",
|
|
1943
|
+
"scopes"
|
|
1944
|
+
]);
|
|
1945
|
+
stripClientCredentialHeaders(params);
|
|
1946
|
+
await validateDurableToolCallAccess({
|
|
1947
|
+
mastra,
|
|
1948
|
+
agent,
|
|
1949
|
+
runId: params.runId,
|
|
1950
|
+
toolCallId: params.toolCallId,
|
|
1951
|
+
requestContext,
|
|
1952
|
+
abortSignal
|
|
1953
|
+
});
|
|
1954
|
+
return (await agent.approveToolCall({
|
|
1955
|
+
...params,
|
|
1956
|
+
requestContext,
|
|
1957
|
+
abortSignal
|
|
1958
|
+
})).fullStream;
|
|
1959
|
+
} catch (error) {
|
|
1960
|
+
return handleError(error, "error approving tool call");
|
|
1961
|
+
}
|
|
1962
|
+
}
|
|
1963
|
+
});
|
|
1964
|
+
async function validateSubscriptionToolCallThreadAccess({ agent, requestContext, resourceId, threadId }) {
|
|
1965
|
+
const effectiveResourceId = getEffectiveResourceId(requestContext, resourceId);
|
|
1966
|
+
const effectiveThreadId = getEffectiveThreadId(requestContext, threadId);
|
|
1967
|
+
if (!effectiveThreadId) throw new HTTPException(400, { message: "threadId is required" });
|
|
1968
|
+
if (effectiveResourceId) {
|
|
1969
|
+
const memory = await agent.getMemory({ requestContext });
|
|
1970
|
+
if (memory) {
|
|
1971
|
+
const thread = await memory.getThreadById({ threadId: effectiveThreadId });
|
|
1972
|
+
await validateThreadOwnership(thread, effectiveResourceId);
|
|
1973
|
+
}
|
|
1974
|
+
}
|
|
1975
|
+
return {
|
|
1976
|
+
effectiveResourceId: effectiveResourceId ?? "",
|
|
1977
|
+
effectiveThreadId
|
|
1978
|
+
};
|
|
1979
|
+
}
|
|
1980
|
+
const SEND_TOOL_APPROVAL_ROUTE = createRoute({
|
|
1981
|
+
method: "POST",
|
|
1982
|
+
path: "/agents/:agentId/send-tool-approval",
|
|
1983
|
+
responseType: "json",
|
|
1984
|
+
pathParamSchema: agentIdPathParams,
|
|
1985
|
+
bodySchema: sendToolApprovalBodySchema,
|
|
1986
|
+
responseSchema: sendToolApprovalResponseSchema,
|
|
1987
|
+
summary: "Send tool approval",
|
|
1988
|
+
description: "Approves or declines a pending tool call and publishes resumed chunks to thread subscribers",
|
|
1989
|
+
tags: ["Agents", "Tools"],
|
|
1990
|
+
requiresAuth: true,
|
|
1991
|
+
requiresPermission: "agents:execute",
|
|
1992
|
+
handler: async ({ mastra, agentId, abortSignal, requestContext: serverRequestContext, ...params }) => {
|
|
1993
|
+
try {
|
|
1994
|
+
const bodyRequestContext = params.requestContext;
|
|
1995
|
+
const agent = await getAgentFromSystem({
|
|
1996
|
+
mastra,
|
|
1997
|
+
agentId,
|
|
1998
|
+
versionOptions: extractVersionOptions(serverRequestContext, bodyRequestContext),
|
|
1999
|
+
requestContext: serverRequestContext
|
|
2000
|
+
});
|
|
2001
|
+
if (!params.toolCallId) throw new HTTPException(400, { message: "Tool call id is required" });
|
|
2002
|
+
mergeBodyRequestContext(serverRequestContext, bodyRequestContext);
|
|
2003
|
+
sanitizeBody(params, [
|
|
2004
|
+
"tools",
|
|
2005
|
+
"actor",
|
|
2006
|
+
"scopes"
|
|
2007
|
+
]);
|
|
2008
|
+
stripClientCredentialHeaders(params);
|
|
2009
|
+
const normalizedStreamOptions = normalizePublicExecutionOptions(params.streamOptions, serverRequestContext);
|
|
2010
|
+
const { effectiveResourceId, effectiveThreadId } = await validateSubscriptionToolCallThreadAccess({
|
|
2011
|
+
agent,
|
|
2012
|
+
requestContext: serverRequestContext,
|
|
2013
|
+
resourceId: params.resourceId,
|
|
2014
|
+
threadId: params.threadId
|
|
2015
|
+
});
|
|
2016
|
+
return await agent.sendToolApproval({
|
|
2017
|
+
...params,
|
|
2018
|
+
...normalizedStreamOptions ? { streamOptions: normalizedStreamOptions } : {},
|
|
2019
|
+
resourceId: effectiveResourceId,
|
|
2020
|
+
threadId: effectiveThreadId,
|
|
2021
|
+
requestContext: serverRequestContext,
|
|
2022
|
+
abortSignal
|
|
2023
|
+
});
|
|
2024
|
+
} catch (error) {
|
|
2025
|
+
return handleError(error, "error sending tool approval");
|
|
2026
|
+
}
|
|
2027
|
+
}
|
|
2028
|
+
});
|
|
2029
|
+
const LIST_SUSPENDED_RUNS_ROUTE = createRoute({
|
|
2030
|
+
method: "GET",
|
|
2031
|
+
path: "/agents/:agentId/suspended-runs",
|
|
2032
|
+
responseType: "json",
|
|
2033
|
+
pathParamSchema: agentIdPathParams,
|
|
2034
|
+
queryParamSchema: listSuspendedRunsQuerySchema,
|
|
2035
|
+
responseSchema: listSuspendedRunsResponseSchema,
|
|
2036
|
+
summary: "List suspended runs",
|
|
2037
|
+
description: "Lists suspended agent runs from storage — runs waiting on a tool-call approval or on a tool that suspended. Works after a server restart and across instances.",
|
|
2038
|
+
tags: ["Agents", "Tools"],
|
|
2039
|
+
requiresAuth: true,
|
|
2040
|
+
handler: async ({ mastra, agentId, requestContext, ...query }) => {
|
|
2041
|
+
try {
|
|
2042
|
+
const agent = await getAgentFromSystem({
|
|
2043
|
+
mastra,
|
|
2044
|
+
agentId,
|
|
2045
|
+
versionOptions: extractVersionOptions(requestContext)
|
|
2046
|
+
});
|
|
2047
|
+
const effectiveResourceId = getEffectiveResourceId(requestContext, query.resourceId);
|
|
2048
|
+
const effectiveThreadId = getEffectiveThreadId(requestContext, query.threadId);
|
|
2049
|
+
if (effectiveThreadId) {
|
|
2050
|
+
const memory = await agent.getMemory({ requestContext });
|
|
2051
|
+
if (!memory) throw new HTTPException(403, { message: "Access denied: agent has no memory configured to validate thread ownership" });
|
|
2052
|
+
const thread = await memory.getThreadById({ threadId: effectiveThreadId });
|
|
2053
|
+
if (!thread) throw new HTTPException(403, { message: "Access denied: thread not found" });
|
|
2054
|
+
await enforceThreadAccess({
|
|
2055
|
+
mastra,
|
|
2056
|
+
requestContext,
|
|
2057
|
+
threadId: effectiveThreadId,
|
|
2058
|
+
thread,
|
|
2059
|
+
effectiveResourceId
|
|
2060
|
+
});
|
|
2061
|
+
}
|
|
2062
|
+
return await agent.listSuspendedRuns({
|
|
2063
|
+
threadId: effectiveThreadId,
|
|
2064
|
+
resourceId: effectiveResourceId,
|
|
2065
|
+
fromDate: query.fromDate,
|
|
2066
|
+
toDate: query.toDate,
|
|
2067
|
+
perPage: query.perPage,
|
|
2068
|
+
page: query.page
|
|
2069
|
+
});
|
|
2070
|
+
} catch (error) {
|
|
2071
|
+
return handleError(error, "error listing suspended runs");
|
|
2072
|
+
}
|
|
2073
|
+
}
|
|
2074
|
+
});
|
|
2075
|
+
const DECLINE_TOOL_CALL_ROUTE = createRoute({
|
|
2076
|
+
method: "POST",
|
|
2077
|
+
path: "/agents/:agentId/decline-tool-call",
|
|
2078
|
+
responseType: "stream",
|
|
2079
|
+
streamFormat: "sse",
|
|
2080
|
+
pathParamSchema: agentIdPathParams,
|
|
2081
|
+
bodySchema: declineToolCallBodySchema,
|
|
2082
|
+
responseSchema: toolCallResponseSchema,
|
|
2083
|
+
summary: "Decline tool call",
|
|
2084
|
+
description: "Declines a pending tool call and continues agent execution without executing the tool",
|
|
2085
|
+
tags: ["Agents", "Tools"],
|
|
2086
|
+
requiresAuth: true,
|
|
2087
|
+
handler: async ({ mastra, agentId, abortSignal, requestContext, ...params }) => {
|
|
2088
|
+
try {
|
|
2089
|
+
const agent = await getAgentFromSystem({
|
|
2090
|
+
mastra,
|
|
2091
|
+
agentId,
|
|
2092
|
+
versionOptions: extractVersionOptions(requestContext)
|
|
2093
|
+
});
|
|
2094
|
+
if (!params.runId) throw new HTTPException(400, { message: "Run id is required" });
|
|
2095
|
+
if (!params.toolCallId) throw new HTTPException(400, { message: "Tool call id is required" });
|
|
2096
|
+
sanitizeBody(params, [
|
|
2097
|
+
"tools",
|
|
2098
|
+
"actor",
|
|
2099
|
+
"scopes"
|
|
2100
|
+
]);
|
|
2101
|
+
stripClientCredentialHeaders(params);
|
|
2102
|
+
await validateDurableToolCallAccess({
|
|
2103
|
+
mastra,
|
|
2104
|
+
agent,
|
|
2105
|
+
runId: params.runId,
|
|
2106
|
+
toolCallId: params.toolCallId,
|
|
2107
|
+
requestContext,
|
|
2108
|
+
abortSignal
|
|
2109
|
+
});
|
|
2110
|
+
return (await agent.declineToolCall({
|
|
2111
|
+
...params,
|
|
2112
|
+
requestContext,
|
|
2113
|
+
abortSignal
|
|
2114
|
+
})).fullStream;
|
|
2115
|
+
} catch (error) {
|
|
2116
|
+
return handleError(error, "error declining tool call");
|
|
2117
|
+
}
|
|
2118
|
+
}
|
|
2119
|
+
});
|
|
2120
|
+
const RESUME_STREAM_ROUTE = createRoute({
|
|
2121
|
+
method: "POST",
|
|
2122
|
+
path: "/agents/:agentId/resume-stream",
|
|
2123
|
+
responseType: "stream",
|
|
2124
|
+
streamFormat: "sse",
|
|
2125
|
+
pathParamSchema: agentIdPathParams,
|
|
2126
|
+
bodySchema: resumeStreamBodySchema,
|
|
2127
|
+
responseSchema: streamResponseSchema,
|
|
2128
|
+
summary: "Resume agent stream",
|
|
2129
|
+
description: "Resumes a suspended agent stream with custom resume data",
|
|
2130
|
+
tags: ["Agents"],
|
|
2131
|
+
requiresAuth: true,
|
|
2132
|
+
requiresPermission: MastraFGAPermissions.AGENTS_EXECUTE,
|
|
2133
|
+
handler: async ({ mastra, agentId, abortSignal, requestContext: serverRequestContext, ...params }) => {
|
|
2134
|
+
try {
|
|
2135
|
+
if (!params.runId) throw new HTTPException(400, { message: "Run id is required" });
|
|
2136
|
+
sanitizeBody(params, [
|
|
2137
|
+
"tools",
|
|
2138
|
+
"actor",
|
|
2139
|
+
"scopes"
|
|
2140
|
+
]);
|
|
2141
|
+
stripClientCredentialHeaders(params);
|
|
2142
|
+
const { resumeData, runId, toolCallId, memory: memoryOption, requestContext: bodyRequestContext, versions, ...rest } = params;
|
|
2143
|
+
const versionOptions = extractVersionOptions(serverRequestContext, bodyRequestContext);
|
|
2144
|
+
const agent = await getAgentFromSystem({
|
|
2145
|
+
mastra,
|
|
2146
|
+
agentId,
|
|
2147
|
+
versionOptions
|
|
2148
|
+
});
|
|
2149
|
+
mergeBodyRequestContext(serverRequestContext, bodyRequestContext);
|
|
2150
|
+
stashVersionOverrides(serverRequestContext, versions);
|
|
2151
|
+
ensureDefaultVersionStatus(serverRequestContext, versionOptions);
|
|
2152
|
+
let authorizedMemoryOption = memoryOption;
|
|
2153
|
+
const clientThreadId = typeof memoryOption?.thread === "string" ? memoryOption.thread : memoryOption?.thread?.id;
|
|
2154
|
+
const effectiveResourceId = getEffectiveResourceId(serverRequestContext, memoryOption?.resource);
|
|
2155
|
+
if (memoryOption) requireEffectiveResourceId(effectiveResourceId);
|
|
2156
|
+
const effectiveThreadId = getEffectiveThreadId(serverRequestContext, clientThreadId);
|
|
2157
|
+
if (effectiveThreadId) {
|
|
2158
|
+
const memoryInstance = await agent.getMemory({ requestContext: serverRequestContext });
|
|
2159
|
+
if (memoryInstance) {
|
|
2160
|
+
const thread = await memoryInstance.getThreadById({ threadId: effectiveThreadId });
|
|
2161
|
+
if (thread) await enforceThreadAccess({
|
|
2162
|
+
mastra,
|
|
2163
|
+
requestContext: serverRequestContext,
|
|
2164
|
+
threadId: effectiveThreadId,
|
|
2165
|
+
thread,
|
|
2166
|
+
effectiveResourceId,
|
|
2167
|
+
permission: MastraFGAPermissions.MEMORY_WRITE
|
|
2168
|
+
});
|
|
2169
|
+
}
|
|
2170
|
+
}
|
|
2171
|
+
if (memoryOption || effectiveResourceId || effectiveThreadId) authorizedMemoryOption = {
|
|
2172
|
+
...memoryOption,
|
|
2173
|
+
...effectiveResourceId ? { resource: effectiveResourceId } : {},
|
|
2174
|
+
...effectiveThreadId ? { thread: applyEffectiveThreadId(memoryOption?.thread, effectiveThreadId) } : {}
|
|
2175
|
+
};
|
|
2176
|
+
await validateDurableToolCallAccess({
|
|
2177
|
+
mastra,
|
|
2178
|
+
agent,
|
|
2179
|
+
runId,
|
|
2180
|
+
toolCallId,
|
|
2181
|
+
requestContext: serverRequestContext,
|
|
2182
|
+
threadId: effectiveThreadId,
|
|
2183
|
+
abortSignal
|
|
2184
|
+
});
|
|
2185
|
+
const workflowRun = await (await mastra.getStorage()?.getStore("workflows"))?.getWorkflowRunById({
|
|
2186
|
+
workflowName: "agentic-loop",
|
|
2187
|
+
runId
|
|
2188
|
+
});
|
|
2189
|
+
await validateRunOwnership(workflowRun, getEffectiveResourceId(serverRequestContext, void 0), mastra);
|
|
2190
|
+
const { structuredOutput, untilIdle, ...restOptions } = rest;
|
|
2191
|
+
const options = {
|
|
2192
|
+
runId,
|
|
2193
|
+
toolCallId,
|
|
2194
|
+
...restOptions,
|
|
2195
|
+
requestContext: serverRequestContext,
|
|
2196
|
+
memory: authorizedMemoryOption,
|
|
2197
|
+
abortSignal
|
|
2198
|
+
};
|
|
2199
|
+
if (untilIdle) options.untilIdle = untilIdle;
|
|
2200
|
+
return (structuredOutput ? await agent.resumeStream(resumeData, {
|
|
2201
|
+
...options,
|
|
2202
|
+
structuredOutput
|
|
2203
|
+
}) : await agent.resumeStream(resumeData, options)).fullStream;
|
|
2204
|
+
} catch (error) {
|
|
2205
|
+
return handleError(error, "error resuming agent stream");
|
|
2206
|
+
}
|
|
2207
|
+
}
|
|
2208
|
+
});
|
|
2209
|
+
const RECOVER_ROUTE = createRoute({
|
|
2210
|
+
method: "POST",
|
|
2211
|
+
path: "/agents/:agentId/recover",
|
|
2212
|
+
responseType: "stream",
|
|
2213
|
+
streamFormat: "sse",
|
|
2214
|
+
pathParamSchema: agentIdPathParams,
|
|
2215
|
+
bodySchema: recoverBodySchema,
|
|
2216
|
+
responseSchema: streamResponseSchema,
|
|
2217
|
+
summary: "Recover an orphaned durable agent run",
|
|
2218
|
+
description: "Re-drives an orphaned RUNNING durable-agent run after a process restart. Only supported on durable agents (createDurableAgent). Returns a stream that replays past chunks and continues the loop to completion.",
|
|
2219
|
+
tags: ["Agents"],
|
|
2220
|
+
requiresAuth: true,
|
|
2221
|
+
requiresPermission: MastraFGAPermissions.AGENTS_EXECUTE,
|
|
2222
|
+
handler: async ({ mastra, agentId, abortSignal, requestContext: serverRequestContext, ...params }) => {
|
|
2223
|
+
try {
|
|
2224
|
+
if (!params.runId) throw new HTTPException(400, { message: "Run id is required" });
|
|
2225
|
+
const { runId, versions } = params;
|
|
2226
|
+
const bodyRequestContext = params.requestContext;
|
|
2227
|
+
const versionOptions = extractVersionOptions(serverRequestContext, bodyRequestContext);
|
|
2228
|
+
mergeBodyRequestContext(serverRequestContext, bodyRequestContext);
|
|
2229
|
+
stashVersionOverrides(serverRequestContext, versions);
|
|
2230
|
+
ensureDefaultVersionStatus(serverRequestContext, versionOptions);
|
|
2231
|
+
const agent = await getAgentFromSystem({
|
|
2232
|
+
mastra,
|
|
2233
|
+
agentId,
|
|
2234
|
+
versionOptions
|
|
2235
|
+
});
|
|
2236
|
+
if (!isDurableAgentLike(agent)) throw new HTTPException(400, { message: "Agent does not support recover. Only durable agents (createDurableAgent) can recover runs." });
|
|
2237
|
+
const workflowRun = await (await mastra.getStorage()?.getStore("workflows"))?.getWorkflowRunById({
|
|
2238
|
+
workflowName: getDurableLoopWorkflowName(agent),
|
|
2239
|
+
runId
|
|
2240
|
+
});
|
|
2241
|
+
await validateRunOwnership(workflowRun, getEffectiveResourceId(serverRequestContext, void 0), mastra);
|
|
2242
|
+
return (await agent.recover(runId, { abortSignal })).fullStream;
|
|
2243
|
+
} catch (error) {
|
|
2244
|
+
return handleError(error, "error recovering agent run");
|
|
2245
|
+
}
|
|
2246
|
+
}
|
|
2247
|
+
});
|
|
2248
|
+
const RESUME_STREAM_UNTIL_IDLE_ROUTE = createRoute({
|
|
2249
|
+
method: "POST",
|
|
2250
|
+
path: "/agents/:agentId/resume-stream-until-idle",
|
|
2251
|
+
responseType: "stream",
|
|
2252
|
+
streamFormat: "sse",
|
|
2253
|
+
pathParamSchema: agentIdPathParams,
|
|
2254
|
+
bodySchema: resumeStreamUntilIdleBodySchema,
|
|
2255
|
+
responseSchema: streamResponseSchema,
|
|
2256
|
+
summary: "Resume agent stream until idle",
|
|
2257
|
+
description: "Resumes a suspended agent stream until idle with custom resume data, also listens for background task completions and streams them in real-time",
|
|
2258
|
+
tags: ["Agents"],
|
|
2259
|
+
requiresAuth: true,
|
|
2260
|
+
requiresPermission: "agents:execute",
|
|
2261
|
+
handler: async ({ mastra, agentId, abortSignal, requestContext: serverRequestContext, ...params }) => {
|
|
2262
|
+
try {
|
|
2263
|
+
if (!params.runId) throw new HTTPException(400, { message: "Run id is required" });
|
|
2264
|
+
sanitizeBody(params, [
|
|
2265
|
+
"tools",
|
|
2266
|
+
"actor",
|
|
2267
|
+
"scopes"
|
|
2268
|
+
]);
|
|
2269
|
+
stripClientCredentialHeaders(params);
|
|
2270
|
+
const { resumeData, runId, toolCallId, memory: memoryOption, requestContext: bodyRequestContext, versions, ...rest } = params;
|
|
2271
|
+
const versionOptions = extractVersionOptions(serverRequestContext, bodyRequestContext);
|
|
2272
|
+
const agent = await getAgentFromSystem({
|
|
2273
|
+
mastra,
|
|
2274
|
+
agentId,
|
|
2275
|
+
versionOptions
|
|
2276
|
+
});
|
|
2277
|
+
mergeBodyRequestContext(serverRequestContext, bodyRequestContext);
|
|
2278
|
+
stashVersionOverrides(serverRequestContext, versions);
|
|
2279
|
+
ensureDefaultVersionStatus(serverRequestContext, versionOptions);
|
|
2280
|
+
let authorizedMemoryOption = memoryOption;
|
|
2281
|
+
const clientThreadId = typeof memoryOption?.thread === "string" ? memoryOption.thread : memoryOption?.thread?.id;
|
|
2282
|
+
const effectiveResourceId = getEffectiveResourceId(serverRequestContext, memoryOption?.resource);
|
|
2283
|
+
if (memoryOption) requireEffectiveResourceId(effectiveResourceId);
|
|
2284
|
+
const effectiveThreadId = getEffectiveThreadId(serverRequestContext, clientThreadId);
|
|
2285
|
+
if (effectiveThreadId) {
|
|
2286
|
+
const memoryInstance = await agent.getMemory({ requestContext: serverRequestContext });
|
|
2287
|
+
if (memoryInstance) {
|
|
2288
|
+
const thread = await memoryInstance.getThreadById({ threadId: effectiveThreadId });
|
|
2289
|
+
if (thread) await enforceThreadAccess({
|
|
2290
|
+
mastra,
|
|
2291
|
+
requestContext: serverRequestContext,
|
|
2292
|
+
threadId: effectiveThreadId,
|
|
2293
|
+
thread,
|
|
2294
|
+
effectiveResourceId,
|
|
2295
|
+
permission: MastraFGAPermissions.MEMORY_WRITE
|
|
2296
|
+
});
|
|
2297
|
+
}
|
|
2298
|
+
}
|
|
2299
|
+
if (memoryOption || effectiveResourceId || effectiveThreadId) authorizedMemoryOption = {
|
|
2300
|
+
...memoryOption,
|
|
2301
|
+
...effectiveResourceId ? { resource: effectiveResourceId } : {},
|
|
2302
|
+
...effectiveThreadId ? { thread: applyEffectiveThreadId(memoryOption?.thread, effectiveThreadId) } : {}
|
|
2303
|
+
};
|
|
2304
|
+
await validateDurableToolCallAccess({
|
|
2305
|
+
mastra,
|
|
2306
|
+
agent,
|
|
2307
|
+
runId,
|
|
2308
|
+
toolCallId,
|
|
2309
|
+
requestContext: serverRequestContext,
|
|
2310
|
+
threadId: effectiveThreadId,
|
|
2311
|
+
abortSignal
|
|
2312
|
+
});
|
|
2313
|
+
const workflowRun = await (await mastra.getStorage()?.getStore("workflows"))?.getWorkflowRunById({
|
|
2314
|
+
workflowName: "agentic-loop",
|
|
2315
|
+
runId
|
|
2316
|
+
});
|
|
2317
|
+
await validateRunOwnership(workflowRun, getEffectiveResourceId(serverRequestContext, void 0), mastra);
|
|
2318
|
+
const { structuredOutput, ...restOptions } = rest;
|
|
2319
|
+
const options = {
|
|
2320
|
+
runId,
|
|
2321
|
+
toolCallId,
|
|
2322
|
+
...restOptions,
|
|
2323
|
+
context: restOptions.context,
|
|
2324
|
+
requestContext: serverRequestContext,
|
|
2325
|
+
memory: authorizedMemoryOption,
|
|
2326
|
+
abortSignal
|
|
2327
|
+
};
|
|
2328
|
+
return (structuredOutput ? await agent.resumeStreamUntilIdle(resumeData, {
|
|
2329
|
+
...options,
|
|
2330
|
+
structuredOutput
|
|
2331
|
+
}) : await agent.resumeStreamUntilIdle(resumeData, options)).fullStream;
|
|
2332
|
+
} catch (error) {
|
|
2333
|
+
return handleError(error, "error resuming agent stream");
|
|
2334
|
+
}
|
|
2335
|
+
}
|
|
2336
|
+
});
|
|
2337
|
+
const APPROVE_TOOL_CALL_GENERATE_ROUTE = createRoute({
|
|
2338
|
+
method: "POST",
|
|
2339
|
+
path: "/agents/:agentId/approve-tool-call-generate",
|
|
2340
|
+
responseType: "json",
|
|
2341
|
+
pathParamSchema: agentIdPathParams,
|
|
2342
|
+
bodySchema: approveToolCallBodySchema,
|
|
2343
|
+
responseSchema: generateResponseSchema,
|
|
2344
|
+
summary: "Approve tool call (non-streaming)",
|
|
2345
|
+
description: "Approves a pending tool call and returns the complete response",
|
|
2346
|
+
tags: ["Agents", "Tools"],
|
|
2347
|
+
requiresAuth: true,
|
|
2348
|
+
handler: async ({ mastra, agentId, abortSignal, requestContext, ...params }) => {
|
|
2349
|
+
try {
|
|
2350
|
+
const agent = await getAgentFromSystem({
|
|
2351
|
+
mastra,
|
|
2352
|
+
agentId,
|
|
2353
|
+
versionOptions: extractVersionOptions(requestContext)
|
|
2354
|
+
});
|
|
2355
|
+
if (!params.runId) throw new HTTPException(400, { message: "Run id is required" });
|
|
2356
|
+
if (!params.toolCallId) throw new HTTPException(400, { message: "Tool call id is required" });
|
|
2357
|
+
sanitizeBody(params, [
|
|
2358
|
+
"tools",
|
|
2359
|
+
"actor",
|
|
2360
|
+
"scopes"
|
|
2361
|
+
]);
|
|
2362
|
+
stripClientCredentialHeaders(params);
|
|
2363
|
+
await validateDurableToolCallAccess({
|
|
2364
|
+
mastra,
|
|
2365
|
+
agent,
|
|
2366
|
+
runId: params.runId,
|
|
2367
|
+
toolCallId: params.toolCallId,
|
|
2368
|
+
requestContext,
|
|
2369
|
+
abortSignal
|
|
2370
|
+
});
|
|
2371
|
+
return await agent.approveToolCallGenerate({
|
|
2372
|
+
...params,
|
|
2373
|
+
requestContext,
|
|
2374
|
+
abortSignal
|
|
2375
|
+
});
|
|
2376
|
+
} catch (error) {
|
|
2377
|
+
return handleError(error, "error approving tool call");
|
|
2378
|
+
}
|
|
2379
|
+
}
|
|
2380
|
+
});
|
|
2381
|
+
const DECLINE_TOOL_CALL_GENERATE_ROUTE = createRoute({
|
|
2382
|
+
method: "POST",
|
|
2383
|
+
path: "/agents/:agentId/decline-tool-call-generate",
|
|
2384
|
+
responseType: "json",
|
|
2385
|
+
pathParamSchema: agentIdPathParams,
|
|
2386
|
+
bodySchema: declineToolCallBodySchema,
|
|
2387
|
+
responseSchema: generateResponseSchema,
|
|
2388
|
+
summary: "Decline tool call (non-streaming)",
|
|
2389
|
+
description: "Declines a pending tool call and returns the complete response",
|
|
2390
|
+
tags: ["Agents", "Tools"],
|
|
2391
|
+
requiresAuth: true,
|
|
2392
|
+
handler: async ({ mastra, agentId, abortSignal, requestContext, ...params }) => {
|
|
2393
|
+
try {
|
|
2394
|
+
const agent = await getAgentFromSystem({
|
|
2395
|
+
mastra,
|
|
2396
|
+
agentId,
|
|
2397
|
+
versionOptions: extractVersionOptions(requestContext)
|
|
2398
|
+
});
|
|
2399
|
+
if (!params.runId) throw new HTTPException(400, { message: "Run id is required" });
|
|
2400
|
+
if (!params.toolCallId) throw new HTTPException(400, { message: "Tool call id is required" });
|
|
2401
|
+
sanitizeBody(params, [
|
|
2402
|
+
"tools",
|
|
2403
|
+
"actor",
|
|
2404
|
+
"scopes"
|
|
2405
|
+
]);
|
|
2406
|
+
stripClientCredentialHeaders(params);
|
|
2407
|
+
await validateDurableToolCallAccess({
|
|
2408
|
+
mastra,
|
|
2409
|
+
agent,
|
|
2410
|
+
runId: params.runId,
|
|
2411
|
+
toolCallId: params.toolCallId,
|
|
2412
|
+
requestContext,
|
|
2413
|
+
abortSignal
|
|
2414
|
+
});
|
|
2415
|
+
return await agent.declineToolCallGenerate({
|
|
2416
|
+
...params,
|
|
2417
|
+
requestContext,
|
|
2418
|
+
abortSignal
|
|
2419
|
+
});
|
|
2420
|
+
} catch (error) {
|
|
2421
|
+
return handleError(error, "error declining tool call");
|
|
2422
|
+
}
|
|
2423
|
+
}
|
|
2424
|
+
});
|
|
2425
|
+
const STREAM_NETWORK_ROUTE = createRoute({
|
|
2426
|
+
method: "POST",
|
|
2427
|
+
path: "/agents/:agentId/network",
|
|
2428
|
+
responseType: "stream",
|
|
2429
|
+
streamFormat: "sse",
|
|
2430
|
+
pathParamSchema: agentIdPathParams,
|
|
2431
|
+
bodySchema: agentExecutionBodySchema,
|
|
2432
|
+
responseSchema: streamResponseSchema,
|
|
2433
|
+
summary: "Stream agent network",
|
|
2434
|
+
description: "Executes an agent network with multiple agents and streams the response",
|
|
2435
|
+
tags: ["Agents"],
|
|
2436
|
+
requiresAuth: true,
|
|
2437
|
+
handler: async ({ mastra, messages, agentId, requestContext, ...params }) => {
|
|
2438
|
+
try {
|
|
2439
|
+
const agent = await getAgentFromSystem({
|
|
2440
|
+
mastra,
|
|
2441
|
+
agentId,
|
|
2442
|
+
versionOptions: extractVersionOptions(requestContext)
|
|
2443
|
+
});
|
|
2444
|
+
sanitizeBody(params, [
|
|
2445
|
+
"tools",
|
|
2446
|
+
"actor",
|
|
2447
|
+
"scopes"
|
|
2448
|
+
]);
|
|
2449
|
+
stripClientCredentialHeaders(params);
|
|
2450
|
+
validateBody({ messages });
|
|
2451
|
+
let authorizedMemoryOption = params.memory;
|
|
2452
|
+
if (params.memory) {
|
|
2453
|
+
const effectiveResourceId = getEffectiveResourceId(requestContext, params.memory.resource);
|
|
2454
|
+
requireEffectiveResourceId(effectiveResourceId);
|
|
2455
|
+
authorizedMemoryOption = {
|
|
2456
|
+
...params.memory,
|
|
2457
|
+
resource: effectiveResourceId
|
|
2458
|
+
};
|
|
2459
|
+
}
|
|
2460
|
+
return await agent.network(messages, {
|
|
2461
|
+
...params,
|
|
2462
|
+
memory: authorizedMemoryOption
|
|
2463
|
+
});
|
|
2464
|
+
} catch (error) {
|
|
2465
|
+
return handleError(error, "error streaming agent loop response");
|
|
2466
|
+
}
|
|
2467
|
+
}
|
|
2468
|
+
});
|
|
2469
|
+
const APPROVE_NETWORK_TOOL_CALL_ROUTE = createRoute({
|
|
2470
|
+
method: "POST",
|
|
2471
|
+
path: "/agents/:agentId/approve-network-tool-call",
|
|
2472
|
+
responseType: "stream",
|
|
2473
|
+
streamFormat: "sse",
|
|
2474
|
+
pathParamSchema: agentIdPathParams,
|
|
2475
|
+
bodySchema: approveNetworkToolCallBodySchema,
|
|
2476
|
+
responseSchema: streamResponseSchema,
|
|
2477
|
+
summary: "Approve network tool call",
|
|
2478
|
+
description: "Approves a pending network tool call and continues network agent execution",
|
|
2479
|
+
tags: ["Agents", "Tools"],
|
|
2480
|
+
requiresAuth: true,
|
|
2481
|
+
handler: async ({ mastra, agentId, requestContext, ...params }) => {
|
|
2482
|
+
try {
|
|
2483
|
+
const agent = await getAgentFromSystem({
|
|
2484
|
+
mastra,
|
|
2485
|
+
agentId,
|
|
2486
|
+
versionOptions: extractVersionOptions(requestContext)
|
|
2487
|
+
});
|
|
2488
|
+
if (!params.runId) throw new HTTPException(400, { message: "Run id is required" });
|
|
2489
|
+
sanitizeBody(params, [
|
|
2490
|
+
"tools",
|
|
2491
|
+
"actor",
|
|
2492
|
+
"scopes"
|
|
2493
|
+
]);
|
|
2494
|
+
stripClientCredentialHeaders(params);
|
|
2495
|
+
return await agent.approveNetworkToolCall({ ...params });
|
|
2496
|
+
} catch (error) {
|
|
2497
|
+
return handleError(error, "error approving network tool call");
|
|
2498
|
+
}
|
|
2499
|
+
}
|
|
2500
|
+
});
|
|
2501
|
+
const DECLINE_NETWORK_TOOL_CALL_ROUTE = createRoute({
|
|
2502
|
+
method: "POST",
|
|
2503
|
+
path: "/agents/:agentId/decline-network-tool-call",
|
|
2504
|
+
responseType: "stream",
|
|
2505
|
+
streamFormat: "sse",
|
|
2506
|
+
pathParamSchema: agentIdPathParams,
|
|
2507
|
+
bodySchema: declineNetworkToolCallBodySchema,
|
|
2508
|
+
responseSchema: streamResponseSchema,
|
|
2509
|
+
summary: "Decline network tool call",
|
|
2510
|
+
description: "Declines a pending network tool call and continues network agent execution without executing the tool",
|
|
2511
|
+
tags: ["Agents", "Tools"],
|
|
2512
|
+
requiresAuth: true,
|
|
2513
|
+
handler: async ({ mastra, agentId, requestContext, ...params }) => {
|
|
2514
|
+
try {
|
|
2515
|
+
const agent = await getAgentFromSystem({
|
|
2516
|
+
mastra,
|
|
2517
|
+
agentId,
|
|
2518
|
+
versionOptions: extractVersionOptions(requestContext)
|
|
2519
|
+
});
|
|
2520
|
+
if (!params.runId) throw new HTTPException(400, { message: "Run id is required" });
|
|
2521
|
+
sanitizeBody(params, [
|
|
2522
|
+
"tools",
|
|
2523
|
+
"actor",
|
|
2524
|
+
"scopes"
|
|
2525
|
+
]);
|
|
2526
|
+
stripClientCredentialHeaders(params);
|
|
2527
|
+
return await agent.declineNetworkToolCall({ ...params });
|
|
2528
|
+
} catch (error) {
|
|
2529
|
+
return handleError(error, "error declining network tool call");
|
|
2530
|
+
}
|
|
2531
|
+
}
|
|
2532
|
+
});
|
|
2533
|
+
const UPDATE_AGENT_MODEL_ROUTE = createRoute({
|
|
2534
|
+
method: "POST",
|
|
2535
|
+
path: "/agents/:agentId/model",
|
|
2536
|
+
responseType: "json",
|
|
2537
|
+
pathParamSchema: agentIdPathParams,
|
|
2538
|
+
bodySchema: updateAgentModelBodySchema,
|
|
2539
|
+
responseSchema: modelManagementResponseSchema,
|
|
2540
|
+
summary: "Update agent model",
|
|
2541
|
+
description: "Updates the AI model used by the agent",
|
|
2542
|
+
tags: ["Agents", "Models"],
|
|
2543
|
+
requiresAuth: true,
|
|
2544
|
+
handler: async ({ mastra, agentId, modelId, provider }) => {
|
|
2545
|
+
try {
|
|
2546
|
+
const agent = await getAgentFromSystem({
|
|
2547
|
+
mastra,
|
|
2548
|
+
agentId
|
|
2549
|
+
});
|
|
2550
|
+
const newModel = `${provider}/${modelId}`;
|
|
2551
|
+
agent.__updateModel({ model: newModel });
|
|
2552
|
+
return { message: "Agent model updated" };
|
|
2553
|
+
} catch (error) {
|
|
2554
|
+
return handleError(error, "error updating agent model");
|
|
2555
|
+
}
|
|
2556
|
+
}
|
|
2557
|
+
});
|
|
2558
|
+
const RESET_AGENT_MODEL_ROUTE = createRoute({
|
|
2559
|
+
method: "POST",
|
|
2560
|
+
path: "/agents/:agentId/model/reset",
|
|
2561
|
+
responseType: "json",
|
|
2562
|
+
pathParamSchema: agentIdPathParams,
|
|
2563
|
+
responseSchema: modelManagementResponseSchema,
|
|
2564
|
+
summary: "Reset agent model",
|
|
2565
|
+
description: "Resets the agent model to its original configuration",
|
|
2566
|
+
tags: ["Agents", "Models"],
|
|
2567
|
+
requiresAuth: true,
|
|
2568
|
+
handler: async ({ mastra, agentId }) => {
|
|
2569
|
+
try {
|
|
2570
|
+
(await getAgentFromSystem({
|
|
2571
|
+
mastra,
|
|
2572
|
+
agentId
|
|
2573
|
+
})).__resetToOriginalModel();
|
|
2574
|
+
return { message: "Agent model reset to original" };
|
|
2575
|
+
} catch (error) {
|
|
2576
|
+
return handleError(error, "error resetting agent model");
|
|
2577
|
+
}
|
|
2578
|
+
}
|
|
2579
|
+
});
|
|
2580
|
+
const REORDER_AGENT_MODEL_LIST_ROUTE = createRoute({
|
|
2581
|
+
method: "POST",
|
|
2582
|
+
path: "/agents/:agentId/models/reorder",
|
|
2583
|
+
responseType: "json",
|
|
2584
|
+
pathParamSchema: agentIdPathParams,
|
|
2585
|
+
bodySchema: reorderAgentModelListBodySchema,
|
|
2586
|
+
responseSchema: modelManagementResponseSchema,
|
|
2587
|
+
summary: "Reorder agent model list",
|
|
2588
|
+
description: "Reorders the model list for agents with multiple model configurations",
|
|
2589
|
+
tags: ["Agents", "Models"],
|
|
2590
|
+
requiresAuth: true,
|
|
2591
|
+
handler: async ({ mastra, agentId, reorderedModelIds }) => {
|
|
2592
|
+
try {
|
|
2593
|
+
const agent = await getAgentFromSystem({
|
|
2594
|
+
mastra,
|
|
2595
|
+
agentId
|
|
2596
|
+
});
|
|
2597
|
+
if (typeof agent.model === "function") throw new HTTPException(409, { message: "Agent model list is dynamic (model is a function) and cannot be edited" });
|
|
2598
|
+
const modelList = await agent.getModelList();
|
|
2599
|
+
if (!modelList || modelList.length === 0) throw new HTTPException(400, { message: "Agent model list is not found or empty" });
|
|
2600
|
+
if (agent.reorderModels(reorderedModelIds) === false) throw new HTTPException(400, { message: "Agent model list could not be reordered" });
|
|
2601
|
+
return { message: "Model list reordered" };
|
|
2602
|
+
} catch (error) {
|
|
2603
|
+
return handleError(error, "error reordering model list");
|
|
2604
|
+
}
|
|
2605
|
+
}
|
|
2606
|
+
});
|
|
2607
|
+
const UPDATE_AGENT_MODEL_IN_MODEL_LIST_ROUTE = createRoute({
|
|
2608
|
+
method: "POST",
|
|
2609
|
+
path: "/agents/:agentId/models/:modelConfigId",
|
|
2610
|
+
responseType: "json",
|
|
2611
|
+
pathParamSchema: modelConfigIdPathParams,
|
|
2612
|
+
bodySchema: updateAgentModelInModelListBodySchema,
|
|
2613
|
+
responseSchema: modelManagementResponseSchema,
|
|
2614
|
+
summary: "Update model in model list",
|
|
2615
|
+
description: "Updates a specific model configuration in the agent model list",
|
|
2616
|
+
tags: ["Agents", "Models"],
|
|
2617
|
+
requiresAuth: true,
|
|
2618
|
+
handler: async ({ mastra, agentId, modelConfigId, model: bodyModel, maxRetries, enabled }) => {
|
|
2619
|
+
try {
|
|
2620
|
+
const agent = await getAgentFromSystem({
|
|
2621
|
+
mastra,
|
|
2622
|
+
agentId
|
|
2623
|
+
});
|
|
2624
|
+
if (typeof agent.model === "function") throw new HTTPException(409, { message: "Agent model list is dynamic (model is a function) and cannot be edited" });
|
|
2625
|
+
const modelList = await agent.getModelList();
|
|
2626
|
+
if (!modelList || modelList.length === 0) throw new HTTPException(400, { message: "Agent model list is not found or empty" });
|
|
2627
|
+
const modelConfig = modelList.find((config) => config.id === modelConfigId);
|
|
2628
|
+
if (!modelConfig) throw new HTTPException(404, { message: `Model config with id ${modelConfigId} not found` });
|
|
2629
|
+
const newModel = bodyModel?.modelId && bodyModel?.provider ? `${bodyModel.provider}/${bodyModel.modelId}` : modelConfig.model;
|
|
2630
|
+
const updated = {
|
|
2631
|
+
...modelConfig,
|
|
2632
|
+
model: newModel,
|
|
2633
|
+
...maxRetries !== void 0 ? { maxRetries } : {},
|
|
2634
|
+
...enabled !== void 0 ? { enabled } : {}
|
|
2635
|
+
};
|
|
2636
|
+
if (agent.updateModelInModelList(updated) === false) throw new HTTPException(404, { message: `Model config with id ${modelConfigId} not found` });
|
|
2637
|
+
return { message: "Model updated in model list" };
|
|
2638
|
+
} catch (error) {
|
|
2639
|
+
return handleError(error, "error updating model in model list");
|
|
2640
|
+
}
|
|
2641
|
+
}
|
|
2642
|
+
});
|
|
2643
|
+
const ENHANCE_SYSTEM_PROMPT_INSTRUCTIONS = `You are an expert system prompt engineer, specialized in analyzing and enhancing instructions to create clear, effective, and comprehensive system prompts. Your goal is to help users transform their basic instructions into well-structured system prompts that will guide AI behavior effectively.
|
|
2644
|
+
|
|
2645
|
+
Follow these steps to analyze and enhance the instructions:
|
|
2646
|
+
|
|
2647
|
+
1. ANALYSIS PHASE
|
|
2648
|
+
- Identify the core purpose and goals
|
|
2649
|
+
- Extract key constraints and requirements
|
|
2650
|
+
- Recognize domain-specific terminology and concepts
|
|
2651
|
+
- Note any implicit assumptions that should be made explicit
|
|
2652
|
+
|
|
2653
|
+
2. PROMPT STRUCTURE
|
|
2654
|
+
Create a system prompt with these components:
|
|
2655
|
+
a) ROLE DEFINITION
|
|
2656
|
+
- Clear statement of the AI's role and purpose
|
|
2657
|
+
- Key responsibilities and scope
|
|
2658
|
+
- Primary stakeholders and users
|
|
2659
|
+
b) CORE CAPABILITIES
|
|
2660
|
+
- Main functions and abilities
|
|
2661
|
+
- Specific domain knowledge required
|
|
2662
|
+
- Tools and resources available
|
|
2663
|
+
c) BEHAVIORAL GUIDELINES
|
|
2664
|
+
- Communication style and tone
|
|
2665
|
+
- Decision-making framework
|
|
2666
|
+
- Error handling approach
|
|
2667
|
+
- Ethical considerations
|
|
2668
|
+
d) CONSTRAINTS & BOUNDARIES
|
|
2669
|
+
- Explicit limitations
|
|
2670
|
+
- Out-of-scope activities
|
|
2671
|
+
- Security and privacy considerations
|
|
2672
|
+
e) SUCCESS CRITERIA
|
|
2673
|
+
- Quality standards
|
|
2674
|
+
- Expected outcomes
|
|
2675
|
+
- Performance metrics
|
|
2676
|
+
|
|
2677
|
+
3. QUALITY CHECKS
|
|
2678
|
+
Ensure the prompt is:
|
|
2679
|
+
- Clear and unambiguous
|
|
2680
|
+
- Comprehensive yet concise
|
|
2681
|
+
- Properly scoped
|
|
2682
|
+
- Technically accurate
|
|
2683
|
+
- Ethically sound
|
|
2684
|
+
|
|
2685
|
+
4. OUTPUT FORMAT
|
|
2686
|
+
Return your response as JSON with exactly these two fields:
|
|
2687
|
+
- explanation: A brief explanation of the changes you made and why
|
|
2688
|
+
- new_prompt: The complete enhanced system prompt as a single string
|
|
2689
|
+
|
|
2690
|
+
Remember: A good system prompt should be specific enough to guide behavior but flexible enough to handle edge cases. Focus on creating prompts that are clear, actionable, and aligned with the intended use case.`;
|
|
2691
|
+
async function findConnectedModel(agent) {
|
|
2692
|
+
const modelList = await agent.getModelList();
|
|
2693
|
+
if (modelList && modelList.length > 0) {
|
|
2694
|
+
for (const modelConfig of modelList) if (modelConfig.enabled !== false) {
|
|
2695
|
+
const model = modelConfig.model;
|
|
2696
|
+
if (isProviderConnected(model.provider)) return model;
|
|
2697
|
+
}
|
|
2698
|
+
return null;
|
|
2699
|
+
}
|
|
2700
|
+
const defaultModel = await agent.getModel();
|
|
2701
|
+
if (isProviderConnected(defaultModel.provider)) return defaultModel;
|
|
2702
|
+
return null;
|
|
2703
|
+
}
|
|
2704
|
+
const ENHANCE_INSTRUCTIONS_ROUTE = createRoute({
|
|
2705
|
+
method: "POST",
|
|
2706
|
+
path: "/agents/:agentId/instructions/enhance",
|
|
2707
|
+
responseType: "json",
|
|
2708
|
+
pathParamSchema: agentIdPathParams,
|
|
2709
|
+
bodySchema: enhanceInstructionsBodySchema,
|
|
2710
|
+
responseSchema: enhanceInstructionsResponseSchema,
|
|
2711
|
+
summary: "Enhance agent instructions",
|
|
2712
|
+
description: "Uses AI to enhance or modify agent instructions based on user feedback",
|
|
2713
|
+
tags: ["Agents"],
|
|
2714
|
+
requiresAuth: true,
|
|
2715
|
+
handler: async ({ mastra, agentId, instructions, comment }) => {
|
|
2716
|
+
try {
|
|
2717
|
+
const model = await findConnectedModel(await getAgentFromSystem({
|
|
2718
|
+
mastra,
|
|
2719
|
+
agentId
|
|
2720
|
+
}));
|
|
2721
|
+
if (!model) throw new HTTPException(400, { message: "No model with a configured API key found. Please set the required environment variable for your model provider." });
|
|
2722
|
+
return await (await new Agent({
|
|
2723
|
+
id: "system-prompt-enhancer",
|
|
2724
|
+
name: "system-prompt-enhancer",
|
|
2725
|
+
instructions: ENHANCE_SYSTEM_PROMPT_INSTRUCTIONS,
|
|
2726
|
+
model
|
|
2727
|
+
}).generate(`We need to improve the system prompt.
|
|
2728
|
+
Current: ${instructions}
|
|
2729
|
+
${comment ? `User feedback: ${comment}` : ""}`, { structuredOutput: { schema: enhanceInstructionsResponseSchema } })).object;
|
|
2730
|
+
} catch (error) {
|
|
2731
|
+
return handleError(error, "Error enhancing instructions");
|
|
2732
|
+
}
|
|
2733
|
+
}
|
|
2734
|
+
});
|
|
2735
|
+
const STREAM_VNEXT_DEPRECATED_ROUTE = createRoute({
|
|
2736
|
+
method: "POST",
|
|
2737
|
+
path: "/agents/:agentId/streamVNext",
|
|
2738
|
+
responseType: "stream",
|
|
2739
|
+
pathParamSchema: agentIdPathParams,
|
|
2740
|
+
bodySchema: agentExecutionBodySchema,
|
|
2741
|
+
responseSchema: streamResponseSchema,
|
|
2742
|
+
summary: "Stream a response from an agent",
|
|
2743
|
+
description: "[DEPRECATED] This endpoint is deprecated. Please use /stream instead.",
|
|
2744
|
+
tags: ["Agents"],
|
|
2745
|
+
requiresAuth: true,
|
|
2746
|
+
deprecated: true,
|
|
2747
|
+
handler: async () => {
|
|
2748
|
+
throw new HTTPException(410, { message: "This endpoint is deprecated. Please use /stream instead." });
|
|
2749
|
+
}
|
|
2750
|
+
});
|
|
2751
|
+
const STREAM_UI_MESSAGE_VNEXT_DEPRECATED_ROUTE = createRoute({
|
|
2752
|
+
method: "POST",
|
|
2753
|
+
path: "/agents/:agentId/stream/vnext/ui",
|
|
2754
|
+
responseType: "stream",
|
|
2755
|
+
pathParamSchema: agentIdPathParams,
|
|
2756
|
+
bodySchema: agentExecutionBodySchema,
|
|
2757
|
+
responseSchema: streamResponseSchema,
|
|
2758
|
+
summary: "Stream UI messages from an agent",
|
|
2759
|
+
description: "[DEPRECATED] This endpoint is deprecated. Please use the @mastra/ai-sdk package for uiMessage transformations",
|
|
2760
|
+
tags: ["Agents"],
|
|
2761
|
+
requiresAuth: true,
|
|
2762
|
+
deprecated: true,
|
|
2763
|
+
handler: async () => {
|
|
2764
|
+
try {
|
|
2765
|
+
throw new MastraError({
|
|
2766
|
+
category: ErrorCategory.USER,
|
|
2767
|
+
domain: ErrorDomain.MASTRA_SERVER,
|
|
2768
|
+
id: "DEPRECATED_ENDPOINT",
|
|
2769
|
+
text: "This endpoint is deprecated. Please use the @mastra/ai-sdk package to for uiMessage transformations"
|
|
2770
|
+
});
|
|
2771
|
+
} catch (error) {
|
|
2772
|
+
return handleError(error, "error streaming agent response");
|
|
2773
|
+
}
|
|
2774
|
+
}
|
|
2775
|
+
});
|
|
2776
|
+
const STREAM_UI_MESSAGE_DEPRECATED_ROUTE = createRoute({
|
|
2777
|
+
method: "POST",
|
|
2778
|
+
path: "/agents/:agentId/stream/ui",
|
|
2779
|
+
responseType: "stream",
|
|
2780
|
+
pathParamSchema: agentIdPathParams,
|
|
2781
|
+
bodySchema: agentExecutionBodySchema,
|
|
2782
|
+
responseSchema: streamResponseSchema,
|
|
2783
|
+
summary: "Stream UI messages from an agent",
|
|
2784
|
+
description: "[DEPRECATED] This endpoint is deprecated. Please use the @mastra/ai-sdk package for uiMessage transformations",
|
|
2785
|
+
tags: ["Agents"],
|
|
2786
|
+
requiresAuth: true,
|
|
2787
|
+
deprecated: true,
|
|
2788
|
+
handler: STREAM_UI_MESSAGE_VNEXT_DEPRECATED_ROUTE.handler
|
|
2789
|
+
});
|
|
2790
|
+
const GET_AGENT_SKILL_ROUTE = createRoute({
|
|
2791
|
+
method: "GET",
|
|
2792
|
+
path: "/agents/:agentId/skills/:skillName",
|
|
2793
|
+
responseType: "json",
|
|
2794
|
+
pathParamSchema: agentSkillPathParams,
|
|
2795
|
+
queryParamSchema: skillDisambiguationQuerySchema,
|
|
2796
|
+
responseSchema: getAgentSkillResponseSchema,
|
|
2797
|
+
summary: "Get agent skill",
|
|
2798
|
+
description: "Returns details for a specific skill available to the agent (inline or workspace)",
|
|
2799
|
+
tags: ["Agents", "Skills"],
|
|
2800
|
+
handler: async ({ mastra, agentId, skillName, path, requestContext }) => {
|
|
2801
|
+
try {
|
|
2802
|
+
const agent = agentId ? mastra.getAgentById(agentId) : null;
|
|
2803
|
+
if (!agent) throw new HTTPException(404, { message: "Agent not found" });
|
|
2804
|
+
const identifier = path ?? skillName;
|
|
2805
|
+
const skill = await agent.getSkill(identifier, { requestContext });
|
|
2806
|
+
if (!skill) throw new HTTPException(404, { message: `Skill "${identifier}" not found` });
|
|
2807
|
+
return {
|
|
2808
|
+
name: skill.name,
|
|
2809
|
+
description: skill.description,
|
|
2810
|
+
license: skill.license,
|
|
2811
|
+
compatibility: skill.compatibility,
|
|
2812
|
+
metadata: skill.metadata,
|
|
2813
|
+
path: skill.path,
|
|
2814
|
+
instructions: skill.instructions,
|
|
2815
|
+
source: skill.source,
|
|
2816
|
+
references: skill.references,
|
|
2817
|
+
scripts: skill.scripts,
|
|
2818
|
+
assets: skill.assets
|
|
2819
|
+
};
|
|
2820
|
+
} catch (error) {
|
|
2821
|
+
return handleError(error, "Error getting agent skill");
|
|
2822
|
+
}
|
|
2823
|
+
}
|
|
2824
|
+
});
|
|
2825
|
+
//#endregion
|
|
2826
|
+
export { STREAM_GENERATE_LEGACY_ROUTE as A, UPDATE_AGENT_MODEL_ROUTE as B, REORDER_AGENT_MODEL_LIST_ROUTE as C, SEND_AGENT_MESSAGE_ROUTE as D, RESUME_STREAM_UNTIL_IDLE_ROUTE as E, STREAM_UI_MESSAGE_VNEXT_DEPRECATED_ROUTE as F, getBrowserToolsFromAgent as G, buildProvidersList as H, STREAM_UNTIL_IDLE_GENERATE_ROUTE as I, getSerializedSkillsFromAgent as J, getSerializedAgentTools as K, STREAM_VNEXT_DEPRECATED_ROUTE as L, STREAM_GENERATE_VNEXT_DEPRECATED_ROUTE as M, STREAM_NETWORK_ROUTE as N, SEND_AGENT_SIGNAL_ROUTE as O, STREAM_UI_MESSAGE_DEPRECATED_ROUTE as P, SUBSCRIBE_AGENT_THREAD_ROUTE as R, RECOVER_ROUTE as S, RESUME_STREAM_ROUTE as T, extractVersionOptions as U, agents_exports as V, getAgentFromSystem as W, isProviderConnected as X, getWorkspaceToolsFromAgent as Y, LIST_AGENTS_ROUTE as _, CANCEL_AGENT_PENDING_SIGNALS_ROUTE as a, QUEUE_AGENT_MESSAGE_ROUTE as b, DECLINE_TOOL_CALL_GENERATE_ROUTE as c, GENERATE_AGENT_ROUTE as d, GENERATE_AGENT_VNEXT_ROUTE as f, GET_PROVIDERS_ROUTE as g, GET_AGENT_SKILL_ROUTE as h, APPROVE_TOOL_CALL_ROUTE as i, STREAM_GENERATE_ROUTE as j, SEND_TOOL_APPROVAL_ROUTE as k, DECLINE_TOOL_CALL_ROUTE as l, GET_AGENT_BY_ID_ROUTE as m, APPROVE_NETWORK_TOOL_CALL_ROUTE as n, CLONE_AGENT_ROUTE as o, GENERATE_LEGACY_ROUTE as p, getSerializedProcessors as q, APPROVE_TOOL_CALL_GENERATE_ROUTE as r, DECLINE_NETWORK_TOOL_CALL_ROUTE as s, ABORT_AGENT_THREAD_ROUTE as t, ENHANCE_INSTRUCTIONS_ROUTE as u, LIST_SUSPENDED_RUNS_ROUTE as v, RESET_AGENT_MODEL_ROUTE as w, QUEUE_AGENT_SIGNAL_ROUTE as x, OBSERVE_AGENT_STREAM_ROUTE as y, UPDATE_AGENT_MODEL_IN_MODEL_LIST_ROUTE as z };
|
|
2827
|
+
|
|
2828
|
+
//# sourceMappingURL=agents-DRQ3ScbX.js.map
|