@mastra/server 1.82.0 → 1.83.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_types/@internal_core@0.1.4/dist/storage/index.d.ts +24 -2
- package/dist/_types/@mastra_schema-compat@1.3.17/dist/_types/@internal_ai-v6@0.0.95/dist/index.d.ts +96 -15
- package/dist/{a2a-CoiG3TAj.js → a2a-DCpd3CTv.js} +4 -4
- package/dist/{a2a-CoiG3TAj.js.map → a2a-DCpd3CTv.js.map} +1 -1
- package/dist/{a2a-DvqRdny6.cjs → a2a-kz7NjjCg.cjs} +4 -4
- package/dist/{a2a-DvqRdny6.cjs.map → a2a-kz7NjjCg.cjs.map} +1 -1
- package/dist/{agent-builder-C_L1i2eE.js → agent-builder-CocfOSi8.js} +7 -7
- package/dist/{agent-builder-C_L1i2eE.js.map → agent-builder-CocfOSi8.js.map} +1 -1
- package/dist/{agent-builder-D0Up9Fw1.cjs → agent-builder-uDstZROq.cjs} +7 -7
- package/dist/{agent-builder-D0Up9Fw1.cjs.map → agent-builder-uDstZROq.cjs.map} +1 -1
- package/dist/{agents-CgcW6lHt.js → agents-BI8ez-FT.js} +7 -7
- package/dist/{agents-CgcW6lHt.js.map → agents-BI8ez-FT.js.map} +1 -1
- package/dist/{agents-DOHGWXDa.cjs → agents-DsfsDhIT.cjs} +7 -7
- package/dist/{agents-DOHGWXDa.cjs.map → agents-DsfsDhIT.cjs.map} +1 -1
- package/dist/{api-schema-manifest-Ci2qUYHc.js → api-schema-manifest-ChxbN16M.js} +3 -3
- package/dist/{api-schema-manifest-Ci2qUYHc.js.map → api-schema-manifest-ChxbN16M.js.map} +1 -1
- package/dist/{api-schema-manifest-DCHOlOuJ.cjs → api-schema-manifest-DtYTPvh9.cjs} +3 -3
- package/dist/{api-schema-manifest-DCHOlOuJ.cjs.map → api-schema-manifest-DtYTPvh9.cjs.map} +1 -1
- package/dist/{background-tasks-BHhn4YZA.js → background-tasks-BIuEr2of.js} +3 -3
- package/dist/{background-tasks-BHhn4YZA.js.map → background-tasks-BIuEr2of.js.map} +1 -1
- package/dist/{background-tasks-Ci2tlxJC.cjs → background-tasks-BXTIp0QV.cjs} +3 -3
- package/dist/{background-tasks-Ci2tlxJC.cjs.map → background-tasks-BXTIp0QV.cjs.map} +1 -1
- package/dist/{builder-registry-m_gHCe12.js → builder-registry-Dd7pbJ5A.js} +4 -4
- package/dist/{builder-registry-m_gHCe12.js.map → builder-registry-Dd7pbJ5A.js.map} +1 -1
- package/dist/{builder-registry-D1_hGKCJ.cjs → builder-registry-DrBUA6EZ.cjs} +4 -4
- package/dist/{builder-registry-D1_hGKCJ.cjs.map → builder-registry-DrBUA6EZ.cjs.map} +1 -1
- package/dist/{channels-hhQ3vD30.js → channels-B6hwVMbV.js} +4 -4
- package/dist/{channels-hhQ3vD30.js.map → channels-B6hwVMbV.js.map} +1 -1
- package/dist/{channels-Bfkp5vYI.cjs → channels-DbfSH5O2.cjs} +4 -4
- package/dist/{channels-Bfkp5vYI.cjs.map → channels-DbfSH5O2.cjs.map} +1 -1
- package/dist/{conversations-xS7yHuG1.js → conversations-BbZYXKIa.js} +5 -5
- package/dist/{conversations-xS7yHuG1.js.map → conversations-BbZYXKIa.js.map} +1 -1
- package/dist/{conversations-Ch_VuVwY.cjs → conversations-QuKJVEFe.cjs} +5 -5
- package/dist/{conversations-Ch_VuVwY.cjs.map → conversations-QuKJVEFe.cjs.map} +1 -1
- package/dist/{dist-BKNKucT9.cjs → dist-Ctfk9X6u.cjs} +208 -247
- package/dist/dist-Ctfk9X6u.cjs.map +1 -0
- package/dist/dist-DJjVMQiv.js +1 -0
- package/dist/{dist-CIYZuix4.js → dist-OKFDPspq.js} +208 -247
- package/dist/dist-OKFDPspq.js.map +1 -0
- package/dist/{dist-DgKeISkr.cjs → dist-ZYvqJK9p.cjs} +1 -1
- package/dist/docs/SKILL.md +3 -1
- package/dist/docs/assets/SOURCE_MAP.json +1 -1
- package/dist/docs/references/docs-knowledge-overview.md +106 -0
- package/dist/docs/references/docs-server-custom-adapters.md +4 -0
- package/dist/docs/references/docs-studio-knowledge.md +45 -24
- package/dist/docs/references/reference-server-invoke-route.md +86 -0
- package/dist/docs/references/reference-server-routes.md +63 -0
- package/dist/{dynamic-workflows-DDauBnDt.js → dynamic-workflows-CyaZLmHX.js} +2 -2
- package/dist/{dynamic-workflows-DDauBnDt.js.map → dynamic-workflows-CyaZLmHX.js.map} +1 -1
- package/dist/{dynamic-workflows-CpCkqM1g.cjs → dynamic-workflows-ZmzWJXxG.cjs} +2 -2
- package/dist/{dynamic-workflows-CpCkqM1g.cjs.map → dynamic-workflows-ZmzWJXxG.cjs.map} +1 -1
- package/dist/{editor-builder-Ceen28s8.js → editor-builder-CbfX5bvL.js} +4 -4
- package/dist/{editor-builder-Ceen28s8.js.map → editor-builder-CbfX5bvL.js.map} +1 -1
- package/dist/{editor-builder-CKfy5eZY.cjs → editor-builder-CjJlqR9a.cjs} +4 -4
- package/dist/{editor-builder-CKfy5eZY.cjs.map → editor-builder-CjJlqR9a.cjs.map} +1 -1
- package/dist/{helpers-DNq3LtLq.js → helpers-B29a1nM3.js} +51 -48
- package/dist/helpers-B29a1nM3.js.map +1 -0
- package/dist/{helpers-BKtUXhz2.cjs → helpers-CylvUIZm.cjs} +56 -47
- package/dist/helpers-CylvUIZm.cjs.map +1 -0
- package/dist/{knowledge-Ba74qr0v.js → knowledge-Cd2cCq-Y.js} +4 -4
- package/dist/{knowledge-Ba74qr0v.js.map → knowledge-Cd2cCq-Y.js.map} +1 -1
- package/dist/{knowledge-urR7FFG8.cjs → knowledge-Q_SCnD9m.cjs} +4 -4
- package/dist/{knowledge-urR7FFG8.cjs.map → knowledge-Q_SCnD9m.cjs.map} +1 -1
- package/dist/{logs-B57_NKDn.js → logs-C5L6gRGr.js} +4 -4
- package/dist/{logs-B57_NKDn.js.map → logs-C5L6gRGr.js.map} +1 -1
- package/dist/{logs-BJN3M88A.cjs → logs-DWIbFIw6.cjs} +4 -4
- package/dist/{logs-BJN3M88A.cjs.map → logs-DWIbFIw6.cjs.map} +1 -1
- package/dist/{mcp-B9BILfJP.cjs → mcp-CKvOVfHn.cjs} +3 -3
- package/dist/{mcp-B9BILfJP.cjs.map → mcp-CKvOVfHn.cjs.map} +1 -1
- package/dist/{mcp-BkmWZD6M.js → mcp-CntC59iU.js} +3 -3
- package/dist/{mcp-BkmWZD6M.js.map → mcp-CntC59iU.js.map} +1 -1
- package/dist/{memory-Dqod_AK9.cjs → memory-DIos0BE-.cjs} +57 -15
- package/dist/{memory-Dqod_AK9.cjs.map → memory-DIos0BE-.cjs.map} +1 -1
- package/dist/{memory-ipOCmg0C.js → memory-JzgWJevA.js} +57 -15
- package/dist/{memory-ipOCmg0C.js.map → memory-JzgWJevA.js.map} +1 -1
- package/dist/{observability-DBtyAJnb.js → observability-BCTkIhJT.js} +3 -3
- package/dist/{observability-DBtyAJnb.js.map → observability-BCTkIhJT.js.map} +1 -1
- package/dist/{observability-BtdW6mjq.cjs → observability-mnHHbnoc.cjs} +3 -3
- package/dist/{observability-BtdW6mjq.cjs.map → observability-mnHHbnoc.cjs.map} +1 -1
- package/dist/{observability-new-endpoints-jjCgXuTF.cjs → observability-new-endpoints-B6fo20v5.cjs} +129 -955
- package/dist/observability-new-endpoints-B6fo20v5.cjs.map +1 -0
- package/dist/{observability-new-endpoints-Di7m_-xc.js → observability-new-endpoints-DHn8uKyr.js} +51 -877
- package/dist/observability-new-endpoints-DHn8uKyr.js.map +1 -0
- package/dist/observability-signal-context-BYOFtbM_.cjs +1317 -0
- package/dist/observability-signal-context-BYOFtbM_.cjs.map +1 -0
- package/dist/observability-signal-context-CL5-rCWM.js +952 -0
- package/dist/observability-signal-context-CL5-rCWM.js.map +1 -0
- package/dist/{plans-nHOnlGzr.js → plans-9hdkc-t8.js} +4 -4
- package/dist/{plans-nHOnlGzr.js.map → plans-9hdkc-t8.js.map} +1 -1
- package/dist/{plans-Djcp3C0d.cjs → plans-DMs8SVBG.cjs} +4 -4
- package/dist/{plans-Djcp3C0d.cjs.map → plans-DMs8SVBG.cjs.map} +1 -1
- package/dist/{probe-image-size-DGTRKrgq.js → probe-image-size-Cxm5QtwO.js} +2 -2
- package/dist/{probe-image-size-DGTRKrgq.js.map → probe-image-size-Cxm5QtwO.js.map} +1 -1
- package/dist/{probe-image-size-BAwk1h6w.cjs → probe-image-size-bDuzMW0E.cjs} +2 -2
- package/dist/{probe-image-size-BAwk1h6w.cjs.map → probe-image-size-bDuzMW0E.cjs.map} +1 -1
- package/dist/{responses-CEet9y8G.js → responses-B5_syoSo.js} +5 -5
- package/dist/{responses-CEet9y8G.js.map → responses-B5_syoSo.js.map} +1 -1
- package/dist/{responses-BdOStKtX.cjs → responses-CNKJoC5a.cjs} +5 -5
- package/dist/{responses-BdOStKtX.cjs.map → responses-CNKJoC5a.cjs.map} +1 -1
- package/dist/{route-builder-BxPrwNog.js → route-builder-BKEzjw_M.js} +2 -2
- package/dist/{route-builder-BxPrwNog.js.map → route-builder-BKEzjw_M.js.map} +1 -1
- package/dist/{route-builder-CvARmqnA.cjs → route-builder-DHqDrSSy.cjs} +2 -2
- package/dist/{route-builder-CvARmqnA.cjs.map → route-builder-DHqDrSSy.cjs.map} +1 -1
- package/dist/{routes-DU_FlwJP.cjs → routes-BYQ38dFx.cjs} +32 -32
- package/dist/{routes-DU_FlwJP.cjs.map → routes-BYQ38dFx.cjs.map} +1 -1
- package/dist/{routes-5FpkkzND.js → routes-C0pgNcG-.js} +32 -32
- package/dist/{routes-5FpkkzND.js.map → routes-C0pgNcG-.js.map} +1 -1
- package/dist/{schedules-D8ShgpY3.cjs → schedules-CvWX2yKR.cjs} +3 -3
- package/dist/{schedules-D8ShgpY3.cjs.map → schedules-CvWX2yKR.cjs.map} +1 -1
- package/dist/{schedules-CGViSLZC.js → schedules-D9CKB18-.js} +3 -3
- package/dist/{schedules-CGViSLZC.js.map → schedules-D9CKB18-.js.map} +1 -1
- package/dist/{schema-Bf12g7KC-DBc4NSds.js → schema-Bf12g7KC-5EUrrnSf.js} +96 -96
- package/dist/{schema-Bf12g7KC-DBc4NSds.js.map → schema-Bf12g7KC-5EUrrnSf.js.map} +1 -1
- package/dist/{schema-Bf12g7KC-plP4Ir6h.cjs → schema-Bf12g7KC-C5XzpQxe.cjs} +96 -96
- package/dist/{schema-Bf12g7KC-plP4Ir6h.cjs.map → schema-Bf12g7KC-C5XzpQxe.cjs.map} +1 -1
- package/dist/{scores-BaDFGpmr.js → scores-B3mS6vqB.js} +4 -4
- package/dist/{scores-BaDFGpmr.js.map → scores-B3mS6vqB.js.map} +1 -1
- package/dist/{scores-Bw6Tuga5.cjs → scores-Dxa8dDfV.cjs} +4 -4
- package/dist/{scores-Bw6Tuga5.cjs.map → scores-Dxa8dDfV.cjs.map} +1 -1
- package/dist/server/auth/helpers.d.ts +20 -0
- package/dist/server/auth/helpers.d.ts.map +1 -1
- package/dist/server/auth/index.cjs +2 -1
- package/dist/server/auth/index.js +2 -2
- package/dist/server/handlers/a2a.cjs +1 -1
- package/dist/server/handlers/a2a.js +1 -1
- package/dist/server/handlers/agent-builder.cjs +1 -1
- package/dist/server/handlers/agent-builder.js +1 -1
- package/dist/server/handlers/agent-controller.cjs +4 -4
- package/dist/server/handlers/agent-controller.js +4 -4
- package/dist/server/handlers/agent-versions.cjs +4 -4
- package/dist/server/handlers/agent-versions.js +4 -4
- package/dist/server/handlers/agents.cjs +1 -1
- package/dist/server/handlers/agents.js +1 -1
- package/dist/server/handlers/auth.cjs +4 -4
- package/dist/server/handlers/auth.js +4 -4
- package/dist/server/handlers/authorship.cjs +1 -1
- package/dist/server/handlers/authorship.js +1 -1
- package/dist/server/handlers/background-tasks.cjs +1 -1
- package/dist/server/handlers/background-tasks.js +1 -1
- package/dist/server/handlers/builder-registry.cjs +1 -1
- package/dist/server/handlers/builder-registry.js +1 -1
- package/dist/server/handlers/channels.cjs +1 -1
- package/dist/server/handlers/channels.js +1 -1
- package/dist/server/handlers/conversations.cjs +1 -1
- package/dist/server/handlers/conversations.js +1 -1
- package/dist/server/handlers/datasets.cjs +3 -3
- package/dist/server/handlers/datasets.js +3 -3
- package/dist/server/handlers/dynamic-workflows.cjs +1 -1
- package/dist/server/handlers/dynamic-workflows.js +1 -1
- package/dist/server/handlers/editor-builder.cjs +1 -1
- package/dist/server/handlers/editor-builder.js +1 -1
- package/dist/server/handlers/favorites-enrichment.cjs +1 -1
- package/dist/server/handlers/favorites-enrichment.js +1 -1
- package/dist/server/handlers/gateway-memory-client.cjs +4 -1
- package/dist/server/handlers/gateway-memory-client.cjs.map +1 -1
- package/dist/server/handlers/gateway-memory-client.d.ts.map +1 -1
- package/dist/server/handlers/gateway-memory-client.js +4 -1
- package/dist/server/handlers/gateway-memory-client.js.map +1 -1
- package/dist/server/handlers/knowledge.cjs +1 -1
- package/dist/server/handlers/knowledge.js +1 -1
- package/dist/server/handlers/logs.cjs +1 -1
- package/dist/server/handlers/logs.js +1 -1
- package/dist/server/handlers/mcp-client-versions.cjs +3 -3
- package/dist/server/handlers/mcp-client-versions.js +3 -3
- package/dist/server/handlers/mcp.cjs +1 -1
- package/dist/server/handlers/mcp.js +1 -1
- package/dist/server/handlers/memory.cjs +1 -1
- package/dist/server/handlers/memory.d.ts.map +1 -1
- package/dist/server/handlers/memory.js +1 -1
- package/dist/server/handlers/observability-new-endpoints.cjs +1 -1
- package/dist/server/handlers/observability-new-endpoints.d.ts +84 -8
- package/dist/server/handlers/observability-new-endpoints.d.ts.map +1 -1
- package/dist/server/handlers/observability-new-endpoints.js +1 -1
- package/dist/server/handlers/observability-shared.cjs +1 -1
- package/dist/server/handlers/observability-shared.js +1 -1
- package/dist/server/handlers/observability-signal-context.cjs +4 -0
- package/dist/server/handlers/observability-signal-context.d.ts +42 -0
- package/dist/server/handlers/observability-signal-context.d.ts.map +1 -0
- package/dist/server/handlers/observability-signal-context.js +1 -0
- package/dist/server/handlers/observability.cjs +2 -2
- package/dist/server/handlers/observability.js +2 -2
- package/dist/server/handlers/plans.cjs +1 -1
- package/dist/server/handlers/plans.js +1 -1
- package/dist/server/handlers/processor-providers.cjs +2 -2
- package/dist/server/handlers/processor-providers.js +2 -2
- package/dist/server/handlers/processors.cjs +2 -2
- package/dist/server/handlers/processors.js +2 -2
- package/dist/server/handlers/prompt-block-versions.cjs +3 -3
- package/dist/server/handlers/prompt-block-versions.js +3 -3
- package/dist/server/handlers/responses.cjs +1 -1
- package/dist/server/handlers/responses.js +1 -1
- package/dist/server/handlers/responses.storage.cjs +1 -1
- package/dist/server/handlers/responses.storage.js +1 -1
- package/dist/server/handlers/schedules.cjs +1 -1
- package/dist/server/handlers/schedules.js +1 -1
- package/dist/server/handlers/scorer-versions.cjs +3 -3
- package/dist/server/handlers/scorer-versions.js +3 -3
- package/dist/server/handlers/scores.cjs +1 -1
- package/dist/server/handlers/scores.js +1 -1
- package/dist/server/handlers/stored-agent-favorites.cjs +5 -5
- package/dist/server/handlers/stored-agent-favorites.js +5 -5
- package/dist/server/handlers/stored-agents.cjs +7 -7
- package/dist/server/handlers/stored-agents.js +7 -7
- package/dist/server/handlers/stored-mcp-clients.cjs +3 -3
- package/dist/server/handlers/stored-mcp-clients.js +3 -3
- package/dist/server/handlers/stored-prompt-blocks.cjs +3 -3
- package/dist/server/handlers/stored-prompt-blocks.js +3 -3
- package/dist/server/handlers/stored-scorers.cjs +3 -3
- package/dist/server/handlers/stored-scorers.js +3 -3
- package/dist/server/handlers/stored-skill-favorites.cjs +5 -5
- package/dist/server/handlers/stored-skill-favorites.js +5 -5
- package/dist/server/handlers/stored-skills.cjs +5 -5
- package/dist/server/handlers/stored-skills.js +5 -5
- package/dist/server/handlers/stored-workspaces.cjs +3 -3
- package/dist/server/handlers/stored-workspaces.js +3 -3
- package/dist/server/handlers/system.cjs +3 -3
- package/dist/server/handlers/system.js +3 -3
- package/dist/server/handlers/tool-providers.cjs +3 -3
- package/dist/server/handlers/tool-providers.js +3 -3
- package/dist/server/handlers/tools.cjs +1 -1
- package/dist/server/handlers/tools.js +1 -1
- package/dist/server/handlers/utils.cjs +1 -1
- package/dist/server/handlers/utils.js +1 -1
- package/dist/server/handlers/validate-agent-instructions.cjs +1 -1
- package/dist/server/handlers/validate-agent-instructions.js +1 -1
- package/dist/server/handlers/vector.cjs +1 -1
- package/dist/server/handlers/vector.js +1 -1
- package/dist/server/handlers/workflow-builder.cjs +1 -1
- package/dist/server/handlers/workflow-builder.js +1 -1
- package/dist/server/handlers/workflows.cjs +1 -1
- package/dist/server/handlers/workflows.d.ts.map +1 -1
- package/dist/server/handlers/workflows.js +1 -1
- package/dist/server/handlers/workspace.cjs +1 -1
- package/dist/server/handlers/workspace.d.ts +23 -23
- package/dist/server/handlers/workspace.js +1 -1
- package/dist/server/handlers.cjs +16 -16
- package/dist/server/handlers.js +16 -16
- package/dist/server/schemas/index.cjs +20 -20
- package/dist/server/schemas/index.js +20 -20
- package/dist/server/server-adapter/index.cjs +231 -61
- package/dist/server/server-adapter/index.cjs.map +1 -1
- package/dist/server/server-adapter/index.d.ts +67 -1
- package/dist/server/server-adapter/index.d.ts.map +1 -1
- package/dist/server/server-adapter/index.js +226 -63
- package/dist/server/server-adapter/index.js.map +1 -1
- package/dist/server/server-adapter/mcp-auth.d.ts +16 -1
- package/dist/server/server-adapter/mcp-auth.d.ts.map +1 -1
- package/dist/server/server-adapter/routes/observability.d.ts +42 -4
- package/dist/server/server-adapter/routes/observability.d.ts.map +1 -1
- package/dist/{tools-CI5oeJWT.cjs → tools-C9W7WvyI.cjs} +7 -7
- package/dist/{tools-CI5oeJWT.cjs.map → tools-C9W7WvyI.cjs.map} +1 -1
- package/dist/{tools-BAmCNGM5.js → tools-Ce7SFoT1.js} +7 -7
- package/dist/{tools-BAmCNGM5.js.map → tools-Ce7SFoT1.js.map} +1 -1
- package/dist/{utils-9PRHHTGC.cjs → utils-BXEJ6FZC.cjs} +2 -2
- package/dist/{utils-9PRHHTGC.cjs.map → utils-BXEJ6FZC.cjs.map} +1 -1
- package/dist/{utils-BhBJHsqX.cjs → utils-CL-m2SWZ.cjs} +3 -3
- package/dist/{utils-BhBJHsqX.cjs.map → utils-CL-m2SWZ.cjs.map} +1 -1
- package/dist/{utils-B15w-1hm.js → utils-CTYtskHa.js} +2 -2
- package/dist/{utils-B15w-1hm.js.map → utils-CTYtskHa.js.map} +1 -1
- package/dist/{utils-Dy_dQTlK.js → utils-y-cW3mQU.js} +3 -3
- package/dist/{utils-Dy_dQTlK.js.map → utils-y-cW3mQU.js.map} +1 -1
- package/dist/{vector-BZ1bKtwM.cjs → vector-6k7Ft7EX.cjs} +3 -3
- package/dist/{vector-BZ1bKtwM.cjs.map → vector-6k7Ft7EX.cjs.map} +1 -1
- package/dist/{vector-BAs5o6mH.js → vector-BWFSDXvg.js} +3 -3
- package/dist/{vector-BAs5o6mH.js.map → vector-BWFSDXvg.js.map} +1 -1
- package/dist/{workflow-builder-CaSfD6oL.js → workflow-builder-BNk301jl.js} +4 -4
- package/dist/{workflow-builder-CaSfD6oL.js.map → workflow-builder-BNk301jl.js.map} +1 -1
- package/dist/{workflow-builder-tr_D_ZDN.cjs → workflow-builder-CsOEskDo.cjs} +4 -4
- package/dist/{workflow-builder-tr_D_ZDN.cjs.map → workflow-builder-CsOEskDo.cjs.map} +1 -1
- package/dist/{workflows-BxXS5AfE.js → workflows-BAFGmHCW.js} +24 -13
- package/dist/workflows-BAFGmHCW.js.map +1 -0
- package/dist/{workflows-Cdi6w8JW.cjs → workflows-CJz5Eh0B.cjs} +76 -65
- package/dist/workflows-CJz5Eh0B.cjs.map +1 -0
- package/dist/{workspace-BU6sQpbV.cjs → workspace-C7PytFzz.cjs} +3 -3
- package/dist/{workspace-BU6sQpbV.cjs.map → workspace-C7PytFzz.cjs.map} +1 -1
- package/dist/{workspace-CS-GYTve.js → workspace-CYwDvH0G.js} +3 -3
- package/dist/{workspace-CS-GYTve.js.map → workspace-CYwDvH0G.js.map} +1 -1
- package/package.json +5 -5
- package/dist/dist-BKNKucT9.cjs.map +0 -1
- package/dist/dist-CIYZuix4.js.map +0 -1
- package/dist/dist-mNQb9_wX.js +0 -1
- package/dist/helpers-BKtUXhz2.cjs.map +0 -1
- package/dist/helpers-DNq3LtLq.js.map +0 -1
- package/dist/observability-new-endpoints-Di7m_-xc.js.map +0 -1
- package/dist/observability-new-endpoints-jjCgXuTF.cjs.map +0 -1
- package/dist/workflows-BxXS5AfE.js.map +0 -1
- package/dist/workflows-Cdi6w8JW.cjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dynamic-workflows-CpCkqM1g.cjs","names":["z","createRoute","HTTPException","handleError"],"sources":["../src/server/schemas/dynamic-workflows.ts","../src/server/handlers/dynamic-workflows.ts"],"sourcesContent":["import { z } from 'zod/v4';\n\n// ============================================================================\n// Serialized graph — discriminated union mirroring core's SerializedStepFlowEntry.\n// Duplicated locally rather than imported from @mastra/core/workflows because\n// this file's peer-dependency floor predates that export. Structurally\n// compatible with `Mastra.addDynamicWorkflow`'s input; the handler casts once\n// to bridge the remaining wire-vs-runtime divergences (sleepUntil.date as\n// ISO string, fluent-builder-only debug labels) that the core rehydrator\n// handles at runtime.\n// ============================================================================\n\nconst stepOptionsSchema = z\n .object({\n retries: z.number().int().nonnegative().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n })\n .optional();\n\n// Optional identity/display fields on control-flow entries (mirrors core's\n// `StepFlowEntryOptions`). Declared explicitly because zod's default object\n// mode strips unknown keys — without these, posted fields would vanish\n// silently before reaching core.\nconst entryDisplayFields = {\n description: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n};\nconst containerIdentityFields = {\n id: z.string().optional(),\n ...entryDisplayFields,\n};\n\n// ----------------------------------------------------------------------------\n// Predicate DSL — declarative condition for `conditional` / `loop` entries.\n// Mirrors `Predicate` in `@mastra/core/workflows/predicate`; duplicated\n// locally for the same peer-floor reason as the graph schema above.\n// ----------------------------------------------------------------------------\nconst literalScalar = z.union([z.string(), z.number(), z.boolean(), z.null()]);\nconst pathOrLiteral: z.ZodType = z.union([\n z.object({ path: z.string().min(1) }).strict(),\n z.object({ literal: literalScalar }).strict(),\n]);\nconst predicateSchema: z.ZodType = z.lazy(() =>\n z.union([\n z\n .object({\n op: z.enum(['eq', 'ne', 'lt', 'lte', 'gt', 'gte']),\n left: pathOrLiteral,\n right: pathOrLiteral,\n })\n .strict(),\n z\n .object({\n op: z.enum(['in', 'notIn']),\n value: pathOrLiteral,\n set: z.array(literalScalar).min(1),\n })\n .strict(),\n z.object({ op: z.enum(['exists', 'notExists']), path: z.string().min(1) }).strict(),\n z.object({ op: z.enum(['truthy', 'falsy']), value: pathOrLiteral }).strict(),\n z.object({ op: z.enum(['and', 'or']), args: z.array(predicateSchema).min(1) }).strict(),\n z.object({ op: z.literal('not'), arg: predicateSchema }).strict(),\n ]),\n);\n\nconst agentEntrySchema = z.object({\n type: z.literal('agent'),\n id: z.string(),\n agentId: z.string(),\n description: z.string().optional(),\n outputSchema: z.record(z.string(), z.unknown()).optional(),\n options: stepOptionsSchema,\n});\n\nconst toolEntrySchema = z.object({\n type: z.literal('tool'),\n id: z.string(),\n toolId: z.string(),\n description: z.string().optional(),\n options: stepOptionsSchema,\n});\n\nconst mappingEntrySchema = z.object({\n type: z.literal('mapping'),\n id: z.string(),\n ...entryDisplayFields,\n mapConfig: z.string(),\n});\n\nconst workflowEntrySchema = z.object({\n type: z.literal('workflow'),\n id: z.string(),\n workflowId: z.string(),\n description: z.string().optional(),\n});\n\nconst singleStepEntrySchema = z.discriminatedUnion('type', [\n agentEntrySchema,\n toolEntrySchema,\n mappingEntrySchema,\n workflowEntrySchema,\n]);\n\nconst foreachInnerStepSchema = z.discriminatedUnion('type', [agentEntrySchema, toolEntrySchema, workflowEntrySchema]);\n\nconst graphEntrySchema = z.discriminatedUnion('type', [\n agentEntrySchema,\n toolEntrySchema,\n mappingEntrySchema,\n workflowEntrySchema,\n z.object({\n type: z.literal('parallel'),\n ...containerIdentityFields,\n steps: z.array(singleStepEntrySchema),\n }),\n z.object({\n type: z.literal('foreach'),\n ...containerIdentityFields,\n step: foreachInnerStepSchema,\n opts: z.object({ concurrency: z.number().int().positive() }).optional(),\n }),\n z.object({\n type: z.literal('sleep'),\n id: z.string(),\n ...entryDisplayFields,\n duration: z.number(),\n }),\n z.object({\n type: z.literal('sleepUntil'),\n id: z.string(),\n ...entryDisplayFields,\n date: z.string(),\n }),\n z\n .object({\n // Declarative-only conditional. Inbound dynamic workflows must ship a\n // `predicates` array aligned with `steps`; closure-based branches are not\n // accepted over the wire (they'd be arbitrary JS strings we can't\n // safely rehydrate).\n type: z.literal('conditional'),\n ...containerIdentityFields,\n steps: z.array(singleStepEntrySchema),\n predicates: z.array(predicateSchema),\n })\n .refine(entry => entry.predicates.length === entry.steps.length, {\n message:\n 'conditional entries must have exactly one predicate per branch (`predicates` and `steps` must be the same length)',\n path: ['predicates'],\n }),\n z.object({\n // Declarative-only loop. Same rationale as `conditional`.\n type: z.literal('loop'),\n ...containerIdentityFields,\n step: singleStepEntrySchema,\n loopType: z.enum(['dowhile', 'dountil']),\n predicate: predicateSchema,\n }),\n]);\n\n// ============================================================================\n// Path params\n// ============================================================================\n\nexport const dynamicWorkflowIdPathParams = z.object({\n dynamicWorkflowId: z.string().describe('Unique identifier for the dynamic workflow definition'),\n});\n\n// ============================================================================\n// Query params\n// ============================================================================\n\nexport const listDynamicWorkflowsQuerySchema = z.object({\n status: z\n .enum(['active', 'archived'])\n .optional()\n .describe('Filter dynamic workflows by status (defaults to active when omitted by the handler)'),\n authorId: z.string().optional().describe('Filter dynamic workflows by author identifier'),\n});\n\n// ============================================================================\n// Body schemas\n// ============================================================================\n\n/**\n * One static workflow definition on the wire. Matches the input shape of\n * `mastra.addDynamicWorkflow()`.\n */\nexport const dynamicWorkflowDefinitionBodySchema = z.object({\n id: z.string().describe('Workflow id — kebab-case, descriptive'),\n description: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n // Schemas are loose object bags by design: different JSON Schema producers\n // emit slightly different shapes and core's `JsonSchema` type is\n // `Record<string, any>`. Using `z.record` here aligns with that shape so\n // no cast is needed at the handler boundary.\n inputSchema: z.record(z.string(), z.unknown()).describe('JSON Schema (Draft 2020-12) for the workflow input'),\n outputSchema: z.record(z.string(), z.unknown()).describe('JSON Schema (Draft 2020-12) for the workflow output'),\n stateSchema: z.record(z.string(), z.unknown()).optional(),\n requestContextSchema: z.record(z.string(), z.unknown()).optional(),\n graph: z\n .array(graphEntrySchema)\n .describe('Static workflow graph — ordered array of serialized step entries with all refs as ids.'),\n});\n\n/**\n * Body for `POST /stored/workflows` — upsert a static workflow definition,\n * optionally together with the helper workflows it nests.\n */\nexport const upsertDynamicWorkflowBodySchema = dynamicWorkflowDefinitionBodySchema.extend({\n // Deliberately a FLAT list rather than a recursive tree: helpers are peers\n // of each other, hydration order is derived from the graphs, and a\n // self-referential Zod schema would not survive OpenAPI generation.\n dependencies: z\n .array(dynamicWorkflowDefinitionBodySchema)\n .optional()\n .describe(\n 'Helper workflow definitions this workflow nests. Saved with it as one unit — the whole set is validated together, ' +\n 'hydrated in derived dependency order, and rejected together, so a failed save never leaves orphaned helpers behind. ' +\n 'Each helper becomes an ordinary dynamic workflow in its own right.',\n ),\n});\n\n// ============================================================================\n// Response schemas\n// ============================================================================\n\n/**\n * Shape returned for any single dynamic workflow row.\n */\nexport const dynamicWorkflowResponseSchema = z.object({\n id: z.string(),\n description: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n inputSchema: z.unknown(),\n outputSchema: z.unknown(),\n stateSchema: z.unknown().optional(),\n requestContextSchema: z.unknown().optional(),\n graph: z.array(z.unknown()),\n status: z.enum(['active', 'archived']),\n source: z.literal('storage'),\n authorId: z.string().optional(),\n createdAt: z.union([z.date(), z.string()]),\n updatedAt: z.union([z.date(), z.string()]),\n});\n\nexport const listDynamicWorkflowsResponseSchema = z.object({\n workflows: z.array(dynamicWorkflowResponseSchema),\n total: z.number(),\n});\n\nexport const getDynamicWorkflowResponseSchema = dynamicWorkflowResponseSchema;\n\nexport const upsertDynamicWorkflowResponseSchema = z.object({\n ok: z.literal(true),\n id: z.string(),\n dependencyIds: z\n .array(z.string())\n .optional()\n .describe('Ids of the helper workflows saved alongside this one. Present only when dependencies were supplied.'),\n});\n\nexport const deleteDynamicWorkflowResponseSchema = z.object({\n success: z.literal(true),\n message: z.string(),\n});\n","import type { Mastra } from '@mastra/core/mastra';\n\nimport { HTTPException } from '../http-exception';\nimport {\n dynamicWorkflowIdPathParams,\n listDynamicWorkflowsQuerySchema,\n upsertDynamicWorkflowBodySchema,\n listDynamicWorkflowsResponseSchema,\n getDynamicWorkflowResponseSchema,\n upsertDynamicWorkflowResponseSchema,\n deleteDynamicWorkflowResponseSchema,\n} from '../schemas/dynamic-workflows';\nimport { createRoute } from '../server-adapter/routes/route-builder';\n\nimport { handleError } from './error';\n\n/**\n * GET /stored/workflows — list stored static workflow definitions.\n *\n * Mirrors `LIST_STORED_AGENTS_ROUTE` but without favorites/visibility/authorship\n * scoping (which the workflow-definitions domain doesn't carry in v1).\n */\nexport const LIST_DYNAMIC_WORKFLOWS_ROUTE = createRoute({\n method: 'GET',\n path: '/stored/workflows',\n responseType: 'json',\n queryParamSchema: listDynamicWorkflowsQuerySchema,\n responseSchema: listDynamicWorkflowsResponseSchema,\n summary: 'List dynamic workflow definitions',\n description: 'Returns workflow definitions persisted to storage. Filterable by status and authorId.',\n tags: ['Dynamic Workflows'],\n requiresAuth: true,\n requiresPermission: 'stored-workflows:read',\n handler: async ({ mastra, status, authorId }) => {\n try {\n const storage = mastra.getStorage();\n if (!storage) throw new HTTPException(500, { message: 'Storage is not configured' });\n\n const store = await storage.getStore('workflowDefinitions');\n if (!store) throw new HTTPException(500, { message: 'workflowDefinitions storage domain is not available' });\n\n const result = await store.list({ status: status ?? 'active', authorId });\n return { workflows: result.definitions, total: result.total };\n } catch (error) {\n return handleError(error, 'Error listing dynamic workflows');\n }\n },\n});\n\n/**\n * GET /stored/workflows/:dynamicWorkflowId — get one dynamic workflow.\n */\nexport const GET_DYNAMIC_WORKFLOW_ROUTE = createRoute({\n method: 'GET',\n path: '/stored/workflows/:dynamicWorkflowId',\n responseType: 'json',\n pathParamSchema: dynamicWorkflowIdPathParams,\n responseSchema: getDynamicWorkflowResponseSchema,\n summary: 'Get a dynamic workflow definition by id',\n description: 'Returns a single workflow definition persisted to storage.',\n tags: ['Dynamic Workflows'],\n requiresAuth: true,\n requiresPermission: 'stored-workflows:read',\n handler: async ({ mastra, dynamicWorkflowId }) => {\n try {\n const storage = mastra.getStorage();\n if (!storage) throw new HTTPException(500, { message: 'Storage is not configured' });\n\n const store = await storage.getStore('workflowDefinitions');\n if (!store) throw new HTTPException(500, { message: 'workflowDefinitions storage domain is not available' });\n\n const def = await store.get(dynamicWorkflowId);\n if (!def) throw new HTTPException(404, { message: `Dynamic workflow \"${dynamicWorkflowId}\" not found` });\n return def;\n } catch (error) {\n return handleError(error, 'Error getting dynamic workflow');\n }\n },\n});\n\n/**\n * POST /stored/workflows — upsert a static workflow definition and live-register\n * it on the Mastra instance.\n *\n * Calls `mastra.addDynamicWorkflow(def)` which persists the row + rehydrates a\n * runnable workflow + registers it via `mastra.addWorkflow(workflow, id)`.\n * After this returns, `GET /workflows/:id` and `POST /workflows/:id/run` work\n * immediately — no server restart needed.\n */\nexport const UPSERT_DYNAMIC_WORKFLOW_ROUTE = createRoute({\n method: 'POST',\n path: '/stored/workflows',\n responseType: 'json',\n bodySchema: upsertDynamicWorkflowBodySchema,\n responseSchema: upsertDynamicWorkflowResponseSchema,\n summary: 'Upsert a dynamic workflow definition and live-register it',\n description:\n 'Persists a static workflow definition and live-registers it on the running Mastra instance. Idempotent — same id updates in place.',\n tags: ['Dynamic Workflows'],\n requiresAuth: true,\n requiresPermission: 'stored-workflows:write',\n handler: async ({\n mastra,\n id,\n description,\n metadata,\n inputSchema,\n outputSchema,\n stateSchema,\n requestContextSchema,\n graph,\n dependencies,\n }) => {\n try {\n // Pick the body fields explicitly — handler args also carry server\n // context (requestContext, abortSignal, ...) which must not leak into\n // the stored definition.\n const def = { id, description, metadata, inputSchema, outputSchema, stateSchema, requestContextSchema, graph };\n // Helpers are saved with the root as one unit so a nested workflow that\n // does not exist yet resolves, and so a rejected root can never leave\n // its helpers behind as orphans. Order within the bundle is derived\n // from the graphs, not from the order the client sent them in.\n const bundle = [...(dependencies ?? []), def];\n // The wire schema is deliberately looser than the core authoring type:\n // it admits `mapping` entries as children of parallel/conditional/loop,\n // which `WorkflowBuilderExecutableInnerEntry` excludes. That is not\n // drift. Letting those through means a misplaced mapping surfaces from\n // the validation domain as a structured `invalid-map-placement` issue —\n // pointed at the offending path and carrying a machine-applicable\n // `remove-workflow-step` repair action that Studio's draft UI consumes —\n // instead of dying at the boundary as an opaque discriminated-union\n // error. `foreach` is excluded from this on purpose: core rejects a\n // foreach mapping body with an unstructured throw during rehydration,\n // so there is no repairable issue to preserve and the wire schema is\n // the better place to catch it.\n //\n // `addDynamicWorkflows` runs a full registry pre-flight before\n // rehydration, so nothing reaches the engine unvalidated; the cast\n // documents this boundary. Narrowing the schema to delete the cast\n // would trade a repairable issue for a generic 400.\n await mastra.addDynamicWorkflows(bundle as Parameters<Mastra['addDynamicWorkflows']>[0]);\n return {\n ok: true as const,\n id: def.id,\n ...(dependencies?.length ? { dependencyIds: dependencies.map(dependency => dependency.id) } : {}),\n };\n } catch (error) {\n return handleError(error, 'Error upserting dynamic workflow');\n }\n },\n});\n\n/**\n * DELETE /stored/workflows/:dynamicWorkflowId — delete a dynamic workflow.\n *\n * Removes the row from storage AND un-registers the live Workflow instance so\n * a subsequent POST with the same id starts from a clean slate. Idempotent.\n */\nexport const DELETE_DYNAMIC_WORKFLOW_ROUTE = createRoute({\n method: 'DELETE',\n path: '/stored/workflows/:dynamicWorkflowId',\n responseType: 'json',\n pathParamSchema: dynamicWorkflowIdPathParams,\n responseSchema: deleteDynamicWorkflowResponseSchema,\n summary: 'Delete a dynamic workflow definition',\n description: 'Removes a dynamic workflow definition and unregisters the live workflow instance. Idempotent.',\n tags: ['Dynamic Workflows'],\n requiresAuth: true,\n requiresPermission: 'stored-workflows:write',\n handler: async ({ mastra, dynamicWorkflowId }) => {\n try {\n const storage = mastra.getStorage();\n if (!storage) throw new HTTPException(500, { message: 'Storage is not configured' });\n\n const store = await storage.getStore('workflowDefinitions');\n if (!store) throw new HTTPException(500, { message: 'workflowDefinitions storage domain is not available' });\n\n await store.delete(dynamicWorkflowId);\n mastra.removeWorkflow(dynamicWorkflowId);\n return { success: true as const, message: `Workflow ${dynamicWorkflowId} deleted` };\n } catch (error) {\n return handleError(error, 'Error deleting dynamic workflow');\n }\n },\n});\n"],"mappings":";;;;;;AAYA,MAAM,oBAAoBA,OAAAA,EACvB,OAAO;CACN,SAASA,OAAAA,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,YAAY,CAAC,CAAC,SAAS;CACjD,UAAUA,OAAAA,EAAE,OAAOA,OAAAA,EAAE,OAAO,GAAGA,OAAAA,EAAE,QAAQ,CAAC,CAAC,CAAC,SAAS;AACvD,CAAC,CAAC,CACD,SAAS;AAMZ,MAAM,qBAAqB;CACzB,aAAaA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;CACjC,UAAUA,OAAAA,EAAE,OAAOA,OAAAA,EAAE,OAAO,GAAGA,OAAAA,EAAE,QAAQ,CAAC,CAAC,CAAC,SAAS;AACvD;AACA,MAAM,0BAA0B;CAC9B,IAAIA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;CACxB,GAAG;AACL;AAOA,MAAM,gBAAgBA,OAAAA,EAAE,MAAM;CAACA,OAAAA,EAAE,OAAO;CAAGA,OAAAA,EAAE,OAAO;CAAGA,OAAAA,EAAE,QAAQ;CAAGA,OAAAA,EAAE,KAAK;AAAC,CAAC;AAC7E,MAAM,gBAA2BA,OAAAA,EAAE,MAAM,CACvCA,OAAAA,EAAE,OAAO,EAAE,MAAMA,OAAAA,EAAE,OAAO,CAAC,CAAC,IAAI,C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;GACd,OAAOC,8BAAAA,YAAY,OAAO,iCAAiC;EAC7D;CACF;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"dynamic-workflows-ZmzWJXxG.cjs","names":["z","createRoute","HTTPException","handleError"],"sources":["../src/server/schemas/dynamic-workflows.ts","../src/server/handlers/dynamic-workflows.ts"],"sourcesContent":["import { z } from 'zod/v4';\n\n// ============================================================================\n// Serialized graph — discriminated union mirroring core's SerializedStepFlowEntry.\n// Duplicated locally rather than imported from @mastra/core/workflows because\n// this file's peer-dependency floor predates that export. Structurally\n// compatible with `Mastra.addDynamicWorkflow`'s input; the handler casts once\n// to bridge the remaining wire-vs-runtime divergences (sleepUntil.date as\n// ISO string, fluent-builder-only debug labels) that the core rehydrator\n// handles at runtime.\n// ============================================================================\n\nconst stepOptionsSchema = z\n .object({\n retries: z.number().int().nonnegative().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n })\n .optional();\n\n// Optional identity/display fields on control-flow entries (mirrors core's\n// `StepFlowEntryOptions`). Declared explicitly because zod's default object\n// mode strips unknown keys — without these, posted fields would vanish\n// silently before reaching core.\nconst entryDisplayFields = {\n description: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n};\nconst containerIdentityFields = {\n id: z.string().optional(),\n ...entryDisplayFields,\n};\n\n// ----------------------------------------------------------------------------\n// Predicate DSL — declarative condition for `conditional` / `loop` entries.\n// Mirrors `Predicate` in `@mastra/core/workflows/predicate`; duplicated\n// locally for the same peer-floor reason as the graph schema above.\n// ----------------------------------------------------------------------------\nconst literalScalar = z.union([z.string(), z.number(), z.boolean(), z.null()]);\nconst pathOrLiteral: z.ZodType = z.union([\n z.object({ path: z.string().min(1) }).strict(),\n z.object({ literal: literalScalar }).strict(),\n]);\nconst predicateSchema: z.ZodType = z.lazy(() =>\n z.union([\n z\n .object({\n op: z.enum(['eq', 'ne', 'lt', 'lte', 'gt', 'gte']),\n left: pathOrLiteral,\n right: pathOrLiteral,\n })\n .strict(),\n z\n .object({\n op: z.enum(['in', 'notIn']),\n value: pathOrLiteral,\n set: z.array(literalScalar).min(1),\n })\n .strict(),\n z.object({ op: z.enum(['exists', 'notExists']), path: z.string().min(1) }).strict(),\n z.object({ op: z.enum(['truthy', 'falsy']), value: pathOrLiteral }).strict(),\n z.object({ op: z.enum(['and', 'or']), args: z.array(predicateSchema).min(1) }).strict(),\n z.object({ op: z.literal('not'), arg: predicateSchema }).strict(),\n ]),\n);\n\nconst agentEntrySchema = z.object({\n type: z.literal('agent'),\n id: z.string(),\n agentId: z.string(),\n description: z.string().optional(),\n outputSchema: z.record(z.string(), z.unknown()).optional(),\n options: stepOptionsSchema,\n});\n\nconst toolEntrySchema = z.object({\n type: z.literal('tool'),\n id: z.string(),\n toolId: z.string(),\n description: z.string().optional(),\n options: stepOptionsSchema,\n});\n\nconst mappingEntrySchema = z.object({\n type: z.literal('mapping'),\n id: z.string(),\n ...entryDisplayFields,\n mapConfig: z.string(),\n});\n\nconst workflowEntrySchema = z.object({\n type: z.literal('workflow'),\n id: z.string(),\n workflowId: z.string(),\n description: z.string().optional(),\n});\n\nconst singleStepEntrySchema = z.discriminatedUnion('type', [\n agentEntrySchema,\n toolEntrySchema,\n mappingEntrySchema,\n workflowEntrySchema,\n]);\n\nconst foreachInnerStepSchema = z.discriminatedUnion('type', [agentEntrySchema, toolEntrySchema, workflowEntrySchema]);\n\nconst graphEntrySchema = z.discriminatedUnion('type', [\n agentEntrySchema,\n toolEntrySchema,\n mappingEntrySchema,\n workflowEntrySchema,\n z.object({\n type: z.literal('parallel'),\n ...containerIdentityFields,\n steps: z.array(singleStepEntrySchema),\n }),\n z.object({\n type: z.literal('foreach'),\n ...containerIdentityFields,\n step: foreachInnerStepSchema,\n opts: z.object({ concurrency: z.number().int().positive() }).optional(),\n }),\n z.object({\n type: z.literal('sleep'),\n id: z.string(),\n ...entryDisplayFields,\n duration: z.number(),\n }),\n z.object({\n type: z.literal('sleepUntil'),\n id: z.string(),\n ...entryDisplayFields,\n date: z.string(),\n }),\n z\n .object({\n // Declarative-only conditional. Inbound dynamic workflows must ship a\n // `predicates` array aligned with `steps`; closure-based branches are not\n // accepted over the wire (they'd be arbitrary JS strings we can't\n // safely rehydrate).\n type: z.literal('conditional'),\n ...containerIdentityFields,\n steps: z.array(singleStepEntrySchema),\n predicates: z.array(predicateSchema),\n })\n .refine(entry => entry.predicates.length === entry.steps.length, {\n message:\n 'conditional entries must have exactly one predicate per branch (`predicates` and `steps` must be the same length)',\n path: ['predicates'],\n }),\n z.object({\n // Declarative-only loop. Same rationale as `conditional`.\n type: z.literal('loop'),\n ...containerIdentityFields,\n step: singleStepEntrySchema,\n loopType: z.enum(['dowhile', 'dountil']),\n predicate: predicateSchema,\n }),\n]);\n\n// ============================================================================\n// Path params\n// ============================================================================\n\nexport const dynamicWorkflowIdPathParams = z.object({\n dynamicWorkflowId: z.string().describe('Unique identifier for the dynamic workflow definition'),\n});\n\n// ============================================================================\n// Query params\n// ============================================================================\n\nexport const listDynamicWorkflowsQuerySchema = z.object({\n status: z\n .enum(['active', 'archived'])\n .optional()\n .describe('Filter dynamic workflows by status (defaults to active when omitted by the handler)'),\n authorId: z.string().optional().describe('Filter dynamic workflows by author identifier'),\n});\n\n// ============================================================================\n// Body schemas\n// ============================================================================\n\n/**\n * One static workflow definition on the wire. Matches the input shape of\n * `mastra.addDynamicWorkflow()`.\n */\nexport const dynamicWorkflowDefinitionBodySchema = z.object({\n id: z.string().describe('Workflow id — kebab-case, descriptive'),\n description: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n // Schemas are loose object bags by design: different JSON Schema producers\n // emit slightly different shapes and core's `JsonSchema` type is\n // `Record<string, any>`. Using `z.record` here aligns with that shape so\n // no cast is needed at the handler boundary.\n inputSchema: z.record(z.string(), z.unknown()).describe('JSON Schema (Draft 2020-12) for the workflow input'),\n outputSchema: z.record(z.string(), z.unknown()).describe('JSON Schema (Draft 2020-12) for the workflow output'),\n stateSchema: z.record(z.string(), z.unknown()).optional(),\n requestContextSchema: z.record(z.string(), z.unknown()).optional(),\n graph: z\n .array(graphEntrySchema)\n .describe('Static workflow graph — ordered array of serialized step entries with all refs as ids.'),\n});\n\n/**\n * Body for `POST /stored/workflows` — upsert a static workflow definition,\n * optionally together with the helper workflows it nests.\n */\nexport const upsertDynamicWorkflowBodySchema = dynamicWorkflowDefinitionBodySchema.extend({\n // Deliberately a FLAT list rather than a recursive tree: helpers are peers\n // of each other, hydration order is derived from the graphs, and a\n // self-referential Zod schema would not survive OpenAPI generation.\n dependencies: z\n .array(dynamicWorkflowDefinitionBodySchema)\n .optional()\n .describe(\n 'Helper workflow definitions this workflow nests. Saved with it as one unit — the whole set is validated together, ' +\n 'hydrated in derived dependency order, and rejected together, so a failed save never leaves orphaned helpers behind. ' +\n 'Each helper becomes an ordinary dynamic workflow in its own right.',\n ),\n});\n\n// ============================================================================\n// Response schemas\n// ============================================================================\n\n/**\n * Shape returned for any single dynamic workflow row.\n */\nexport const dynamicWorkflowResponseSchema = z.object({\n id: z.string(),\n description: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n inputSchema: z.unknown(),\n outputSchema: z.unknown(),\n stateSchema: z.unknown().optional(),\n requestContextSchema: z.unknown().optional(),\n graph: z.array(z.unknown()),\n status: z.enum(['active', 'archived']),\n source: z.literal('storage'),\n authorId: z.string().optional(),\n createdAt: z.union([z.date(), z.string()]),\n updatedAt: z.union([z.date(), z.string()]),\n});\n\nexport const listDynamicWorkflowsResponseSchema = z.object({\n workflows: z.array(dynamicWorkflowResponseSchema),\n total: z.number(),\n});\n\nexport const getDynamicWorkflowResponseSchema = dynamicWorkflowResponseSchema;\n\nexport const upsertDynamicWorkflowResponseSchema = z.object({\n ok: z.literal(true),\n id: z.string(),\n dependencyIds: z\n .array(z.string())\n .optional()\n .describe('Ids of the helper workflows saved alongside this one. Present only when dependencies were supplied.'),\n});\n\nexport const deleteDynamicWorkflowResponseSchema = z.object({\n success: z.literal(true),\n message: z.string(),\n});\n","import type { Mastra } from '@mastra/core/mastra';\n\nimport { HTTPException } from '../http-exception';\nimport {\n dynamicWorkflowIdPathParams,\n listDynamicWorkflowsQuerySchema,\n upsertDynamicWorkflowBodySchema,\n listDynamicWorkflowsResponseSchema,\n getDynamicWorkflowResponseSchema,\n upsertDynamicWorkflowResponseSchema,\n deleteDynamicWorkflowResponseSchema,\n} from '../schemas/dynamic-workflows';\nimport { createRoute } from '../server-adapter/routes/route-builder';\n\nimport { handleError } from './error';\n\n/**\n * GET /stored/workflows — list stored static workflow definitions.\n *\n * Mirrors `LIST_STORED_AGENTS_ROUTE` but without favorites/visibility/authorship\n * scoping (which the workflow-definitions domain doesn't carry in v1).\n */\nexport const LIST_DYNAMIC_WORKFLOWS_ROUTE = createRoute({\n method: 'GET',\n path: '/stored/workflows',\n responseType: 'json',\n queryParamSchema: listDynamicWorkflowsQuerySchema,\n responseSchema: listDynamicWorkflowsResponseSchema,\n summary: 'List dynamic workflow definitions',\n description: 'Returns workflow definitions persisted to storage. Filterable by status and authorId.',\n tags: ['Dynamic Workflows'],\n requiresAuth: true,\n requiresPermission: 'stored-workflows:read',\n handler: async ({ mastra, status, authorId }) => {\n try {\n const storage = mastra.getStorage();\n if (!storage) throw new HTTPException(500, { message: 'Storage is not configured' });\n\n const store = await storage.getStore('workflowDefinitions');\n if (!store) throw new HTTPException(500, { message: 'workflowDefinitions storage domain is not available' });\n\n const result = await store.list({ status: status ?? 'active', authorId });\n return { workflows: result.definitions, total: result.total };\n } catch (error) {\n return handleError(error, 'Error listing dynamic workflows');\n }\n },\n});\n\n/**\n * GET /stored/workflows/:dynamicWorkflowId — get one dynamic workflow.\n */\nexport const GET_DYNAMIC_WORKFLOW_ROUTE = createRoute({\n method: 'GET',\n path: '/stored/workflows/:dynamicWorkflowId',\n responseType: 'json',\n pathParamSchema: dynamicWorkflowIdPathParams,\n responseSchema: getDynamicWorkflowResponseSchema,\n summary: 'Get a dynamic workflow definition by id',\n description: 'Returns a single workflow definition persisted to storage.',\n tags: ['Dynamic Workflows'],\n requiresAuth: true,\n requiresPermission: 'stored-workflows:read',\n handler: async ({ mastra, dynamicWorkflowId }) => {\n try {\n const storage = mastra.getStorage();\n if (!storage) throw new HTTPException(500, { message: 'Storage is not configured' });\n\n const store = await storage.getStore('workflowDefinitions');\n if (!store) throw new HTTPException(500, { message: 'workflowDefinitions storage domain is not available' });\n\n const def = await store.get(dynamicWorkflowId);\n if (!def) throw new HTTPException(404, { message: `Dynamic workflow \"${dynamicWorkflowId}\" not found` });\n return def;\n } catch (error) {\n return handleError(error, 'Error getting dynamic workflow');\n }\n },\n});\n\n/**\n * POST /stored/workflows — upsert a static workflow definition and live-register\n * it on the Mastra instance.\n *\n * Calls `mastra.addDynamicWorkflow(def)` which persists the row + rehydrates a\n * runnable workflow + registers it via `mastra.addWorkflow(workflow, id)`.\n * After this returns, `GET /workflows/:id` and `POST /workflows/:id/run` work\n * immediately — no server restart needed.\n */\nexport const UPSERT_DYNAMIC_WORKFLOW_ROUTE = createRoute({\n method: 'POST',\n path: '/stored/workflows',\n responseType: 'json',\n bodySchema: upsertDynamicWorkflowBodySchema,\n responseSchema: upsertDynamicWorkflowResponseSchema,\n summary: 'Upsert a dynamic workflow definition and live-register it',\n description:\n 'Persists a static workflow definition and live-registers it on the running Mastra instance. Idempotent — same id updates in place.',\n tags: ['Dynamic Workflows'],\n requiresAuth: true,\n requiresPermission: 'stored-workflows:write',\n handler: async ({\n mastra,\n id,\n description,\n metadata,\n inputSchema,\n outputSchema,\n stateSchema,\n requestContextSchema,\n graph,\n dependencies,\n }) => {\n try {\n // Pick the body fields explicitly — handler args also carry server\n // context (requestContext, abortSignal, ...) which must not leak into\n // the stored definition.\n const def = { id, description, metadata, inputSchema, outputSchema, stateSchema, requestContextSchema, graph };\n // Helpers are saved with the root as one unit so a nested workflow that\n // does not exist yet resolves, and so a rejected root can never leave\n // its helpers behind as orphans. Order within the bundle is derived\n // from the graphs, not from the order the client sent them in.\n const bundle = [...(dependencies ?? []), def];\n // The wire schema is deliberately looser than the core authoring type:\n // it admits `mapping` entries as children of parallel/conditional/loop,\n // which `WorkflowBuilderExecutableInnerEntry` excludes. That is not\n // drift. Letting those through means a misplaced mapping surfaces from\n // the validation domain as a structured `invalid-map-placement` issue —\n // pointed at the offending path and carrying a machine-applicable\n // `remove-workflow-step` repair action that Studio's draft UI consumes —\n // instead of dying at the boundary as an opaque discriminated-union\n // error. `foreach` is excluded from this on purpose: core rejects a\n // foreach mapping body with an unstructured throw during rehydration,\n // so there is no repairable issue to preserve and the wire schema is\n // the better place to catch it.\n //\n // `addDynamicWorkflows` runs a full registry pre-flight before\n // rehydration, so nothing reaches the engine unvalidated; the cast\n // documents this boundary. Narrowing the schema to delete the cast\n // would trade a repairable issue for a generic 400.\n await mastra.addDynamicWorkflows(bundle as Parameters<Mastra['addDynamicWorkflows']>[0]);\n return {\n ok: true as const,\n id: def.id,\n ...(dependencies?.length ? { dependencyIds: dependencies.map(dependency => dependency.id) } : {}),\n };\n } catch (error) {\n return handleError(error, 'Error upserting dynamic workflow');\n }\n },\n});\n\n/**\n * DELETE /stored/workflows/:dynamicWorkflowId — delete a dynamic workflow.\n *\n * Removes the row from storage AND un-registers the live Workflow instance so\n * a subsequent POST with the same id starts from a clean slate. Idempotent.\n */\nexport const DELETE_DYNAMIC_WORKFLOW_ROUTE = createRoute({\n method: 'DELETE',\n path: '/stored/workflows/:dynamicWorkflowId',\n responseType: 'json',\n pathParamSchema: dynamicWorkflowIdPathParams,\n responseSchema: deleteDynamicWorkflowResponseSchema,\n summary: 'Delete a dynamic workflow definition',\n description: 'Removes a dynamic workflow definition and unregisters the live workflow instance. Idempotent.',\n tags: ['Dynamic Workflows'],\n requiresAuth: true,\n requiresPermission: 'stored-workflows:write',\n handler: async ({ mastra, dynamicWorkflowId }) => {\n try {\n const storage = mastra.getStorage();\n if (!storage) throw new HTTPException(500, { message: 'Storage is not configured' });\n\n const store = await storage.getStore('workflowDefinitions');\n if (!store) throw new HTTPException(500, { message: 'workflowDefinitions storage domain is not available' });\n\n await store.delete(dynamicWorkflowId);\n mastra.removeWorkflow(dynamicWorkflowId);\n return { success: true as const, message: `Workflow ${dynamicWorkflowId} deleted` };\n } catch (error) {\n return handleError(error, 'Error deleting dynamic workflow');\n }\n },\n});\n"],"mappings":";;;;;;AAYA,MAAM,oBAAoBA,OAAAA,EACvB,OAAO;CACN,SAASA,OAAAA,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,YAAY,CAAC,CAAC,SAAS;CACjD,UAAUA,OAAAA,EAAE,OAAOA,OAAAA,EAAE,OAAO,GAAGA,OAAAA,EAAE,QAAQ,CAAC,CAAC,CAAC,SAAS;AACvD,CAAC,CAAC,CACD,SAAS;AAMZ,MAAM,qBAAqB;CACzB,aAAaA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;CACjC,UAAUA,OAAAA,EAAE,OAAOA,OAAAA,EAAE,OAAO,GAAGA,OAAAA,EAAE,QAAQ,CAAC,CAAC,CAAC,SAAS;AACvD;AACA,MAAM,0BAA0B;CAC9B,IAAIA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;CACxB,GAAG;AACL;AAOA,MAAM,gBAAgBA,OAAAA,EAAE,MAAM;CAACA,OAAAA,EAAE,OAAO;CAAGA,OAAAA,EAAE,OAAO;CAAGA,OAAAA,EAAE,QAAQ;CAAGA,OAAAA,EAAE,KAAK;AAAC,CAAC;AAC7E,MAAM,gBAA2BA,OAAAA,EAAE,MAAM,CACvCA,OAAAA,EAAE,OAAO,EAAE,MAAMA,OAAAA,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,GAC7CA,OAAAA,EAAE,OAAO,EAAE,SAAS,cAAc,CAAC,CAAC,CAAC,OAAO,CAC9C,CAAC;AACD,MAAM,kBAA6BA,OAAAA,EAAE,WACnCA,OAAAA,EAAE,MAAM;CACNA,OAAAA,EACG,OAAO;EACN,IAAIA,OAAAA,EAAE,KAAK;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,IAAI;GAIF,MAAM,MAAM;IAAE;IAAI;IAAa;IAAU;IAAa;IAAc;IAAa;IAAsB;GAAM;GAK7G,MAAM,SAAS,CAAC,GAAI,gBAAgB,CAAC,GAAI,GAAG;GAkB5C,MAAM,OAAO,oBAAoB,MAAsD;GACvF,OAAO;IACL,IAAI;IACJ,IAAI,IAAI;IACR,GAAI,cAAc,SAAS,EAAE,eAAe,aAAa,KAAI,eAAc,WAAW,EAAE,EAAE,IAAI,CAAC;GACjG;EACF,SAAS,OAAO;GACd,OAAOE,8BAAAA,YAAY,OAAO,kCAAkC;EAC9D;CACF;AACF,CAAC;;;;;;;AAQD,MAAa,gCAAgCF,sBAAAA,YAAY;CACvD,QAAQ;CACR,MAAM;CACN,cAAc;CACd,iBAAiB;CACjB,gBAAgB;CAChB,SAAS;CACT,aAAa;CACb,MAAM,CAAC,mBAAmB;CAC1B,cAAc;CACd,oBAAoB;CACpB,SAAS,OAAO,EAAE,QAAQ,wBAAwB;EAChD,IAAI;GACF,MAAM,UAAU,OAAO,WAAW;GAClC,IAAI,CAAC,SAAS,MAAM,IAAIC,uBAAAA,cAAc,KAAK,EAAE,SAAS,4BAA4B,CAAC;GAEnF,MAAM,QAAQ,MAAM,QAAQ,SAAS,qBAAqB;GAC1D,IAAI,CAAC,OAAO,MAAM,IAAIA,uBAAAA,cAAc,KAAK,EAAE,SAAS,sDAAsD,CAAC;GAE3G,MAAM,MAAM,OAAO,iBAAiB;GACpC,OAAO,eAAe,iBAAiB;GACvC,OAAO;IAAE,SAAS;IAAe,SAAS,YAAY,kBAAkB;GAAU;EACpF,SAAS,OAAO;GACd,OAAOC,8BAAAA,YAAY,OAAO,iCAAiC;EAC7D;CACF;AACF,CAAC"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { t as HTTPException } from "./http-exception-CzaWkxMl.js";
|
|
2
|
-
import { n as createRoute } from "./route-builder-BxPrwNog.js";
|
|
3
|
-
import { handleError } from "./server/handlers/error.js";
|
|
4
|
-
import { U as buildProvidersList } from "./agents-CgcW6lHt.js";
|
|
5
2
|
import { i as builderAvailableModelsResponseSchema, l as infrastructureStatusResponseSchema, n as agentFeaturesSchema, s as builderSettingsResponseSchema } from "./editor-builder-Bln4Pg1U.js";
|
|
3
|
+
import { n as createRoute } from "./route-builder-BKEzjw_M.js";
|
|
4
|
+
import { U as buildProvidersList } from "./agents-BI8ez-FT.js";
|
|
5
|
+
import { handleError } from "./server/handlers/error.js";
|
|
6
6
|
// src/server/utils/resolve-builder-model-policy.ts
|
|
7
7
|
/**
|
|
8
8
|
* Server-side wrapper around `builderToModelPolicy`.
|
|
@@ -333,4 +333,4 @@ const GET_INFRASTRUCTURE_STATUS_ROUTE = createRoute({
|
|
|
333
333
|
});
|
|
334
334
|
export { requireBuilderFeature as a, isBuilderFeatureEnabled as i, GET_EDITOR_BUILDER_SETTINGS_ROUTE as n, GET_INFRASTRUCTURE_STATUS_ROUTE as r, GET_EDITOR_BUILDER_AVAILABLE_MODELS_ROUTE as t };
|
|
335
335
|
|
|
336
|
-
//# sourceMappingURL=editor-builder-
|
|
336
|
+
//# sourceMappingURL=editor-builder-CbfX5bvL.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"editor-builder-Ceen28s8.js","names":[],"sources":["../src/server/utils/resolve-builder-model-policy.ts","../src/server/handlers/editor-builder.ts"],"sourcesContent":["import type { BuilderModelPolicy } from '@mastra/core/agent-builder/ee';\nimport type { IMastraEditor } from '@mastra/core/editor';\n\n/**\n * Server-side wrapper around `builderToModelPolicy`.\n *\n * Handles the optional `IMastraEditor` builder API surface (older / OSS editors\n * may not implement `hasEnabledBuilderConfig` / `resolveBuilder`) and returns\n * a uniform `BuilderModelPolicy` to every call site.\n *\n * Returns `{ active: false }` whenever:\n * - no editor is configured,\n * - the editor doesn't expose builder methods,\n * - the builder config is disabled, or\n * - resolving the builder fails / yields nothing.\n *\n * The `@mastra/core/agent-builder/ee` subpath is loaded lazily so this module\n * remains importable on `@mastra/core` versions that pre-date the subpath\n * (the subpath was added in core 1.34.0). The dynamic import is only reached\n * once an editor is actually configured, by which point a compatible core is\n * guaranteed.\n */\nexport async function resolveBuilderModelPolicy(editor: IMastraEditor | undefined): Promise<BuilderModelPolicy> {\n if (!editor) return { active: false };\n if (typeof editor.resolveBuilder !== 'function') return { active: false };\n if (typeof editor.hasEnabledBuilderConfig === 'function' && !editor.hasEnabledBuilderConfig()) {\n return { active: false };\n }\n\n // Degrade to inactive on builder-resolution failure rather than letting the\n // rejection escape: agent execution routes seed this on every request, so a\n // transient failure must not 500 the entire route.\n try {\n const builder = await editor.resolveBuilder();\n const { builderToModelPolicy } = await import('@mastra/core/agent-builder/ee');\n return builderToModelPolicy(builder);\n } catch {\n return { active: false };\n }\n}\n","import type { Mastra } from '@mastra/core';\nimport type { ChannelProvider } from '@mastra/core/channels';\n\nimport { HTTPException } from '../http-exception';\nimport {\n agentFeaturesSchema,\n builderAvailableModelsResponseSchema,\n builderSettingsResponseSchema,\n infrastructureStatusResponseSchema,\n} from '../schemas/editor-builder';\nimport type { AgentFeatures, InfrastructureStatus } from '../schemas/editor-builder';\nimport { createRoute } from '../server-adapter/routes/route-builder';\nimport { resolveBuilderModelPolicy } from '../utils/resolve-builder-model-policy';\nimport { buildProvidersList } from './agents';\nimport { handleError } from './error';\n\n/**\n * Resolve the active builder feature flags. Returns `null` when the editor is\n * absent, the builder is disabled, or no features are configured.\n */\nasync function resolveBuilderFeatures(mastra: Mastra): Promise<AgentFeatures | null> {\n const editor = mastra.getEditor();\n if (!editor || typeof editor.resolveBuilder !== 'function') return null;\n if (!editor.hasEnabledBuilderConfig?.()) return null;\n const builder = await editor.resolveBuilder();\n if (!builder || !builder.enabled) return null;\n const features = builder.getFeatures?.()?.agent;\n if (!features) return null;\n // Validate the shape so unknown keys cannot smuggle through.\n const parsed = agentFeaturesSchema.safeParse(features);\n return parsed.success ? parsed.data : null;\n}\n\n/**\n * Returns whether a given agent-builder feature is enabled. Used by list /\n * get-by-id handlers to soft-gate response enrichment (omit fields, ignore\n * favoritedOnly / pinFavoritedFor params) when the feature is off.\n */\nexport async function isBuilderFeatureEnabled(mastra: Mastra, feature: keyof AgentFeatures): Promise<boolean> {\n const features = await resolveBuilderFeatures(mastra);\n return features?.[feature] === true;\n}\n\n/**\n * Hard-gate helper for mutation routes that must not exist when the feature\n * is off. Throws `HTTPException(404)` so we don't leak the existence of the\n * feature surface (matches behavior of unregistered routes).\n */\nexport async function requireBuilderFeature(mastra: Mastra, feature: keyof AgentFeatures): Promise<void> {\n if (!(await isBuilderFeatureEnabled(mastra, feature))) {\n throw new HTTPException(404, { message: 'Not Found' });\n }\n}\n\n/**\n * GET /editor/builder/settings\n *\n * Returns the agent builder settings configured by the admin.\n * Used by frontend to determine which features to display.\n */\nexport const GET_EDITOR_BUILDER_SETTINGS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/builder/settings',\n responseType: 'json',\n responseSchema: builderSettingsResponseSchema,\n summary: 'Get agent builder settings',\n description: 'Returns the agent builder feature flags and configuration for UI gating',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'stored-agents:read',\n handler: async ({ mastra }) => {\n try {\n const editor = mastra.getEditor();\n\n // No editor configured\n if (!editor) {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n // Editor doesn't support builder (older version or OSS)\n if (typeof editor.resolveBuilder !== 'function') {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n // Check if builder is enabled in config\n if (!editor.hasEnabledBuilderConfig?.()) {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n // Resolve the builder instance\n const builder = await editor.resolveBuilder();\n if (!builder || !builder.enabled) {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n const baseWarnings = builder.getModelPolicyWarnings?.() ?? [];\n const configuration = builder.getConfiguration();\n\n // Picker allowlists are written against entity `.id` (what users see in\n // the UI, URLs, traces). The client filters list responses by their\n // response keys, which are not always `.id`:\n // - GET /agents keys by `agent.id`\n // - GET /tools keys by registration key (values include `id`)\n // - GET /workflows keys by registration key (values omit `id`)\n // To keep the client filter simple, we accept `.id` (fallback to\n // registration key) for matching, but emit visible IDs as response keys\n // so `Object.keys(data)` lines up.\n type AliasPair = { id: string; key: string };\n const collectAliases = (registry: Record<string, unknown>): AliasPair[] =>\n Object.entries(registry).map(([key, entity]) => ({\n id: (entity as { id?: string }).id || key,\n key,\n }));\n\n const toolAliases = collectAliases(mastra.listTools() ?? {});\n const agentAliases = collectAliases(mastra.listAgents() ?? {});\n const workflowAliases = collectAliases(mastra.listWorkflows() ?? {});\n\n // Tools/workflows responses are keyed by registration key. Agents\n // response is keyed by `.id`.\n const toResponseKey = (aliases: AliasPair[], byId: 'id' | 'key') => {\n const map = new Map<string, string>();\n for (const a of aliases) {\n map.set(a.id, byId === 'id' ? a.id : a.key);\n map.set(a.key, byId === 'id' ? a.id : a.key);\n }\n return map;\n };\n const toolKeyMap = toResponseKey(toolAliases, 'key');\n const agentKeyMap = toResponseKey(agentAliases, 'id');\n const workflowKeyMap = toResponseKey(workflowAliases, 'key');\n\n // Lazy-load the EE subpath so this module remains importable on\n // `@mastra/core` versions that pre-date it (added in core 1.34.0).\n // We only reach here after `builder.enabled` is true, which guarantees\n // a compatible core.\n const { builderToModelPolicy, resolvePickerVisibility } = await import('@mastra/core/agent-builder/ee');\n\n const picker = resolvePickerVisibility({\n config: configuration?.agent,\n registeredToolIds: toolAliases.flatMap(a => [a.id, a.key]),\n registeredAgentIds: agentAliases.flatMap(a => [a.id, a.key]),\n registeredWorkflowIds: workflowAliases.flatMap(a => [a.id, a.key]),\n });\n\n const normalize = (visible: string[] | null, map: Map<string, string>): string[] | null => {\n if (visible === null) return null;\n const out: string[] = [];\n const seen = new Set<string>();\n for (const id of visible) {\n const mapped = map.get(id);\n if (mapped && !seen.has(mapped)) {\n seen.add(mapped);\n out.push(mapped);\n }\n }\n return out;\n };\n\n const modelPolicyWarnings = [...baseWarnings, ...picker.warnings];\n\n return {\n enabled: true,\n features: builder.getFeatures(),\n configuration,\n modelPolicy: builderToModelPolicy(builder),\n picker: {\n visibleTools: normalize(picker.visibleTools, toolKeyMap),\n visibleAgents: normalize(picker.visibleAgents, agentKeyMap),\n visibleWorkflows: normalize(picker.visibleWorkflows, workflowKeyMap),\n },\n ...(modelPolicyWarnings.length > 0 ? { modelPolicyWarnings } : {}),\n };\n } catch (error) {\n return handleError(error, 'Error getting builder settings');\n }\n },\n});\n\n/**\n * GET /editor/builder/models/available\n *\n * Returns the configured AI providers/models the agent builder may use. The\n * server is the single authority: it scopes the list to providers with a\n * configured API key (`connected`) and applies the active builder model\n * policy via `isModelAllowed`, so the Studio surfaces can render the response\n * verbatim without importing any EE matcher into the browser.\n *\n * - Providers without a configured API key are always omitted — the builder\n * decides the agent's model from this list, so an unconnected provider would\n * produce an agent that can never run.\n * - Policy inactive (or no allowlist) ⇒ all connected providers are returned.\n * - Policy active with an allowlist ⇒ each connected provider's models are\n * filtered, and providers left with no allowed models are omitted entirely.\n */\nexport const GET_EDITOR_BUILDER_AVAILABLE_MODELS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/builder/models/available',\n responseType: 'json',\n responseSchema: builderAvailableModelsResponseSchema,\n summary: 'List builder-available AI models',\n description: 'Returns AI providers/models filtered by the active agent-builder model policy.',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'stored-agents:read',\n handler: async ({ mastra }) => {\n try {\n // Only surface providers whose API key is configured (`connected`). The\n // agent builder decides the agent's model from this list, so including\n // providers without a key lets it pick a model that can never run. We\n // scope to connected providers so every choice is actually usable.\n const providers = (await buildProvidersList(mastra)).filter(provider => provider.connected);\n const policy = await resolveBuilderModelPolicy(mastra.getEditor());\n\n // Inactive policy (or no allowlist) ⇒ no allowlist filtering to apply.\n if (!policy.active || !policy.allowed || policy.allowed.length === 0) {\n return { providers };\n }\n\n // Lazy-load the EE matcher (server-only); mirrors the convention used by\n // resolve-builder-model-policy and the settings handler.\n const { isModelAllowed } = await import('@mastra/core/agent-builder/ee');\n\n const filtered = providers\n .map(provider => ({\n ...provider,\n models: provider.models.filter(modelId => isModelAllowed(policy.allowed, { provider: provider.id, modelId })),\n }))\n .filter(provider => provider.models.length > 0);\n\n return { providers: filtered };\n } catch (error) {\n return handleError(error, 'Error fetching available models');\n }\n },\n});\n\n/**\n * GET /editor/builder/infrastructure\n *\n * Returns the runtime status of Mastra-opinionated primitives (channels,\n * browser providers, workspaces). Admin-only; surfaced in Studio Settings so\n * admins can sanity-check what's wired up to the running server.\n */\nexport const GET_INFRASTRUCTURE_STATUS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/builder/infrastructure',\n responseType: 'json',\n responseSchema: infrastructureStatusResponseSchema,\n summary: 'Get infrastructure status',\n description: 'Agent Builder infrastructure configuration and lightweight runtime status.',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'infrastructure:read',\n handler: async ({ mastra }) => {\n try {\n const formatConfigValue = (value: unknown): string => {\n if (value === null || value === undefined) return 'not set';\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return String(value);\n if (Array.isArray(value)) return `${value.length} item${value.length === 1 ? '' : 's'}`;\n return value.constructor?.name && value.constructor.name !== 'Object' ? value.constructor.name : 'configured';\n };\n\n const getProviderName = (value: unknown): string | null => {\n if (!value) return null;\n if (typeof value === 'object' && 'provider' in value && typeof value.provider === 'string')\n return value.provider;\n if (typeof value === 'object' && 'constructor' in value) {\n const name = (value as { constructor?: { name?: string } }).constructor?.name;\n return name && name !== 'Object' ? name : 'configured';\n }\n return null;\n };\n\n const getConfigEntries = (config: Record<string, unknown>, omittedKeys: string[] = []) =>\n Object.entries(config)\n .filter(([key, value]) => !omittedKeys.includes(key) && value !== undefined && value !== null)\n .map(([key, value]) => ({ key, value: formatConfigValue(value) }));\n\n // Prefer resolveChannels() so a live channels resolver (e.g. @mastra/connect's\n // channels()) reports connections added after boot; older cores lack the method.\n const mastraWithResolver = mastra as typeof mastra & {\n resolveChannels?: () => Promise<Record<string, ChannelProvider>>;\n };\n const channelProviders =\n typeof mastraWithResolver.resolveChannels === 'function'\n ? await mastraWithResolver.resolveChannels()\n : (mastra.getChannelProviders() ?? {});\n const channels: InfrastructureStatus['channels'] = {\n providers: Object.entries(channelProviders)\n .map(([id, provider]) => {\n const info = provider.getInfo?.();\n const routes = provider.getRoutes?.() ?? [];\n return {\n id: info?.id ?? id,\n name: info?.name ?? id,\n isConfigured: info?.isConfigured ?? false,\n routeCount: routes.length,\n };\n })\n .filter(provider => provider.isConfigured),\n };\n\n const editor = mastra.getEditor();\n let browser: InfrastructureStatus['browser'] = {\n type: null,\n provider: null,\n env: null,\n registered: false,\n availableProviders: [],\n config: [],\n };\n let workspace: InfrastructureStatus['workspace'] = {\n type: null,\n workspaceId: null,\n name: null,\n source: null,\n registered: false,\n hasFilesystem: false,\n hasSandbox: false,\n filesystemProvider: null,\n sandboxProvider: null,\n config: [],\n };\n let registries: InfrastructureStatus['registries'] = {\n skillsSh: { enabled: false },\n };\n\n if (editor?.resolveBuilder) {\n const browsers = (editor as unknown as { __browsers?: Map<string, unknown> }).__browsers;\n const builder = await editor.resolveBuilder();\n const builderRegistries = builder?.getRegistries?.();\n registries = {\n skillsSh: { enabled: builderRegistries?.skillsSh?.enabled === true },\n };\n const configuration = builder?.getConfiguration?.()?.agent as\n | {\n browser?: { type?: string; config?: { provider?: string; env?: string } };\n workspace?: {\n type?: string;\n workspaceId?: string;\n config?: { name?: string; filesystem?: unknown; sandbox?: unknown };\n };\n }\n | undefined;\n\n const browserRef = configuration?.browser;\n const browserConfig = browserRef?.config ?? {};\n const providerId = browserConfig.provider ?? null;\n browser = {\n type: browserRef?.type ?? null,\n provider: providerId,\n env: browserConfig.env ?? null,\n registered: providerId ? !!browsers?.has(providerId) : false,\n availableProviders: browsers ? Array.from(browsers.keys()) : [],\n config: getConfigEntries(browserConfig, ['provider', 'env']),\n };\n\n const workspaceRef = configuration?.workspace;\n const workspaceConfig = workspaceRef?.config ?? {};\n const registeredWorkspaces = mastra.listWorkspaces();\n const registeredWorkspace = workspaceRef?.workspaceId\n ? registeredWorkspaces[workspaceRef.workspaceId]\n : undefined;\n const filesystem = registeredWorkspace?.workspace.filesystem ?? workspaceConfig.filesystem;\n const sandbox = registeredWorkspace?.workspace.sandbox ?? workspaceConfig.sandbox;\n const filesystemConfig =\n typeof workspaceConfig.filesystem === 'object' &&\n workspaceConfig.filesystem &&\n 'config' in workspaceConfig.filesystem\n ? (workspaceConfig.filesystem.config as Record<string, unknown>)\n : {};\n const sandboxConfig =\n typeof workspaceConfig.sandbox === 'object' && workspaceConfig.sandbox && 'config' in workspaceConfig.sandbox\n ? (workspaceConfig.sandbox.config as Record<string, unknown>)\n : {};\n workspace = {\n type: workspaceRef?.type ?? null,\n workspaceId: workspaceRef?.workspaceId ?? null,\n name: workspaceConfig.name ?? registeredWorkspace?.workspace.name ?? null,\n source: registeredWorkspace?.source ?? null,\n registered: !!registeredWorkspace,\n hasFilesystem: !!filesystem,\n hasSandbox: !!sandbox,\n filesystemProvider: getProviderName(filesystem),\n sandboxProvider: getProviderName(sandbox),\n config: [\n ...getConfigEntries(filesystemConfig).map(entry => ({ ...entry, key: `filesystem.${entry.key}` })),\n ...getConfigEntries(sandboxConfig).map(entry => ({ ...entry, key: `sandbox.${entry.key}` })),\n ],\n };\n }\n\n return { channels, browser, workspace, registries };\n } catch (error) {\n return handleError(error, 'Error getting infrastructure status');\n }\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,eAAsB,0BAA0B,QAAgE;CAC9G,IAAI,CAAC,QAAQ,OAAO,EAAE,QAAQ,MAAM;CACpC,IAAI,OAAO,OAAO,mBAAmB,YAAY,OAAO,EAAE,QAAQ,MAAM;CACxE,IAAI,OAAO,OAAO,4BAA4B,cAAc,CAAC,OAAO,wBAAwB,GAC1F,OAAO,EAAE,QAAQ,MAAM;CAMzB,IAAI;EACF,MAAM,UAAU,MAAM,OAAO,eAAe;EAC5C,MAAM,EAAE,yBAAyB,MAAM,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CACF;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"editor-builder-CbfX5bvL.js","names":[],"sources":["../src/server/utils/resolve-builder-model-policy.ts","../src/server/handlers/editor-builder.ts"],"sourcesContent":["import type { BuilderModelPolicy } from '@mastra/core/agent-builder/ee';\nimport type { IMastraEditor } from '@mastra/core/editor';\n\n/**\n * Server-side wrapper around `builderToModelPolicy`.\n *\n * Handles the optional `IMastraEditor` builder API surface (older / OSS editors\n * may not implement `hasEnabledBuilderConfig` / `resolveBuilder`) and returns\n * a uniform `BuilderModelPolicy` to every call site.\n *\n * Returns `{ active: false }` whenever:\n * - no editor is configured,\n * - the editor doesn't expose builder methods,\n * - the builder config is disabled, or\n * - resolving the builder fails / yields nothing.\n *\n * The `@mastra/core/agent-builder/ee` subpath is loaded lazily so this module\n * remains importable on `@mastra/core` versions that pre-date the subpath\n * (the subpath was added in core 1.34.0). The dynamic import is only reached\n * once an editor is actually configured, by which point a compatible core is\n * guaranteed.\n */\nexport async function resolveBuilderModelPolicy(editor: IMastraEditor | undefined): Promise<BuilderModelPolicy> {\n if (!editor) return { active: false };\n if (typeof editor.resolveBuilder !== 'function') return { active: false };\n if (typeof editor.hasEnabledBuilderConfig === 'function' && !editor.hasEnabledBuilderConfig()) {\n return { active: false };\n }\n\n // Degrade to inactive on builder-resolution failure rather than letting the\n // rejection escape: agent execution routes seed this on every request, so a\n // transient failure must not 500 the entire route.\n try {\n const builder = await editor.resolveBuilder();\n const { builderToModelPolicy } = await import('@mastra/core/agent-builder/ee');\n return builderToModelPolicy(builder);\n } catch {\n return { active: false };\n }\n}\n","import type { Mastra } from '@mastra/core';\nimport type { ChannelProvider } from '@mastra/core/channels';\n\nimport { HTTPException } from '../http-exception';\nimport {\n agentFeaturesSchema,\n builderAvailableModelsResponseSchema,\n builderSettingsResponseSchema,\n infrastructureStatusResponseSchema,\n} from '../schemas/editor-builder';\nimport type { AgentFeatures, InfrastructureStatus } from '../schemas/editor-builder';\nimport { createRoute } from '../server-adapter/routes/route-builder';\nimport { resolveBuilderModelPolicy } from '../utils/resolve-builder-model-policy';\nimport { buildProvidersList } from './agents';\nimport { handleError } from './error';\n\n/**\n * Resolve the active builder feature flags. Returns `null` when the editor is\n * absent, the builder is disabled, or no features are configured.\n */\nasync function resolveBuilderFeatures(mastra: Mastra): Promise<AgentFeatures | null> {\n const editor = mastra.getEditor();\n if (!editor || typeof editor.resolveBuilder !== 'function') return null;\n if (!editor.hasEnabledBuilderConfig?.()) return null;\n const builder = await editor.resolveBuilder();\n if (!builder || !builder.enabled) return null;\n const features = builder.getFeatures?.()?.agent;\n if (!features) return null;\n // Validate the shape so unknown keys cannot smuggle through.\n const parsed = agentFeaturesSchema.safeParse(features);\n return parsed.success ? parsed.data : null;\n}\n\n/**\n * Returns whether a given agent-builder feature is enabled. Used by list /\n * get-by-id handlers to soft-gate response enrichment (omit fields, ignore\n * favoritedOnly / pinFavoritedFor params) when the feature is off.\n */\nexport async function isBuilderFeatureEnabled(mastra: Mastra, feature: keyof AgentFeatures): Promise<boolean> {\n const features = await resolveBuilderFeatures(mastra);\n return features?.[feature] === true;\n}\n\n/**\n * Hard-gate helper for mutation routes that must not exist when the feature\n * is off. Throws `HTTPException(404)` so we don't leak the existence of the\n * feature surface (matches behavior of unregistered routes).\n */\nexport async function requireBuilderFeature(mastra: Mastra, feature: keyof AgentFeatures): Promise<void> {\n if (!(await isBuilderFeatureEnabled(mastra, feature))) {\n throw new HTTPException(404, { message: 'Not Found' });\n }\n}\n\n/**\n * GET /editor/builder/settings\n *\n * Returns the agent builder settings configured by the admin.\n * Used by frontend to determine which features to display.\n */\nexport const GET_EDITOR_BUILDER_SETTINGS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/builder/settings',\n responseType: 'json',\n responseSchema: builderSettingsResponseSchema,\n summary: 'Get agent builder settings',\n description: 'Returns the agent builder feature flags and configuration for UI gating',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'stored-agents:read',\n handler: async ({ mastra }) => {\n try {\n const editor = mastra.getEditor();\n\n // No editor configured\n if (!editor) {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n // Editor doesn't support builder (older version or OSS)\n if (typeof editor.resolveBuilder !== 'function') {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n // Check if builder is enabled in config\n if (!editor.hasEnabledBuilderConfig?.()) {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n // Resolve the builder instance\n const builder = await editor.resolveBuilder();\n if (!builder || !builder.enabled) {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n const baseWarnings = builder.getModelPolicyWarnings?.() ?? [];\n const configuration = builder.getConfiguration();\n\n // Picker allowlists are written against entity `.id` (what users see in\n // the UI, URLs, traces). The client filters list responses by their\n // response keys, which are not always `.id`:\n // - GET /agents keys by `agent.id`\n // - GET /tools keys by registration key (values include `id`)\n // - GET /workflows keys by registration key (values omit `id`)\n // To keep the client filter simple, we accept `.id` (fallback to\n // registration key) for matching, but emit visible IDs as response keys\n // so `Object.keys(data)` lines up.\n type AliasPair = { id: string; key: string };\n const collectAliases = (registry: Record<string, unknown>): AliasPair[] =>\n Object.entries(registry).map(([key, entity]) => ({\n id: (entity as { id?: string }).id || key,\n key,\n }));\n\n const toolAliases = collectAliases(mastra.listTools() ?? {});\n const agentAliases = collectAliases(mastra.listAgents() ?? {});\n const workflowAliases = collectAliases(mastra.listWorkflows() ?? {});\n\n // Tools/workflows responses are keyed by registration key. Agents\n // response is keyed by `.id`.\n const toResponseKey = (aliases: AliasPair[], byId: 'id' | 'key') => {\n const map = new Map<string, string>();\n for (const a of aliases) {\n map.set(a.id, byId === 'id' ? a.id : a.key);\n map.set(a.key, byId === 'id' ? a.id : a.key);\n }\n return map;\n };\n const toolKeyMap = toResponseKey(toolAliases, 'key');\n const agentKeyMap = toResponseKey(agentAliases, 'id');\n const workflowKeyMap = toResponseKey(workflowAliases, 'key');\n\n // Lazy-load the EE subpath so this module remains importable on\n // `@mastra/core` versions that pre-date it (added in core 1.34.0).\n // We only reach here after `builder.enabled` is true, which guarantees\n // a compatible core.\n const { builderToModelPolicy, resolvePickerVisibility } = await import('@mastra/core/agent-builder/ee');\n\n const picker = resolvePickerVisibility({\n config: configuration?.agent,\n registeredToolIds: toolAliases.flatMap(a => [a.id, a.key]),\n registeredAgentIds: agentAliases.flatMap(a => [a.id, a.key]),\n registeredWorkflowIds: workflowAliases.flatMap(a => [a.id, a.key]),\n });\n\n const normalize = (visible: string[] | null, map: Map<string, string>): string[] | null => {\n if (visible === null) return null;\n const out: string[] = [];\n const seen = new Set<string>();\n for (const id of visible) {\n const mapped = map.get(id);\n if (mapped && !seen.has(mapped)) {\n seen.add(mapped);\n out.push(mapped);\n }\n }\n return out;\n };\n\n const modelPolicyWarnings = [...baseWarnings, ...picker.warnings];\n\n return {\n enabled: true,\n features: builder.getFeatures(),\n configuration,\n modelPolicy: builderToModelPolicy(builder),\n picker: {\n visibleTools: normalize(picker.visibleTools, toolKeyMap),\n visibleAgents: normalize(picker.visibleAgents, agentKeyMap),\n visibleWorkflows: normalize(picker.visibleWorkflows, workflowKeyMap),\n },\n ...(modelPolicyWarnings.length > 0 ? { modelPolicyWarnings } : {}),\n };\n } catch (error) {\n return handleError(error, 'Error getting builder settings');\n }\n },\n});\n\n/**\n * GET /editor/builder/models/available\n *\n * Returns the configured AI providers/models the agent builder may use. The\n * server is the single authority: it scopes the list to providers with a\n * configured API key (`connected`) and applies the active builder model\n * policy via `isModelAllowed`, so the Studio surfaces can render the response\n * verbatim without importing any EE matcher into the browser.\n *\n * - Providers without a configured API key are always omitted — the builder\n * decides the agent's model from this list, so an unconnected provider would\n * produce an agent that can never run.\n * - Policy inactive (or no allowlist) ⇒ all connected providers are returned.\n * - Policy active with an allowlist ⇒ each connected provider's models are\n * filtered, and providers left with no allowed models are omitted entirely.\n */\nexport const GET_EDITOR_BUILDER_AVAILABLE_MODELS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/builder/models/available',\n responseType: 'json',\n responseSchema: builderAvailableModelsResponseSchema,\n summary: 'List builder-available AI models',\n description: 'Returns AI providers/models filtered by the active agent-builder model policy.',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'stored-agents:read',\n handler: async ({ mastra }) => {\n try {\n // Only surface providers whose API key is configured (`connected`). The\n // agent builder decides the agent's model from this list, so including\n // providers without a key lets it pick a model that can never run. We\n // scope to connected providers so every choice is actually usable.\n const providers = (await buildProvidersList(mastra)).filter(provider => provider.connected);\n const policy = await resolveBuilderModelPolicy(mastra.getEditor());\n\n // Inactive policy (or no allowlist) ⇒ no allowlist filtering to apply.\n if (!policy.active || !policy.allowed || policy.allowed.length === 0) {\n return { providers };\n }\n\n // Lazy-load the EE matcher (server-only); mirrors the convention used by\n // resolve-builder-model-policy and the settings handler.\n const { isModelAllowed } = await import('@mastra/core/agent-builder/ee');\n\n const filtered = providers\n .map(provider => ({\n ...provider,\n models: provider.models.filter(modelId => isModelAllowed(policy.allowed, { provider: provider.id, modelId })),\n }))\n .filter(provider => provider.models.length > 0);\n\n return { providers: filtered };\n } catch (error) {\n return handleError(error, 'Error fetching available models');\n }\n },\n});\n\n/**\n * GET /editor/builder/infrastructure\n *\n * Returns the runtime status of Mastra-opinionated primitives (channels,\n * browser providers, workspaces). Admin-only; surfaced in Studio Settings so\n * admins can sanity-check what's wired up to the running server.\n */\nexport const GET_INFRASTRUCTURE_STATUS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/builder/infrastructure',\n responseType: 'json',\n responseSchema: infrastructureStatusResponseSchema,\n summary: 'Get infrastructure status',\n description: 'Agent Builder infrastructure configuration and lightweight runtime status.',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'infrastructure:read',\n handler: async ({ mastra }) => {\n try {\n const formatConfigValue = (value: unknown): string => {\n if (value === null || value === undefined) return 'not set';\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return String(value);\n if (Array.isArray(value)) return `${value.length} item${value.length === 1 ? '' : 's'}`;\n return value.constructor?.name && value.constructor.name !== 'Object' ? value.constructor.name : 'configured';\n };\n\n const getProviderName = (value: unknown): string | null => {\n if (!value) return null;\n if (typeof value === 'object' && 'provider' in value && typeof value.provider === 'string')\n return value.provider;\n if (typeof value === 'object' && 'constructor' in value) {\n const name = (value as { constructor?: { name?: string } }).constructor?.name;\n return name && name !== 'Object' ? name : 'configured';\n }\n return null;\n };\n\n const getConfigEntries = (config: Record<string, unknown>, omittedKeys: string[] = []) =>\n Object.entries(config)\n .filter(([key, value]) => !omittedKeys.includes(key) && value !== undefined && value !== null)\n .map(([key, value]) => ({ key, value: formatConfigValue(value) }));\n\n // Prefer resolveChannels() so a live channels resolver (e.g. @mastra/connect's\n // channels()) reports connections added after boot; older cores lack the method.\n const mastraWithResolver = mastra as typeof mastra & {\n resolveChannels?: () => Promise<Record<string, ChannelProvider>>;\n };\n const channelProviders =\n typeof mastraWithResolver.resolveChannels === 'function'\n ? await mastraWithResolver.resolveChannels()\n : (mastra.getChannelProviders() ?? {});\n const channels: InfrastructureStatus['channels'] = {\n providers: Object.entries(channelProviders)\n .map(([id, provider]) => {\n const info = provider.getInfo?.();\n const routes = provider.getRoutes?.() ?? [];\n return {\n id: info?.id ?? id,\n name: info?.name ?? id,\n isConfigured: info?.isConfigured ?? false,\n routeCount: routes.length,\n };\n })\n .filter(provider => provider.isConfigured),\n };\n\n const editor = mastra.getEditor();\n let browser: InfrastructureStatus['browser'] = {\n type: null,\n provider: null,\n env: null,\n registered: false,\n availableProviders: [],\n config: [],\n };\n let workspace: InfrastructureStatus['workspace'] = {\n type: null,\n workspaceId: null,\n name: null,\n source: null,\n registered: false,\n hasFilesystem: false,\n hasSandbox: false,\n filesystemProvider: null,\n sandboxProvider: null,\n config: [],\n };\n let registries: InfrastructureStatus['registries'] = {\n skillsSh: { enabled: false },\n };\n\n if (editor?.resolveBuilder) {\n const browsers = (editor as unknown as { __browsers?: Map<string, unknown> }).__browsers;\n const builder = await editor.resolveBuilder();\n const builderRegistries = builder?.getRegistries?.();\n registries = {\n skillsSh: { enabled: builderRegistries?.skillsSh?.enabled === true },\n };\n const configuration = builder?.getConfiguration?.()?.agent as\n | {\n browser?: { type?: string; config?: { provider?: string; env?: string } };\n workspace?: {\n type?: string;\n workspaceId?: string;\n config?: { name?: string; filesystem?: unknown; sandbox?: unknown };\n };\n }\n | undefined;\n\n const browserRef = configuration?.browser;\n const browserConfig = browserRef?.config ?? {};\n const providerId = browserConfig.provider ?? null;\n browser = {\n type: browserRef?.type ?? null,\n provider: providerId,\n env: browserConfig.env ?? null,\n registered: providerId ? !!browsers?.has(providerId) : false,\n availableProviders: browsers ? Array.from(browsers.keys()) : [],\n config: getConfigEntries(browserConfig, ['provider', 'env']),\n };\n\n const workspaceRef = configuration?.workspace;\n const workspaceConfig = workspaceRef?.config ?? {};\n const registeredWorkspaces = mastra.listWorkspaces();\n const registeredWorkspace = workspaceRef?.workspaceId\n ? registeredWorkspaces[workspaceRef.workspaceId]\n : undefined;\n const filesystem = registeredWorkspace?.workspace.filesystem ?? workspaceConfig.filesystem;\n const sandbox = registeredWorkspace?.workspace.sandbox ?? workspaceConfig.sandbox;\n const filesystemConfig =\n typeof workspaceConfig.filesystem === 'object' &&\n workspaceConfig.filesystem &&\n 'config' in workspaceConfig.filesystem\n ? (workspaceConfig.filesystem.config as Record<string, unknown>)\n : {};\n const sandboxConfig =\n typeof workspaceConfig.sandbox === 'object' && workspaceConfig.sandbox && 'config' in workspaceConfig.sandbox\n ? (workspaceConfig.sandbox.config as Record<string, unknown>)\n : {};\n workspace = {\n type: workspaceRef?.type ?? null,\n workspaceId: workspaceRef?.workspaceId ?? null,\n name: workspaceConfig.name ?? registeredWorkspace?.workspace.name ?? null,\n source: registeredWorkspace?.source ?? null,\n registered: !!registeredWorkspace,\n hasFilesystem: !!filesystem,\n hasSandbox: !!sandbox,\n filesystemProvider: getProviderName(filesystem),\n sandboxProvider: getProviderName(sandbox),\n config: [\n ...getConfigEntries(filesystemConfig).map(entry => ({ ...entry, key: `filesystem.${entry.key}` })),\n ...getConfigEntries(sandboxConfig).map(entry => ({ ...entry, key: `sandbox.${entry.key}` })),\n ],\n };\n }\n\n return { channels, browser, workspace, registries };\n } catch (error) {\n return handleError(error, 'Error getting infrastructure status');\n }\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,eAAsB,0BAA0B,QAAgE;CAC9G,IAAI,CAAC,QAAQ,OAAO,EAAE,QAAQ,MAAM;CACpC,IAAI,OAAO,OAAO,mBAAmB,YAAY,OAAO,EAAE,QAAQ,MAAM;CACxE,IAAI,OAAO,OAAO,4BAA4B,cAAc,CAAC,OAAO,wBAAwB,GAC1F,OAAO,EAAE,QAAQ,MAAM;CAMzB,IAAI;EACF,MAAM,UAAU,MAAM,OAAO,eAAe;EAC5C,MAAM,EAAE,yBAAyB,MAAM,OAAO;EAC9C,OAAO,qBAAqB,OAAO;CACrC,QAAQ;EACN,OAAO,EAAE,QAAQ,MAAM;CACzB;AACF;;;;;;ACnBA,eAAe,uBAAuB,QAA+C;CACnF,MAAM,SAAS,OAAO,UAAU;CAChC,IAAI,CAAC,UAAU,OAAO,OAAO,mBAAmB,YAAY,OAAO;CACnE,IAAI,CAAC,OAAO,0BAA0B,GAAG,OAAO;CAChD,MAAM,UAAU,MAAM,OAAO,eAAe;CAC5C,IAAI,CAAC,WAAW,CAAC,QAAQ,SAAS,OAAO;CACzC,MAAM,WAAW,QAAQ,cAAc,CAAC,EAAE;CAC1C,IAAI,CAAC,UAAU,OAAO;CAEtB,MAAM,SAAS,oBAAoB,UAAU,QAAQ;CACrD,OAAO,OAAO,UAAU,OAAO,OAAO;AACxC;;;;;;AAOA,eAAsB,wBAAwB,QAAgB,SAAgD;CAE5G,QAAO,MADgB,uBAAuB,MAAM,EAAA,GAClC,aAAa;AACjC;;;;;;AAOA,eAAsB,sBAAsB,QAAgB,SAA6C;CACvG,IAAI,CAAE,MAAM,wBAAwB,QAAQ,OAAO,GACjD,MAAM,IAAI,cAAc,KAAK,EAAE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QAAQ,qBAAqB,UAAU,QAAQ;KACrE,QAAQ,qBAAqB,UAAU;KACvC,YAAY,CAAC,CAAC;KACd,eAAe,CAAC,CAAC;KACjB,YAAY,CAAC,CAAC;KACd,oBAAoB,gBAAgB,UAAU;KAC9C,iBAAiB,gBAAgB,OAAO;KACxC,QAAQ,CACN,GAAG,iBAAiB,gBAAgB,CAAC,CAAC,KAAI,WAAU;MAAE,GAAG;MAAO,KAAK,cAAc,MAAM;KAAM,EAAE,GACjG,GAAG,iBAAiB,aAAa,CAAC,CAAC,KAAI,WAAU;MAAE,GAAG;MAAO,KAAK,WAAW,MAAM;KAAM,EAAE,CAC7F;IACF;GACF;GAEA,OAAO;IAAE;IAAU;IAAS;IAAW;GAAW;EACpD,SAAS,OAAO;GACd,OAAO,YAAY,OAAO,qCAAqC;EACjE;CACF;AACF,CAAC"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
const require_http_exception = require("./http-exception-Co3MbFUf.cjs");
|
|
2
|
-
const require_route_builder = require("./route-builder-CvARmqnA.cjs");
|
|
3
|
-
const require_server_handlers_error = require("./server/handlers/error.cjs");
|
|
4
|
-
const require_agents = require("./agents-DOHGWXDa.cjs");
|
|
5
2
|
const require_editor_builder = require("./editor-builder-BaI8pttR.cjs");
|
|
3
|
+
const require_route_builder = require("./route-builder-DHqDrSSy.cjs");
|
|
4
|
+
const require_agents = require("./agents-DsfsDhIT.cjs");
|
|
5
|
+
const require_server_handlers_error = require("./server/handlers/error.cjs");
|
|
6
6
|
// src/server/utils/resolve-builder-model-policy.ts
|
|
7
7
|
/**
|
|
8
8
|
* Server-side wrapper around `builderToModelPolicy`.
|
|
@@ -362,4 +362,4 @@ Object.defineProperty(exports, "requireBuilderFeature", {
|
|
|
362
362
|
}
|
|
363
363
|
});
|
|
364
364
|
|
|
365
|
-
//# sourceMappingURL=editor-builder-
|
|
365
|
+
//# sourceMappingURL=editor-builder-CjJlqR9a.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"editor-builder-CKfy5eZY.cjs","names":["agentFeaturesSchema","HTTPException","createRoute","builderSettingsResponseSchema","handleError","builderAvailableModelsResponseSchema","buildProvidersList","infrastructureStatusResponseSchema"],"sources":["../src/server/utils/resolve-builder-model-policy.ts","../src/server/handlers/editor-builder.ts"],"sourcesContent":["import type { BuilderModelPolicy } from '@mastra/core/agent-builder/ee';\nimport type { IMastraEditor } from '@mastra/core/editor';\n\n/**\n * Server-side wrapper around `builderToModelPolicy`.\n *\n * Handles the optional `IMastraEditor` builder API surface (older / OSS editors\n * may not implement `hasEnabledBuilderConfig` / `resolveBuilder`) and returns\n * a uniform `BuilderModelPolicy` to every call site.\n *\n * Returns `{ active: false }` whenever:\n * - no editor is configured,\n * - the editor doesn't expose builder methods,\n * - the builder config is disabled, or\n * - resolving the builder fails / yields nothing.\n *\n * The `@mastra/core/agent-builder/ee` subpath is loaded lazily so this module\n * remains importable on `@mastra/core` versions that pre-date the subpath\n * (the subpath was added in core 1.34.0). The dynamic import is only reached\n * once an editor is actually configured, by which point a compatible core is\n * guaranteed.\n */\nexport async function resolveBuilderModelPolicy(editor: IMastraEditor | undefined): Promise<BuilderModelPolicy> {\n if (!editor) return { active: false };\n if (typeof editor.resolveBuilder !== 'function') return { active: false };\n if (typeof editor.hasEnabledBuilderConfig === 'function' && !editor.hasEnabledBuilderConfig()) {\n return { active: false };\n }\n\n // Degrade to inactive on builder-resolution failure rather than letting the\n // rejection escape: agent execution routes seed this on every request, so a\n // transient failure must not 500 the entire route.\n try {\n const builder = await editor.resolveBuilder();\n const { builderToModelPolicy } = await import('@mastra/core/agent-builder/ee');\n return builderToModelPolicy(builder);\n } catch {\n return { active: false };\n }\n}\n","import type { Mastra } from '@mastra/core';\nimport type { ChannelProvider } from '@mastra/core/channels';\n\nimport { HTTPException } from '../http-exception';\nimport {\n agentFeaturesSchema,\n builderAvailableModelsResponseSchema,\n builderSettingsResponseSchema,\n infrastructureStatusResponseSchema,\n} from '../schemas/editor-builder';\nimport type { AgentFeatures, InfrastructureStatus } from '../schemas/editor-builder';\nimport { createRoute } from '../server-adapter/routes/route-builder';\nimport { resolveBuilderModelPolicy } from '../utils/resolve-builder-model-policy';\nimport { buildProvidersList } from './agents';\nimport { handleError } from './error';\n\n/**\n * Resolve the active builder feature flags. Returns `null` when the editor is\n * absent, the builder is disabled, or no features are configured.\n */\nasync function resolveBuilderFeatures(mastra: Mastra): Promise<AgentFeatures | null> {\n const editor = mastra.getEditor();\n if (!editor || typeof editor.resolveBuilder !== 'function') return null;\n if (!editor.hasEnabledBuilderConfig?.()) return null;\n const builder = await editor.resolveBuilder();\n if (!builder || !builder.enabled) return null;\n const features = builder.getFeatures?.()?.agent;\n if (!features) return null;\n // Validate the shape so unknown keys cannot smuggle through.\n const parsed = agentFeaturesSchema.safeParse(features);\n return parsed.success ? parsed.data : null;\n}\n\n/**\n * Returns whether a given agent-builder feature is enabled. Used by list /\n * get-by-id handlers to soft-gate response enrichment (omit fields, ignore\n * favoritedOnly / pinFavoritedFor params) when the feature is off.\n */\nexport async function isBuilderFeatureEnabled(mastra: Mastra, feature: keyof AgentFeatures): Promise<boolean> {\n const features = await resolveBuilderFeatures(mastra);\n return features?.[feature] === true;\n}\n\n/**\n * Hard-gate helper for mutation routes that must not exist when the feature\n * is off. Throws `HTTPException(404)` so we don't leak the existence of the\n * feature surface (matches behavior of unregistered routes).\n */\nexport async function requireBuilderFeature(mastra: Mastra, feature: keyof AgentFeatures): Promise<void> {\n if (!(await isBuilderFeatureEnabled(mastra, feature))) {\n throw new HTTPException(404, { message: 'Not Found' });\n }\n}\n\n/**\n * GET /editor/builder/settings\n *\n * Returns the agent builder settings configured by the admin.\n * Used by frontend to determine which features to display.\n */\nexport const GET_EDITOR_BUILDER_SETTINGS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/builder/settings',\n responseType: 'json',\n responseSchema: builderSettingsResponseSchema,\n summary: 'Get agent builder settings',\n description: 'Returns the agent builder feature flags and configuration for UI gating',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'stored-agents:read',\n handler: async ({ mastra }) => {\n try {\n const editor = mastra.getEditor();\n\n // No editor configured\n if (!editor) {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n // Editor doesn't support builder (older version or OSS)\n if (typeof editor.resolveBuilder !== 'function') {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n // Check if builder is enabled in config\n if (!editor.hasEnabledBuilderConfig?.()) {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n // Resolve the builder instance\n const builder = await editor.resolveBuilder();\n if (!builder || !builder.enabled) {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n const baseWarnings = builder.getModelPolicyWarnings?.() ?? [];\n const configuration = builder.getConfiguration();\n\n // Picker allowlists are written against entity `.id` (what users see in\n // the UI, URLs, traces). The client filters list responses by their\n // response keys, which are not always `.id`:\n // - GET /agents keys by `agent.id`\n // - GET /tools keys by registration key (values include `id`)\n // - GET /workflows keys by registration key (values omit `id`)\n // To keep the client filter simple, we accept `.id` (fallback to\n // registration key) for matching, but emit visible IDs as response keys\n // so `Object.keys(data)` lines up.\n type AliasPair = { id: string; key: string };\n const collectAliases = (registry: Record<string, unknown>): AliasPair[] =>\n Object.entries(registry).map(([key, entity]) => ({\n id: (entity as { id?: string }).id || key,\n key,\n }));\n\n const toolAliases = collectAliases(mastra.listTools() ?? {});\n const agentAliases = collectAliases(mastra.listAgents() ?? {});\n const workflowAliases = collectAliases(mastra.listWorkflows() ?? {});\n\n // Tools/workflows responses are keyed by registration key. Agents\n // response is keyed by `.id`.\n const toResponseKey = (aliases: AliasPair[], byId: 'id' | 'key') => {\n const map = new Map<string, string>();\n for (const a of aliases) {\n map.set(a.id, byId === 'id' ? a.id : a.key);\n map.set(a.key, byId === 'id' ? a.id : a.key);\n }\n return map;\n };\n const toolKeyMap = toResponseKey(toolAliases, 'key');\n const agentKeyMap = toResponseKey(agentAliases, 'id');\n const workflowKeyMap = toResponseKey(workflowAliases, 'key');\n\n // Lazy-load the EE subpath so this module remains importable on\n // `@mastra/core` versions that pre-date it (added in core 1.34.0).\n // We only reach here after `builder.enabled` is true, which guarantees\n // a compatible core.\n const { builderToModelPolicy, resolvePickerVisibility } = await import('@mastra/core/agent-builder/ee');\n\n const picker = resolvePickerVisibility({\n config: configuration?.agent,\n registeredToolIds: toolAliases.flatMap(a => [a.id, a.key]),\n registeredAgentIds: agentAliases.flatMap(a => [a.id, a.key]),\n registeredWorkflowIds: workflowAliases.flatMap(a => [a.id, a.key]),\n });\n\n const normalize = (visible: string[] | null, map: Map<string, string>): string[] | null => {\n if (visible === null) return null;\n const out: string[] = [];\n const seen = new Set<string>();\n for (const id of visible) {\n const mapped = map.get(id);\n if (mapped && !seen.has(mapped)) {\n seen.add(mapped);\n out.push(mapped);\n }\n }\n return out;\n };\n\n const modelPolicyWarnings = [...baseWarnings, ...picker.warnings];\n\n return {\n enabled: true,\n features: builder.getFeatures(),\n configuration,\n modelPolicy: builderToModelPolicy(builder),\n picker: {\n visibleTools: normalize(picker.visibleTools, toolKeyMap),\n visibleAgents: normalize(picker.visibleAgents, agentKeyMap),\n visibleWorkflows: normalize(picker.visibleWorkflows, workflowKeyMap),\n },\n ...(modelPolicyWarnings.length > 0 ? { modelPolicyWarnings } : {}),\n };\n } catch (error) {\n return handleError(error, 'Error getting builder settings');\n }\n },\n});\n\n/**\n * GET /editor/builder/models/available\n *\n * Returns the configured AI providers/models the agent builder may use. The\n * server is the single authority: it scopes the list to providers with a\n * configured API key (`connected`) and applies the active builder model\n * policy via `isModelAllowed`, so the Studio surfaces can render the response\n * verbatim without importing any EE matcher into the browser.\n *\n * - Providers without a configured API key are always omitted — the builder\n * decides the agent's model from this list, so an unconnected provider would\n * produce an agent that can never run.\n * - Policy inactive (or no allowlist) ⇒ all connected providers are returned.\n * - Policy active with an allowlist ⇒ each connected provider's models are\n * filtered, and providers left with no allowed models are omitted entirely.\n */\nexport const GET_EDITOR_BUILDER_AVAILABLE_MODELS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/builder/models/available',\n responseType: 'json',\n responseSchema: builderAvailableModelsResponseSchema,\n summary: 'List builder-available AI models',\n description: 'Returns AI providers/models filtered by the active agent-builder model policy.',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'stored-agents:read',\n handler: async ({ mastra }) => {\n try {\n // Only surface providers whose API key is configured (`connected`). The\n // agent builder decides the agent's model from this list, so including\n // providers without a key lets it pick a model that can never run. We\n // scope to connected providers so every choice is actually usable.\n const providers = (await buildProvidersList(mastra)).filter(provider => provider.connected);\n const policy = await resolveBuilderModelPolicy(mastra.getEditor());\n\n // Inactive policy (or no allowlist) ⇒ no allowlist filtering to apply.\n if (!policy.active || !policy.allowed || policy.allowed.length === 0) {\n return { providers };\n }\n\n // Lazy-load the EE matcher (server-only); mirrors the convention used by\n // resolve-builder-model-policy and the settings handler.\n const { isModelAllowed } = await import('@mastra/core/agent-builder/ee');\n\n const filtered = providers\n .map(provider => ({\n ...provider,\n models: provider.models.filter(modelId => isModelAllowed(policy.allowed, { provider: provider.id, modelId })),\n }))\n .filter(provider => provider.models.length > 0);\n\n return { providers: filtered };\n } catch (error) {\n return handleError(error, 'Error fetching available models');\n }\n },\n});\n\n/**\n * GET /editor/builder/infrastructure\n *\n * Returns the runtime status of Mastra-opinionated primitives (channels,\n * browser providers, workspaces). Admin-only; surfaced in Studio Settings so\n * admins can sanity-check what's wired up to the running server.\n */\nexport const GET_INFRASTRUCTURE_STATUS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/builder/infrastructure',\n responseType: 'json',\n responseSchema: infrastructureStatusResponseSchema,\n summary: 'Get infrastructure status',\n description: 'Agent Builder infrastructure configuration and lightweight runtime status.',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'infrastructure:read',\n handler: async ({ mastra }) => {\n try {\n const formatConfigValue = (value: unknown): string => {\n if (value === null || value === undefined) return 'not set';\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return String(value);\n if (Array.isArray(value)) return `${value.length} item${value.length === 1 ? '' : 's'}`;\n return value.constructor?.name && value.constructor.name !== 'Object' ? value.constructor.name : 'configured';\n };\n\n const getProviderName = (value: unknown): string | null => {\n if (!value) return null;\n if (typeof value === 'object' && 'provider' in value && typeof value.provider === 'string')\n return value.provider;\n if (typeof value === 'object' && 'constructor' in value) {\n const name = (value as { constructor?: { name?: string } }).constructor?.name;\n return name && name !== 'Object' ? name : 'configured';\n }\n return null;\n };\n\n const getConfigEntries = (config: Record<string, unknown>, omittedKeys: string[] = []) =>\n Object.entries(config)\n .filter(([key, value]) => !omittedKeys.includes(key) && value !== undefined && value !== null)\n .map(([key, value]) => ({ key, value: formatConfigValue(value) }));\n\n // Prefer resolveChannels() so a live channels resolver (e.g. @mastra/connect's\n // channels()) reports connections added after boot; older cores lack the method.\n const mastraWithResolver = mastra as typeof mastra & {\n resolveChannels?: () => Promise<Record<string, ChannelProvider>>;\n };\n const channelProviders =\n typeof mastraWithResolver.resolveChannels === 'function'\n ? await mastraWithResolver.resolveChannels()\n : (mastra.getChannelProviders() ?? {});\n const channels: InfrastructureStatus['channels'] = {\n providers: Object.entries(channelProviders)\n .map(([id, provider]) => {\n const info = provider.getInfo?.();\n const routes = provider.getRoutes?.() ?? [];\n return {\n id: info?.id ?? id,\n name: info?.name ?? id,\n isConfigured: info?.isConfigured ?? false,\n routeCount: routes.length,\n };\n })\n .filter(provider => provider.isConfigured),\n };\n\n const editor = mastra.getEditor();\n let browser: InfrastructureStatus['browser'] = {\n type: null,\n provider: null,\n env: null,\n registered: false,\n availableProviders: [],\n config: [],\n };\n let workspace: InfrastructureStatus['workspace'] = {\n type: null,\n workspaceId: null,\n name: null,\n source: null,\n registered: false,\n hasFilesystem: false,\n hasSandbox: false,\n filesystemProvider: null,\n sandboxProvider: null,\n config: [],\n };\n let registries: InfrastructureStatus['registries'] = {\n skillsSh: { enabled: false },\n };\n\n if (editor?.resolveBuilder) {\n const browsers = (editor as unknown as { __browsers?: Map<string, unknown> }).__browsers;\n const builder = await editor.resolveBuilder();\n const builderRegistries = builder?.getRegistries?.();\n registries = {\n skillsSh: { enabled: builderRegistries?.skillsSh?.enabled === true },\n };\n const configuration = builder?.getConfiguration?.()?.agent as\n | {\n browser?: { type?: string; config?: { provider?: string; env?: string } };\n workspace?: {\n type?: string;\n workspaceId?: string;\n config?: { name?: string; filesystem?: unknown; sandbox?: unknown };\n };\n }\n | undefined;\n\n const browserRef = configuration?.browser;\n const browserConfig = browserRef?.config ?? {};\n const providerId = browserConfig.provider ?? null;\n browser = {\n type: browserRef?.type ?? null,\n provider: providerId,\n env: browserConfig.env ?? null,\n registered: providerId ? !!browsers?.has(providerId) : false,\n availableProviders: browsers ? Array.from(browsers.keys()) : [],\n config: getConfigEntries(browserConfig, ['provider', 'env']),\n };\n\n const workspaceRef = configuration?.workspace;\n const workspaceConfig = workspaceRef?.config ?? {};\n const registeredWorkspaces = mastra.listWorkspaces();\n const registeredWorkspace = workspaceRef?.workspaceId\n ? registeredWorkspaces[workspaceRef.workspaceId]\n : undefined;\n const filesystem = registeredWorkspace?.workspace.filesystem ?? workspaceConfig.filesystem;\n const sandbox = registeredWorkspace?.workspace.sandbox ?? workspaceConfig.sandbox;\n const filesystemConfig =\n typeof workspaceConfig.filesystem === 'object' &&\n workspaceConfig.filesystem &&\n 'config' in workspaceConfig.filesystem\n ? (workspaceConfig.filesystem.config as Record<string, unknown>)\n : {};\n const sandboxConfig =\n typeof workspaceConfig.sandbox === 'object' && workspaceConfig.sandbox && 'config' in workspaceConfig.sandbox\n ? (workspaceConfig.sandbox.config as Record<string, unknown>)\n : {};\n workspace = {\n type: workspaceRef?.type ?? null,\n workspaceId: workspaceRef?.workspaceId ?? null,\n name: workspaceConfig.name ?? registeredWorkspace?.workspace.name ?? null,\n source: registeredWorkspace?.source ?? null,\n registered: !!registeredWorkspace,\n hasFilesystem: !!filesystem,\n hasSandbox: !!sandbox,\n filesystemProvider: getProviderName(filesystem),\n sandboxProvider: getProviderName(sandbox),\n config: [\n ...getConfigEntries(filesystemConfig).map(entry => ({ ...entry, key: `filesystem.${entry.key}` })),\n ...getConfigEntries(sandboxConfig).map(entry => ({ ...entry, key: `sandbox.${entry.key}` })),\n ],\n };\n }\n\n return { channels, browser, workspace, registries };\n } catch (error) {\n return handleError(error, 'Error getting infrastructure status');\n }\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,eAAsB,0BAA0B,QAAgE;CAC9G,IAAI,CAAC,QAAQ,OAAO,EAAE,QAAQ,MAAM;CACpC,IAAI,OAAO,OAAO,mBAAmB,YAAY,OAAO,EAAE,QAAQ,MAAM;CACxE,IAAI,OAAO,OAAO,4BAA4B,cAAc,CAAC,OAAO,wBAAwB,GAC1F,OAAO,EAAE,QAAQ,MAAM;CAMzB,IAAI;EACF,MAAM,UAAU,MAAM,OAAO,eAAe;EAC5C,MAAM,EAAE,yBAAyB,MAAM,OAAO;EAC9C,OAAO,qBAAqB,OAAO;CACrC,QAAQ;EACN,OAAO,EAAE,QAAQ,MAAM;CACzB;AACF;;;;;;ACnBA,eAAe,uBAAuB,QAA+C;CACnF,MAAM,SAAS,OAAO,UAAU;CAChC,IAAI,CAAC,UAAU,OAAO,OAAO,mBAAmB,YAAY,OAAO;CACnE,IAAI,CAAC,OAAO,0BAA0B,GAAG,OAAO;CAChD,MAAM,UAAU,MAAM,OAAO,eAAe;CAC5C,IAAI,CAAC,WAAW,CAAC,QAAQ,SAAS,OAAO;CACzC,MAAM,WAAW,QAAQ,cAAc,CAAC,EAAE;CAC1C,IAAI,CAAC,UAAU,OAAO;CAEtB,MAAM,SAASA,uBAAAA,oBAAoB,UAAU,QAAQ;CACrD,OAAO,OAAO,UAAU,OAAO,OAAO;AACxC;;;;;;AAOA,eAAsB,wBAAwB,QAAgB,SAAgD;CAE5G,QAAO,MADgB,uBAAuB,MAAM,EAAA,GAClC,aAAa;AACjC;;;;;;AAOA,eAAsB,sBAAsB,QAAgB,SAA6C;CACv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,OAAO,gBAAgB,YAAY,YAAY,gBAAgB,WAAW,YAAY,gBAAgB,UACjG,gBAAgB,QAAQ,SACzB,CAAC;IACP,YAAY;KACV,MAAM,cAAc,QAAQ;KAC5B,aAAa,cAAc,eAAe;KAC1C,MAAM,gBAAgB,QAAQ,qBAAqB,UAAU,QAAQ;KACrE,QAAQ,qBAAqB,UAAU;KACvC,YAAY,CAAC,CAAC;KACd,eAAe,CAAC,CAAC;KACjB,YAAY,CAAC,CAAC;KACd,oBAAoB,gBAAgB,UAAU;KAC9C,iBAAiB,gBAAgB,OAAO;KACxC,QAAQ,CACN,GAAG,iBAAiB,gBAAgB,CAAC,CAAC,KAAI,WAAU;MAAE,GAAG;MAAO,KAAK,cAAc,MAAM;KAAM,EAAE,GACjG,GAAG,iBAAiB,aAAa,CAAC,CAAC,KAAI,WAAU;MAAE,GAAG;MAAO,KAAK,WAAW,MAAM;KAAM,EAAE,CAC7F;IACF;GACF;GAEA,OAAO;IAAE;IAAU;IAAS;IAAW;GAAW;EACpD,SAAS,OAAO;GACd,OAAOH,8BAAAA,YAAY,OAAO,qCAAqC;EACjE;CACF;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"editor-builder-CjJlqR9a.cjs","names":["agentFeaturesSchema","HTTPException","createRoute","builderSettingsResponseSchema","handleError","builderAvailableModelsResponseSchema","buildProvidersList","infrastructureStatusResponseSchema"],"sources":["../src/server/utils/resolve-builder-model-policy.ts","../src/server/handlers/editor-builder.ts"],"sourcesContent":["import type { BuilderModelPolicy } from '@mastra/core/agent-builder/ee';\nimport type { IMastraEditor } from '@mastra/core/editor';\n\n/**\n * Server-side wrapper around `builderToModelPolicy`.\n *\n * Handles the optional `IMastraEditor` builder API surface (older / OSS editors\n * may not implement `hasEnabledBuilderConfig` / `resolveBuilder`) and returns\n * a uniform `BuilderModelPolicy` to every call site.\n *\n * Returns `{ active: false }` whenever:\n * - no editor is configured,\n * - the editor doesn't expose builder methods,\n * - the builder config is disabled, or\n * - resolving the builder fails / yields nothing.\n *\n * The `@mastra/core/agent-builder/ee` subpath is loaded lazily so this module\n * remains importable on `@mastra/core` versions that pre-date the subpath\n * (the subpath was added in core 1.34.0). The dynamic import is only reached\n * once an editor is actually configured, by which point a compatible core is\n * guaranteed.\n */\nexport async function resolveBuilderModelPolicy(editor: IMastraEditor | undefined): Promise<BuilderModelPolicy> {\n if (!editor) return { active: false };\n if (typeof editor.resolveBuilder !== 'function') return { active: false };\n if (typeof editor.hasEnabledBuilderConfig === 'function' && !editor.hasEnabledBuilderConfig()) {\n return { active: false };\n }\n\n // Degrade to inactive on builder-resolution failure rather than letting the\n // rejection escape: agent execution routes seed this on every request, so a\n // transient failure must not 500 the entire route.\n try {\n const builder = await editor.resolveBuilder();\n const { builderToModelPolicy } = await import('@mastra/core/agent-builder/ee');\n return builderToModelPolicy(builder);\n } catch {\n return { active: false };\n }\n}\n","import type { Mastra } from '@mastra/core';\nimport type { ChannelProvider } from '@mastra/core/channels';\n\nimport { HTTPException } from '../http-exception';\nimport {\n agentFeaturesSchema,\n builderAvailableModelsResponseSchema,\n builderSettingsResponseSchema,\n infrastructureStatusResponseSchema,\n} from '../schemas/editor-builder';\nimport type { AgentFeatures, InfrastructureStatus } from '../schemas/editor-builder';\nimport { createRoute } from '../server-adapter/routes/route-builder';\nimport { resolveBuilderModelPolicy } from '../utils/resolve-builder-model-policy';\nimport { buildProvidersList } from './agents';\nimport { handleError } from './error';\n\n/**\n * Resolve the active builder feature flags. Returns `null` when the editor is\n * absent, the builder is disabled, or no features are configured.\n */\nasync function resolveBuilderFeatures(mastra: Mastra): Promise<AgentFeatures | null> {\n const editor = mastra.getEditor();\n if (!editor || typeof editor.resolveBuilder !== 'function') return null;\n if (!editor.hasEnabledBuilderConfig?.()) return null;\n const builder = await editor.resolveBuilder();\n if (!builder || !builder.enabled) return null;\n const features = builder.getFeatures?.()?.agent;\n if (!features) return null;\n // Validate the shape so unknown keys cannot smuggle through.\n const parsed = agentFeaturesSchema.safeParse(features);\n return parsed.success ? parsed.data : null;\n}\n\n/**\n * Returns whether a given agent-builder feature is enabled. Used by list /\n * get-by-id handlers to soft-gate response enrichment (omit fields, ignore\n * favoritedOnly / pinFavoritedFor params) when the feature is off.\n */\nexport async function isBuilderFeatureEnabled(mastra: Mastra, feature: keyof AgentFeatures): Promise<boolean> {\n const features = await resolveBuilderFeatures(mastra);\n return features?.[feature] === true;\n}\n\n/**\n * Hard-gate helper for mutation routes that must not exist when the feature\n * is off. Throws `HTTPException(404)` so we don't leak the existence of the\n * feature surface (matches behavior of unregistered routes).\n */\nexport async function requireBuilderFeature(mastra: Mastra, feature: keyof AgentFeatures): Promise<void> {\n if (!(await isBuilderFeatureEnabled(mastra, feature))) {\n throw new HTTPException(404, { message: 'Not Found' });\n }\n}\n\n/**\n * GET /editor/builder/settings\n *\n * Returns the agent builder settings configured by the admin.\n * Used by frontend to determine which features to display.\n */\nexport const GET_EDITOR_BUILDER_SETTINGS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/builder/settings',\n responseType: 'json',\n responseSchema: builderSettingsResponseSchema,\n summary: 'Get agent builder settings',\n description: 'Returns the agent builder feature flags and configuration for UI gating',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'stored-agents:read',\n handler: async ({ mastra }) => {\n try {\n const editor = mastra.getEditor();\n\n // No editor configured\n if (!editor) {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n // Editor doesn't support builder (older version or OSS)\n if (typeof editor.resolveBuilder !== 'function') {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n // Check if builder is enabled in config\n if (!editor.hasEnabledBuilderConfig?.()) {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n // Resolve the builder instance\n const builder = await editor.resolveBuilder();\n if (!builder || !builder.enabled) {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n const baseWarnings = builder.getModelPolicyWarnings?.() ?? [];\n const configuration = builder.getConfiguration();\n\n // Picker allowlists are written against entity `.id` (what users see in\n // the UI, URLs, traces). The client filters list responses by their\n // response keys, which are not always `.id`:\n // - GET /agents keys by `agent.id`\n // - GET /tools keys by registration key (values include `id`)\n // - GET /workflows keys by registration key (values omit `id`)\n // To keep the client filter simple, we accept `.id` (fallback to\n // registration key) for matching, but emit visible IDs as response keys\n // so `Object.keys(data)` lines up.\n type AliasPair = { id: string; key: string };\n const collectAliases = (registry: Record<string, unknown>): AliasPair[] =>\n Object.entries(registry).map(([key, entity]) => ({\n id: (entity as { id?: string }).id || key,\n key,\n }));\n\n const toolAliases = collectAliases(mastra.listTools() ?? {});\n const agentAliases = collectAliases(mastra.listAgents() ?? {});\n const workflowAliases = collectAliases(mastra.listWorkflows() ?? {});\n\n // Tools/workflows responses are keyed by registration key. Agents\n // response is keyed by `.id`.\n const toResponseKey = (aliases: AliasPair[], byId: 'id' | 'key') => {\n const map = new Map<string, string>();\n for (const a of aliases) {\n map.set(a.id, byId === 'id' ? a.id : a.key);\n map.set(a.key, byId === 'id' ? a.id : a.key);\n }\n return map;\n };\n const toolKeyMap = toResponseKey(toolAliases, 'key');\n const agentKeyMap = toResponseKey(agentAliases, 'id');\n const workflowKeyMap = toResponseKey(workflowAliases, 'key');\n\n // Lazy-load the EE subpath so this module remains importable on\n // `@mastra/core` versions that pre-date it (added in core 1.34.0).\n // We only reach here after `builder.enabled` is true, which guarantees\n // a compatible core.\n const { builderToModelPolicy, resolvePickerVisibility } = await import('@mastra/core/agent-builder/ee');\n\n const picker = resolvePickerVisibility({\n config: configuration?.agent,\n registeredToolIds: toolAliases.flatMap(a => [a.id, a.key]),\n registeredAgentIds: agentAliases.flatMap(a => [a.id, a.key]),\n registeredWorkflowIds: workflowAliases.flatMap(a => [a.id, a.key]),\n });\n\n const normalize = (visible: string[] | null, map: Map<string, string>): string[] | null => {\n if (visible === null) return null;\n const out: string[] = [];\n const seen = new Set<string>();\n for (const id of visible) {\n const mapped = map.get(id);\n if (mapped && !seen.has(mapped)) {\n seen.add(mapped);\n out.push(mapped);\n }\n }\n return out;\n };\n\n const modelPolicyWarnings = [...baseWarnings, ...picker.warnings];\n\n return {\n enabled: true,\n features: builder.getFeatures(),\n configuration,\n modelPolicy: builderToModelPolicy(builder),\n picker: {\n visibleTools: normalize(picker.visibleTools, toolKeyMap),\n visibleAgents: normalize(picker.visibleAgents, agentKeyMap),\n visibleWorkflows: normalize(picker.visibleWorkflows, workflowKeyMap),\n },\n ...(modelPolicyWarnings.length > 0 ? { modelPolicyWarnings } : {}),\n };\n } catch (error) {\n return handleError(error, 'Error getting builder settings');\n }\n },\n});\n\n/**\n * GET /editor/builder/models/available\n *\n * Returns the configured AI providers/models the agent builder may use. The\n * server is the single authority: it scopes the list to providers with a\n * configured API key (`connected`) and applies the active builder model\n * policy via `isModelAllowed`, so the Studio surfaces can render the response\n * verbatim without importing any EE matcher into the browser.\n *\n * - Providers without a configured API key are always omitted — the builder\n * decides the agent's model from this list, so an unconnected provider would\n * produce an agent that can never run.\n * - Policy inactive (or no allowlist) ⇒ all connected providers are returned.\n * - Policy active with an allowlist ⇒ each connected provider's models are\n * filtered, and providers left with no allowed models are omitted entirely.\n */\nexport const GET_EDITOR_BUILDER_AVAILABLE_MODELS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/builder/models/available',\n responseType: 'json',\n responseSchema: builderAvailableModelsResponseSchema,\n summary: 'List builder-available AI models',\n description: 'Returns AI providers/models filtered by the active agent-builder model policy.',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'stored-agents:read',\n handler: async ({ mastra }) => {\n try {\n // Only surface providers whose API key is configured (`connected`). The\n // agent builder decides the agent's model from this list, so including\n // providers without a key lets it pick a model that can never run. We\n // scope to connected providers so every choice is actually usable.\n const providers = (await buildProvidersList(mastra)).filter(provider => provider.connected);\n const policy = await resolveBuilderModelPolicy(mastra.getEditor());\n\n // Inactive policy (or no allowlist) ⇒ no allowlist filtering to apply.\n if (!policy.active || !policy.allowed || policy.allowed.length === 0) {\n return { providers };\n }\n\n // Lazy-load the EE matcher (server-only); mirrors the convention used by\n // resolve-builder-model-policy and the settings handler.\n const { isModelAllowed } = await import('@mastra/core/agent-builder/ee');\n\n const filtered = providers\n .map(provider => ({\n ...provider,\n models: provider.models.filter(modelId => isModelAllowed(policy.allowed, { provider: provider.id, modelId })),\n }))\n .filter(provider => provider.models.length > 0);\n\n return { providers: filtered };\n } catch (error) {\n return handleError(error, 'Error fetching available models');\n }\n },\n});\n\n/**\n * GET /editor/builder/infrastructure\n *\n * Returns the runtime status of Mastra-opinionated primitives (channels,\n * browser providers, workspaces). Admin-only; surfaced in Studio Settings so\n * admins can sanity-check what's wired up to the running server.\n */\nexport const GET_INFRASTRUCTURE_STATUS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/builder/infrastructure',\n responseType: 'json',\n responseSchema: infrastructureStatusResponseSchema,\n summary: 'Get infrastructure status',\n description: 'Agent Builder infrastructure configuration and lightweight runtime status.',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'infrastructure:read',\n handler: async ({ mastra }) => {\n try {\n const formatConfigValue = (value: unknown): string => {\n if (value === null || value === undefined) return 'not set';\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return String(value);\n if (Array.isArray(value)) return `${value.length} item${value.length === 1 ? '' : 's'}`;\n return value.constructor?.name && value.constructor.name !== 'Object' ? value.constructor.name : 'configured';\n };\n\n const getProviderName = (value: unknown): string | null => {\n if (!value) return null;\n if (typeof value === 'object' && 'provider' in value && typeof value.provider === 'string')\n return value.provider;\n if (typeof value === 'object' && 'constructor' in value) {\n const name = (value as { constructor?: { name?: string } }).constructor?.name;\n return name && name !== 'Object' ? name : 'configured';\n }\n return null;\n };\n\n const getConfigEntries = (config: Record<string, unknown>, omittedKeys: string[] = []) =>\n Object.entries(config)\n .filter(([key, value]) => !omittedKeys.includes(key) && value !== undefined && value !== null)\n .map(([key, value]) => ({ key, value: formatConfigValue(value) }));\n\n // Prefer resolveChannels() so a live channels resolver (e.g. @mastra/connect's\n // channels()) reports connections added after boot; older cores lack the method.\n const mastraWithResolver = mastra as typeof mastra & {\n resolveChannels?: () => Promise<Record<string, ChannelProvider>>;\n };\n const channelProviders =\n typeof mastraWithResolver.resolveChannels === 'function'\n ? await mastraWithResolver.resolveChannels()\n : (mastra.getChannelProviders() ?? {});\n const channels: InfrastructureStatus['channels'] = {\n providers: Object.entries(channelProviders)\n .map(([id, provider]) => {\n const info = provider.getInfo?.();\n const routes = provider.getRoutes?.() ?? [];\n return {\n id: info?.id ?? id,\n name: info?.name ?? id,\n isConfigured: info?.isConfigured ?? false,\n routeCount: routes.length,\n };\n })\n .filter(provider => provider.isConfigured),\n };\n\n const editor = mastra.getEditor();\n let browser: InfrastructureStatus['browser'] = {\n type: null,\n provider: null,\n env: null,\n registered: false,\n availableProviders: [],\n config: [],\n };\n let workspace: InfrastructureStatus['workspace'] = {\n type: null,\n workspaceId: null,\n name: null,\n source: null,\n registered: false,\n hasFilesystem: false,\n hasSandbox: false,\n filesystemProvider: null,\n sandboxProvider: null,\n config: [],\n };\n let registries: InfrastructureStatus['registries'] = {\n skillsSh: { enabled: false },\n };\n\n if (editor?.resolveBuilder) {\n const browsers = (editor as unknown as { __browsers?: Map<string, unknown> }).__browsers;\n const builder = await editor.resolveBuilder();\n const builderRegistries = builder?.getRegistries?.();\n registries = {\n skillsSh: { enabled: builderRegistries?.skillsSh?.enabled === true },\n };\n const configuration = builder?.getConfiguration?.()?.agent as\n | {\n browser?: { type?: string; config?: { provider?: string; env?: string } };\n workspace?: {\n type?: string;\n workspaceId?: string;\n config?: { name?: string; filesystem?: unknown; sandbox?: unknown };\n };\n }\n | undefined;\n\n const browserRef = configuration?.browser;\n const browserConfig = browserRef?.config ?? {};\n const providerId = browserConfig.provider ?? null;\n browser = {\n type: browserRef?.type ?? null,\n provider: providerId,\n env: browserConfig.env ?? null,\n registered: providerId ? !!browsers?.has(providerId) : false,\n availableProviders: browsers ? Array.from(browsers.keys()) : [],\n config: getConfigEntries(browserConfig, ['provider', 'env']),\n };\n\n const workspaceRef = configuration?.workspace;\n const workspaceConfig = workspaceRef?.config ?? {};\n const registeredWorkspaces = mastra.listWorkspaces();\n const registeredWorkspace = workspaceRef?.workspaceId\n ? registeredWorkspaces[workspaceRef.workspaceId]\n : undefined;\n const filesystem = registeredWorkspace?.workspace.filesystem ?? workspaceConfig.filesystem;\n const sandbox = registeredWorkspace?.workspace.sandbox ?? workspaceConfig.sandbox;\n const filesystemConfig =\n typeof workspaceConfig.filesystem === 'object' &&\n workspaceConfig.filesystem &&\n 'config' in workspaceConfig.filesystem\n ? (workspaceConfig.filesystem.config as Record<string, unknown>)\n : {};\n const sandboxConfig =\n typeof workspaceConfig.sandbox === 'object' && workspaceConfig.sandbox && 'config' in workspaceConfig.sandbox\n ? (workspaceConfig.sandbox.config as Record<string, unknown>)\n : {};\n workspace = {\n type: workspaceRef?.type ?? null,\n workspaceId: workspaceRef?.workspaceId ?? null,\n name: workspaceConfig.name ?? registeredWorkspace?.workspace.name ?? null,\n source: registeredWorkspace?.source ?? null,\n registered: !!registeredWorkspace,\n hasFilesystem: !!filesystem,\n hasSandbox: !!sandbox,\n filesystemProvider: getProviderName(filesystem),\n sandboxProvider: getProviderName(sandbox),\n config: [\n ...getConfigEntries(filesystemConfig).map(entry => ({ ...entry, key: `filesystem.${entry.key}` })),\n ...getConfigEntries(sandboxConfig).map(entry => ({ ...entry, key: `sandbox.${entry.key}` })),\n ],\n };\n }\n\n return { channels, browser, workspace, registries };\n } catch (error) {\n return handleError(error, 'Error getting infrastructure status');\n }\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,eAAsB,0BAA0B,QAAgE;CAC9G,IAAI,CAAC,QAAQ,OAAO,EAAE,QAAQ,MAAM;CACpC,IAAI,OAAO,OAAO,mBAAmB,YAAY,OAAO,EAAE,QAAQ,MAAM;CACxE,IAAI,OAAO,OAAO,4BAA4B,cAAc,CAAC,OAAO,wBAAwB,GAC1F,OAAO,EAAE,QAAQ,MAAM;CAMzB,IAAI;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AI,WAAU;MAAE,GAAG;MAAO,KAAK,WAAW,MAAM;KAAM,EAAE,CAC7F;IACF;GACF;GAEA,OAAO;IAAE;IAAU;IAAS;IAAW;GAAW;EACpD,SAAS,OAAO;GACd,OAAOH,8BAAAA,YAAY,OAAO,qCAAqC;EACjE;CACF;AACF,CAAC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as HTTPException } from "./http-exception-CzaWkxMl.js";
|
|
2
1
|
import { d as MASTRA_USER_PERMISSIONS_KEY, f as MASTRA_USER_ROLES_KEY, n as MASTRA_AUTH_TOKEN_KEY, s as MASTRA_RESOURCE_ID_KEY, t as MASTRA_AUTH_MODE_KEY, u as MASTRA_USER_KEY } from "./constants-CXAvBYcz.js";
|
|
2
|
+
import { t as HTTPException } from "./http-exception-CzaWkxMl.js";
|
|
3
3
|
import { CompositeAuth } from "@mastra/core/server";
|
|
4
4
|
// src/server/auth/defaults.ts
|
|
5
5
|
const defaultAuthConfig = {
|
|
@@ -353,33 +353,58 @@ const coreAuthMiddleware = async (ctx) => {
|
|
|
353
353
|
headers: refreshHeaders
|
|
354
354
|
};
|
|
355
355
|
}
|
|
356
|
+
const authorizationError = await authorizeAuthenticatedUser({
|
|
357
|
+
path,
|
|
358
|
+
method,
|
|
359
|
+
user,
|
|
360
|
+
mastra,
|
|
361
|
+
authConfig,
|
|
362
|
+
customRouteAuthConfig,
|
|
363
|
+
requestContext,
|
|
364
|
+
rawRequest,
|
|
365
|
+
buildAuthorizeContext: ctx.buildAuthorizeContext
|
|
366
|
+
});
|
|
367
|
+
if (authorizationError) return {
|
|
368
|
+
action: "error",
|
|
369
|
+
...authorizationError,
|
|
370
|
+
headers: refreshHeaders
|
|
371
|
+
};
|
|
372
|
+
return refreshHeaders ? {
|
|
373
|
+
action: "next",
|
|
374
|
+
headers: refreshHeaders
|
|
375
|
+
} : pass;
|
|
376
|
+
};
|
|
377
|
+
/**
|
|
378
|
+
* The authorization step of server auth for an already authenticated user:
|
|
379
|
+
* `authorizeUser`, `authorize(path, method, user)`, `rules`, or the RBAC default rules.
|
|
380
|
+
* Returns null when the user may access `method path`.
|
|
381
|
+
*/
|
|
382
|
+
const authorizeAuthenticatedUser = async (ctx) => {
|
|
383
|
+
const { path, method, user, mastra, authConfig, requestContext, rawRequest } = ctx;
|
|
384
|
+
const denied = {
|
|
385
|
+
status: 403,
|
|
386
|
+
body: { error: "Access denied" }
|
|
387
|
+
};
|
|
356
388
|
if ("authorizeUser" in authConfig && typeof authConfig.authorizeUser === "function") try {
|
|
357
|
-
|
|
358
|
-
action: "error",
|
|
359
|
-
status: 403,
|
|
360
|
-
body: { error: "Access denied" },
|
|
361
|
-
headers: refreshHeaders
|
|
362
|
-
};
|
|
389
|
+
return await authConfig.authorizeUser(user, adaptToMastraAuthRequest(rawRequest)) ? null : denied;
|
|
363
390
|
} catch (err) {
|
|
364
391
|
mastra.getLogger()?.error("Authorization error in authorizeUser", { error: err instanceof Error ? {
|
|
365
392
|
message: err.message,
|
|
366
393
|
stack: err.stack
|
|
367
394
|
} : err });
|
|
368
395
|
return {
|
|
369
|
-
action: "error",
|
|
370
396
|
status: 500,
|
|
371
|
-
body: { error: "Authorization error" }
|
|
372
|
-
headers: refreshHeaders
|
|
397
|
+
body: { error: "Authorization error" }
|
|
373
398
|
};
|
|
374
399
|
}
|
|
375
|
-
|
|
376
|
-
const authorizeCtx = withAuthorizeVariables(ctx.buildAuthorizeContext(),
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
400
|
+
if ("authorize" in authConfig && typeof authConfig.authorize === "function") try {
|
|
401
|
+
const authorizeCtx = withAuthorizeVariables(ctx.buildAuthorizeContext(), {
|
|
402
|
+
mastra,
|
|
403
|
+
requestContext,
|
|
404
|
+
customRouteAuthConfig: ctx.customRouteAuthConfig,
|
|
405
|
+
rawRequest
|
|
406
|
+
});
|
|
407
|
+
return await authConfig.authorize(path, method, user, authorizeCtx) ? null : denied;
|
|
383
408
|
} catch (err) {
|
|
384
409
|
mastra.getLogger()?.error("Authorization error in authorize", {
|
|
385
410
|
error: err instanceof Error ? {
|
|
@@ -390,38 +415,16 @@ const coreAuthMiddleware = async (ctx) => {
|
|
|
390
415
|
method
|
|
391
416
|
});
|
|
392
417
|
return {
|
|
393
|
-
action: "error",
|
|
394
418
|
status: 500,
|
|
395
|
-
body: { error: "Authorization error" }
|
|
396
|
-
headers: refreshHeaders
|
|
419
|
+
body: { error: "Authorization error" }
|
|
397
420
|
};
|
|
398
421
|
}
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
body: { error: "Access denied" },
|
|
404
|
-
headers: refreshHeaders
|
|
405
|
-
};
|
|
406
|
-
} else if (requestContext.get("mastra__authMode") === "studio" ? mastra.getStudio?.()?.rbac ?? mastra.getServer()?.rbac : mastra.getServer()?.rbac) {
|
|
407
|
-
if (defaultAuthConfig.rules && defaultAuthConfig.rules.length > 0) {
|
|
408
|
-
if (!await checkRules(defaultAuthConfig.rules, path, method, user)) return {
|
|
409
|
-
action: "error",
|
|
410
|
-
status: 403,
|
|
411
|
-
body: { error: "Access denied" },
|
|
412
|
-
headers: refreshHeaders
|
|
413
|
-
};
|
|
414
|
-
} else return {
|
|
415
|
-
action: "error",
|
|
416
|
-
status: 403,
|
|
417
|
-
body: { error: "Access denied" },
|
|
418
|
-
headers: refreshHeaders
|
|
419
|
-
};
|
|
422
|
+
if ("rules" in authConfig && authConfig.rules && authConfig.rules.length > 0) return await checkRules(authConfig.rules, path, method, user) ? null : denied;
|
|
423
|
+
if (requestContext.get("mastra__authMode") === "studio" ? mastra.getStudio?.()?.rbac ?? mastra.getServer()?.rbac : mastra.getServer()?.rbac) {
|
|
424
|
+
if (defaultAuthConfig.rules && defaultAuthConfig.rules.length > 0) return await checkRules(defaultAuthConfig.rules, path, method, user) ? null : denied;
|
|
425
|
+
return denied;
|
|
420
426
|
}
|
|
421
|
-
return
|
|
422
|
-
action: "next",
|
|
423
|
-
headers: refreshHeaders
|
|
424
|
-
} : pass;
|
|
427
|
+
return null;
|
|
425
428
|
};
|
|
426
429
|
const checkRules = async (rules, path, method, user) => {
|
|
427
430
|
for (const i in rules || []) {
|
|
@@ -435,6 +438,6 @@ const checkRules = async (rules, path, method, user) => {
|
|
|
435
438
|
}
|
|
436
439
|
return false;
|
|
437
440
|
};
|
|
438
|
-
export {
|
|
441
|
+
export { findMatchingCustomRoute as a, isDevPlaygroundRequest as c, matchesOrIncludes as d, pathMatchesPattern as f, defaultAuthConfig as h, coreAuthMiddleware as i, isProtectedCustomRoute as l, supportsSessionRefresh as m, canAccessPublicly as n, getAuthenticatedUser as o, pathMatchesRule as p, checkRules as r, isCustomRoutePublic as s, authorizeAuthenticatedUser as t, isProtectedPath as u };
|
|
439
442
|
|
|
440
|
-
//# sourceMappingURL=helpers-
|
|
443
|
+
//# sourceMappingURL=helpers-B29a1nM3.js.map
|