@mastra/server 1.79.0-alpha.2 → 1.79.0-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (262) hide show
  1. package/dist/_types/@internal_voice/dist/_types/zod/v4/core/schemas.d.ts +3 -1
  2. package/dist/_types/@internal_voice/dist/_types/zod/v4/core/util.d.ts +2 -0
  3. package/dist/_types/@mastra_schema-compat/dist/_types/@internal_ai-v6/dist/index.d.ts +95 -1095
  4. package/dist/{a2a-D5CGFO8W.cjs → a2a-BSJETR5U.cjs} +3 -3
  5. package/dist/a2a-BSJETR5U.cjs.map +1 -0
  6. package/dist/{a2a-Dg3ylOKc.js → a2a-hc5lDJCh.js} +3 -3
  7. package/dist/{a2a-D5CGFO8W.cjs.map → a2a-hc5lDJCh.js.map} +1 -1
  8. package/dist/{agents-D9vpLghy.cjs → agents-BgeSrhey.cjs} +2 -1
  9. package/dist/agents-BgeSrhey.cjs.map +1 -0
  10. package/dist/{agents-DNWDET4U.js → agents-wamaX7m2.js} +2 -1
  11. package/dist/agents-wamaX7m2.js.map +1 -0
  12. package/dist/{api-schema-manifest-CI0gyTVi.cjs → api-schema-manifest-BIpRlCSx.cjs} +9 -3
  13. package/dist/api-schema-manifest-BIpRlCSx.cjs.map +1 -0
  14. package/dist/{api-schema-manifest-BgWM-O7K.js → api-schema-manifest-Zr5wt6oZ.js} +9 -3
  15. package/dist/api-schema-manifest-Zr5wt6oZ.js.map +1 -0
  16. package/dist/{background-tasks-BbYzMhlD.cjs → background-tasks-B-OILmJH.cjs} +3 -3
  17. package/dist/{background-tasks-BbYzMhlD.cjs.map → background-tasks-B-OILmJH.cjs.map} +1 -1
  18. package/dist/{background-tasks-zvlIcbhg.js → background-tasks-xOB2d8x6.js} +3 -3
  19. package/dist/{background-tasks-zvlIcbhg.js.map → background-tasks-xOB2d8x6.js.map} +1 -1
  20. package/dist/{builder-registry-1GwmVVwr.js → builder-registry-BvLWRDhU.js} +3 -3
  21. package/dist/{builder-registry-1GwmVVwr.js.map → builder-registry-BvLWRDhU.js.map} +1 -1
  22. package/dist/{builder-registry-DagCZI4A.cjs → builder-registry-DMTPXlGU.cjs} +3 -3
  23. package/dist/{builder-registry-DagCZI4A.cjs.map → builder-registry-DMTPXlGU.cjs.map} +1 -1
  24. package/dist/{channels-5J7CTFyY.cjs → channels-B0IpCxzk.cjs} +2 -2
  25. package/dist/{channels-5J7CTFyY.cjs.map → channels-B0IpCxzk.cjs.map} +1 -1
  26. package/dist/{channels-B3aoI-f1.js → channels-CmWBm-JB.js} +2 -2
  27. package/dist/{channels-B3aoI-f1.js.map → channels-CmWBm-JB.js.map} +1 -1
  28. package/dist/{dist-D5O8s1u2.cjs → dist-3FPW9nVj.cjs} +3 -3
  29. package/dist/{dist-D5O8s1u2.cjs.map → dist-3FPW9nVj.cjs.map} +1 -1
  30. package/dist/{dist-Bw2XgCSY.cjs → dist-B5OwHWTo.cjs} +3 -3
  31. package/dist/{dist-Bw2XgCSY.cjs.map → dist-B5OwHWTo.cjs.map} +1 -1
  32. package/dist/{dist-C5TZXkhS.js → dist-B_bet8uz.js} +2 -2
  33. package/dist/{dist-C5TZXkhS.js.map → dist-B_bet8uz.js.map} +1 -1
  34. package/dist/{dist-CKHUMrWI.cjs → dist-Bi2UyBDO.cjs} +586 -883
  35. package/dist/dist-Bi2UyBDO.cjs.map +1 -0
  36. package/dist/{dist-8fx1_bLF.js → dist-BwYL7Ykb.js} +3 -3
  37. package/dist/{dist-8fx1_bLF.js.map → dist-BwYL7Ykb.js.map} +1 -1
  38. package/dist/{dist-_RnqhYfY.js → dist-BxMmGD3n.js} +3 -3
  39. package/dist/{dist-_RnqhYfY.js.map → dist-BxMmGD3n.js.map} +1 -1
  40. package/dist/{dist-D1oSHJhK.js → dist-CBRJax5e.js} +3 -3
  41. package/dist/{dist-D1oSHJhK.js.map → dist-CBRJax5e.js.map} +1 -1
  42. package/dist/{dist-D5mpJHHH.cjs → dist-CQ3FSKT-.cjs} +3 -3
  43. package/dist/{dist-D5mpJHHH.cjs.map → dist-CQ3FSKT-.cjs.map} +1 -1
  44. package/dist/{dist-hfFDNas-.js → dist-CSVQ5lzr.js} +587 -884
  45. package/dist/dist-CSVQ5lzr.js.map +1 -0
  46. package/dist/{dist-CgemVduI.cjs → dist-DC1Pewf5.cjs} +4 -4
  47. package/dist/{dist-CgemVduI.cjs.map → dist-DC1Pewf5.cjs.map} +1 -1
  48. package/dist/{dist-BCTqy9i3.js → dist-DOWsEmo6.js} +4 -4
  49. package/dist/{dist-BCTqy9i3.js.map → dist-DOWsEmo6.js.map} +1 -1
  50. package/dist/{dist-Bz4l8I_x.js → dist-DcoIg_tp.js} +3 -3
  51. package/dist/{dist-Bz4l8I_x.js.map → dist-DcoIg_tp.js.map} +1 -1
  52. package/dist/{dist-UACuV_1t.cjs → dist-UKEksCGq.cjs} +3 -3
  53. package/dist/{dist-UACuV_1t.cjs.map → dist-UKEksCGq.cjs.map} +1 -1
  54. package/dist/{dist-tYOY8gEs.cjs → dist-rDRetJVY.cjs} +2 -2
  55. package/dist/{dist-tYOY8gEs.cjs.map → dist-rDRetJVY.cjs.map} +1 -1
  56. package/dist/docs/SKILL.md +1 -1
  57. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  58. package/dist/docs/references/reference-observability-tracing-trace-query.md +39 -10
  59. package/dist/{dynamic-workflows-BL3eD0zL.cjs → dynamic-workflows-BVW4SyS5.cjs} +2 -2
  60. package/dist/{dynamic-workflows-BL3eD0zL.cjs.map → dynamic-workflows-BVW4SyS5.cjs.map} +1 -1
  61. package/dist/{dynamic-workflows-BJfoQMo8.js → dynamic-workflows-CE-xM2NQ.js} +2 -2
  62. package/dist/{dynamic-workflows-BJfoQMo8.js.map → dynamic-workflows-CE-xM2NQ.js.map} +1 -1
  63. package/dist/{editor-builder-BOmAPurW.cjs → editor-builder-C2dwLp86.cjs} +3 -3
  64. package/dist/{editor-builder-BOmAPurW.cjs.map → editor-builder-C2dwLp86.cjs.map} +1 -1
  65. package/dist/{editor-builder-DHqCWGd2.js → editor-builder-C5xHbYcZ.js} +2 -2
  66. package/dist/{editor-builder-DHqCWGd2.js.map → editor-builder-C5xHbYcZ.js.map} +1 -1
  67. package/dist/{editor-builder-DqHKoEDx.cjs → editor-builder-CP7URDqM.cjs} +2 -2
  68. package/dist/{editor-builder-DqHKoEDx.cjs.map → editor-builder-CP7URDqM.cjs.map} +1 -1
  69. package/dist/{editor-builder-CeLVu_FT.js → editor-builder-DdZk963o.js} +3 -3
  70. package/dist/{editor-builder-CeLVu_FT.js.map → editor-builder-DdZk963o.js.map} +1 -1
  71. package/dist/{observability-new-endpoints-BKFVVMTS.cjs → observability-new-endpoints-CXbVKROm.cjs} +74 -17
  72. package/dist/observability-new-endpoints-CXbVKROm.cjs.map +1 -0
  73. package/dist/{observability-new-endpoints-C5VO7nLK.js → observability-new-endpoints-JxqtW8f5.js} +75 -18
  74. package/dist/observability-new-endpoints-JxqtW8f5.js.map +1 -0
  75. package/dist/{route-builder-lBil8Cvo.js → route-builder-DzUGCSQT.js} +3 -3
  76. package/dist/{route-builder-lBil8Cvo.js.map → route-builder-DzUGCSQT.js.map} +1 -1
  77. package/dist/{route-builder-2yrD15TL.cjs → route-builder-TBkBU65d.cjs} +3 -3
  78. package/dist/{route-builder-2yrD15TL.cjs.map → route-builder-TBkBU65d.cjs.map} +1 -1
  79. package/dist/{routes-CeX9JLW2.cjs → routes-C5zubsU0.cjs} +11 -11
  80. package/dist/{routes-CeX9JLW2.cjs.map → routes-C5zubsU0.cjs.map} +1 -1
  81. package/dist/{routes-CMj-3iyu.js → routes-DrxGo6Ug.js} +11 -11
  82. package/dist/{routes-CMj-3iyu.js.map → routes-DrxGo6Ug.js.map} +1 -1
  83. package/dist/{schedules-B0g72u5Y.cjs → schedules-55nFQfsJ.cjs} +3 -3
  84. package/dist/{schedules-B0g72u5Y.cjs.map → schedules-55nFQfsJ.cjs.map} +1 -1
  85. package/dist/{schedules-CrAmZ2gu.js → schedules-DxDUE8Fb.js} +3 -3
  86. package/dist/{schedules-CrAmZ2gu.js.map → schedules-DxDUE8Fb.js.map} +1 -1
  87. package/dist/schema-Drf2W04o.js +2 -0
  88. package/dist/schema-EQanefYq.cjs +1 -0
  89. package/dist/{schema-e0VHpMt0-BS9KHnuT.cjs → schema-e0VHpMt0-C0452jOk.cjs} +2 -2
  90. package/dist/{schema-e0VHpMt0-BS9KHnuT.cjs.map → schema-e0VHpMt0-C0452jOk.cjs.map} +1 -1
  91. package/dist/{schema-e0VHpMt0-CvPvLS06.js → schema-e0VHpMt0-CVP5Hnxy.js} +2 -2
  92. package/dist/{schema-e0VHpMt0-CvPvLS06.js.map → schema-e0VHpMt0-CVP5Hnxy.js.map} +1 -1
  93. package/dist/server/a2a/tasks.d.ts +2 -2
  94. package/dist/server/a2a/tasks.d.ts.map +1 -1
  95. package/dist/server/handlers/a2a.cjs +1 -1
  96. package/dist/server/handlers/a2a.d.ts +2 -2
  97. package/dist/server/handlers/a2a.d.ts.map +1 -1
  98. package/dist/server/handlers/a2a.js +1 -1
  99. package/dist/server/handlers/agent-builder.cjs +4 -4
  100. package/dist/server/handlers/agent-builder.js +4 -4
  101. package/dist/server/handlers/agent-controller.cjs +47 -7
  102. package/dist/server/handlers/agent-controller.cjs.map +1 -1
  103. package/dist/server/handlers/agent-controller.d.ts +2 -0
  104. package/dist/server/handlers/agent-controller.d.ts.map +1 -1
  105. package/dist/server/handlers/agent-controller.js +47 -7
  106. package/dist/server/handlers/agent-controller.js.map +1 -1
  107. package/dist/server/handlers/agent-versions.cjs +2 -2
  108. package/dist/server/handlers/agent-versions.js +2 -2
  109. package/dist/server/handlers/agents.cjs +17 -13
  110. package/dist/server/handlers/agents.cjs.map +1 -1
  111. package/dist/server/handlers/agents.d.ts +6 -0
  112. package/dist/server/handlers/agents.d.ts.map +1 -1
  113. package/dist/server/handlers/agents.js +17 -13
  114. package/dist/server/handlers/agents.js.map +1 -1
  115. package/dist/server/handlers/auth.cjs +1 -1
  116. package/dist/server/handlers/auth.js +1 -1
  117. package/dist/server/handlers/background-tasks.cjs +1 -1
  118. package/dist/server/handlers/background-tasks.js +1 -1
  119. package/dist/server/handlers/builder-registry.cjs +1 -1
  120. package/dist/server/handlers/builder-registry.js +1 -1
  121. package/dist/server/handlers/channels.cjs +1 -1
  122. package/dist/server/handlers/channels.js +1 -1
  123. package/dist/server/handlers/conversations.cjs +2 -2
  124. package/dist/server/handlers/conversations.js +2 -2
  125. package/dist/server/handlers/datasets.cjs +1 -1
  126. package/dist/server/handlers/datasets.js +1 -1
  127. package/dist/server/handlers/dynamic-workflows.cjs +1 -1
  128. package/dist/server/handlers/dynamic-workflows.js +1 -1
  129. package/dist/server/handlers/editor-builder.cjs +1 -1
  130. package/dist/server/handlers/editor-builder.js +1 -1
  131. package/dist/server/handlers/error.cjs +7 -5
  132. package/dist/server/handlers/error.cjs.map +1 -1
  133. package/dist/server/handlers/error.d.ts.map +1 -1
  134. package/dist/server/handlers/error.js +7 -5
  135. package/dist/server/handlers/error.js.map +1 -1
  136. package/dist/server/handlers/favorites-enrichment.cjs +1 -1
  137. package/dist/server/handlers/favorites-enrichment.js +1 -1
  138. package/dist/server/handlers/logs.cjs +2 -2
  139. package/dist/server/handlers/logs.js +2 -2
  140. package/dist/server/handlers/mcp-client-versions.cjs +3 -3
  141. package/dist/server/handlers/mcp-client-versions.js +3 -3
  142. package/dist/server/handlers/mcp.cjs +1 -1
  143. package/dist/server/handlers/mcp.js +1 -1
  144. package/dist/server/handlers/memory.cjs +2 -2
  145. package/dist/server/handlers/memory.js +2 -2
  146. package/dist/server/handlers/observability-new-endpoints.cjs +1 -1
  147. package/dist/server/handlers/observability-new-endpoints.d.ts +335 -31
  148. package/dist/server/handlers/observability-new-endpoints.d.ts.map +1 -1
  149. package/dist/server/handlers/observability-new-endpoints.js +1 -1
  150. package/dist/server/handlers/observability-shared.cjs +73 -9
  151. package/dist/server/handlers/observability-shared.cjs.map +1 -1
  152. package/dist/server/handlers/observability-shared.d.ts +25 -1
  153. package/dist/server/handlers/observability-shared.d.ts.map +1 -1
  154. package/dist/server/handlers/observability-shared.js +68 -10
  155. package/dist/server/handlers/observability-shared.js.map +1 -1
  156. package/dist/server/handlers/observability.cjs +2 -2
  157. package/dist/server/handlers/observability.js +2 -2
  158. package/dist/server/handlers/plans.cjs +3 -3
  159. package/dist/server/handlers/plans.js +3 -3
  160. package/dist/server/handlers/processor-providers.cjs +1 -1
  161. package/dist/server/handlers/processor-providers.js +1 -1
  162. package/dist/server/handlers/processors.cjs +1 -1
  163. package/dist/server/handlers/processors.js +1 -1
  164. package/dist/server/handlers/prompt-block-versions.cjs +3 -3
  165. package/dist/server/handlers/prompt-block-versions.js +3 -3
  166. package/dist/server/handlers/responses.cjs +2 -2
  167. package/dist/server/handlers/responses.js +2 -2
  168. package/dist/server/handlers/responses.storage.cjs +1 -1
  169. package/dist/server/handlers/responses.storage.js +1 -1
  170. package/dist/server/handlers/schedules.cjs +1 -1
  171. package/dist/server/handlers/schedules.js +1 -1
  172. package/dist/server/handlers/scorer-versions.cjs +3 -3
  173. package/dist/server/handlers/scorer-versions.js +3 -3
  174. package/dist/server/handlers/scores.cjs +1 -1
  175. package/dist/server/handlers/scores.js +1 -1
  176. package/dist/server/handlers/stored-agent-favorites.cjs +3 -3
  177. package/dist/server/handlers/stored-agent-favorites.js +3 -3
  178. package/dist/server/handlers/stored-agents.cjs +3 -3
  179. package/dist/server/handlers/stored-agents.js +3 -3
  180. package/dist/server/handlers/stored-mcp-clients.cjs +3 -3
  181. package/dist/server/handlers/stored-mcp-clients.js +3 -3
  182. package/dist/server/handlers/stored-prompt-blocks.cjs +3 -3
  183. package/dist/server/handlers/stored-prompt-blocks.js +3 -3
  184. package/dist/server/handlers/stored-scorers.cjs +3 -3
  185. package/dist/server/handlers/stored-scorers.js +3 -3
  186. package/dist/server/handlers/stored-skill-favorites.cjs +4 -4
  187. package/dist/server/handlers/stored-skill-favorites.js +4 -4
  188. package/dist/server/handlers/stored-skills.cjs +4 -4
  189. package/dist/server/handlers/stored-skills.js +4 -4
  190. package/dist/server/handlers/stored-workspaces.cjs +2 -2
  191. package/dist/server/handlers/stored-workspaces.js +2 -2
  192. package/dist/server/handlers/system.cjs +3 -3
  193. package/dist/server/handlers/system.d.ts +6 -0
  194. package/dist/server/handlers/system.d.ts.map +1 -1
  195. package/dist/server/handlers/system.js +3 -3
  196. package/dist/server/handlers/tool-providers.cjs +1 -1
  197. package/dist/server/handlers/tool-providers.js +1 -1
  198. package/dist/server/handlers/tools.cjs +6 -6
  199. package/dist/server/handlers/tools.js +6 -6
  200. package/dist/server/handlers/utils.cjs +2 -1
  201. package/dist/server/handlers/utils.d.ts +9 -0
  202. package/dist/server/handlers/utils.d.ts.map +1 -1
  203. package/dist/server/handlers/utils.js +2 -2
  204. package/dist/server/handlers/validate-agent-instructions.cjs +1 -1
  205. package/dist/server/handlers/validate-agent-instructions.js +1 -1
  206. package/dist/server/handlers/vector.cjs +1 -1
  207. package/dist/server/handlers/vector.js +1 -1
  208. package/dist/server/handlers/workflow-builder.cjs +1 -1
  209. package/dist/server/handlers/workflow-builder.d.ts.map +1 -1
  210. package/dist/server/handlers/workflow-builder.js +1 -1
  211. package/dist/server/handlers/workflows.cjs +4 -4
  212. package/dist/server/handlers/workflows.js +4 -4
  213. package/dist/server/handlers/workspace.cjs +1 -1
  214. package/dist/server/handlers/workspace.js +1 -1
  215. package/dist/server/handlers.cjs +2 -2
  216. package/dist/server/handlers.js +2 -2
  217. package/dist/server/schemas/agents.d.ts +3 -0
  218. package/dist/server/schemas/agents.d.ts.map +1 -1
  219. package/dist/server/schemas/index.cjs +4 -4
  220. package/dist/server/schemas/index.js +4 -4
  221. package/dist/server/schemas/system.d.ts +6 -0
  222. package/dist/server/schemas/system.d.ts.map +1 -1
  223. package/dist/server/server-adapter/api-schema-manifest.d.ts +2 -0
  224. package/dist/server/server-adapter/api-schema-manifest.d.ts.map +1 -1
  225. package/dist/server/server-adapter/index.cjs +3 -3
  226. package/dist/server/server-adapter/index.js +3 -3
  227. package/dist/server/server-adapter/routes/observability.d.ts +167 -15
  228. package/dist/server/server-adapter/routes/observability.d.ts.map +1 -1
  229. package/dist/server/server-adapter/routes/system.d.ts +6 -0
  230. package/dist/server/server-adapter/routes/system.d.ts.map +1 -1
  231. package/dist/{system-MGpkVA20.js → system-CiAOa3RO.js} +4 -1
  232. package/dist/system-CiAOa3RO.js.map +1 -0
  233. package/dist/{system-DY6UweSl.cjs → system-wG9idyeI.cjs} +4 -1
  234. package/dist/system-wG9idyeI.cjs.map +1 -0
  235. package/dist/{utils-D5DHrO3K.js → utils-BBJlS81s.js} +19 -2
  236. package/dist/{utils-D5DHrO3K.js.map → utils-BBJlS81s.js.map} +1 -1
  237. package/dist/{utils-tmrFs-gf.js → utils-DCAUeb6M.js} +3 -3
  238. package/dist/{utils-tmrFs-gf.js.map → utils-DCAUeb6M.js.map} +1 -1
  239. package/dist/{utils-BZdnPmsW.cjs → utils-DCgeTrq2.cjs} +3 -3
  240. package/dist/{utils-BZdnPmsW.cjs.map → utils-DCgeTrq2.cjs.map} +1 -1
  241. package/dist/{utils-CczRcgHQ.cjs → utils-Du-EpvDs.cjs} +24 -1
  242. package/dist/{utils-CczRcgHQ.cjs.map → utils-Du-EpvDs.cjs.map} +1 -1
  243. package/dist/{workflow-builder-DJ0eeJuG.js → workflow-builder-Dr6Rm3gH.js} +6 -6
  244. package/dist/workflow-builder-Dr6Rm3gH.js.map +1 -0
  245. package/dist/{workflow-builder-DdSutoga.cjs → workflow-builder-Dx24RhD3.cjs} +6 -6
  246. package/dist/workflow-builder-Dx24RhD3.cjs.map +1 -0
  247. package/package.json +8 -9
  248. package/dist/a2a-Dg3ylOKc.js.map +0 -1
  249. package/dist/agents-D9vpLghy.cjs.map +0 -1
  250. package/dist/agents-DNWDET4U.js.map +0 -1
  251. package/dist/api-schema-manifest-BgWM-O7K.js.map +0 -1
  252. package/dist/api-schema-manifest-CI0gyTVi.cjs.map +0 -1
  253. package/dist/dist-CKHUMrWI.cjs.map +0 -1
  254. package/dist/dist-hfFDNas-.js.map +0 -1
  255. package/dist/observability-new-endpoints-BKFVVMTS.cjs.map +0 -1
  256. package/dist/observability-new-endpoints-C5VO7nLK.js.map +0 -1
  257. package/dist/schema-BVcoNfni.cjs +0 -1
  258. package/dist/schema-Xxr5X5Je.js +0 -2
  259. package/dist/system-DY6UweSl.cjs.map +0 -1
  260. package/dist/system-MGpkVA20.js.map +0 -1
  261. package/dist/workflow-builder-DJ0eeJuG.js.map +0 -1
  262. package/dist/workflow-builder-DdSutoga.cjs.map +0 -1
@@ -157,18 +157,20 @@ Hono and Fastify enforce the request-body limit before JSON parsing. Express and
157
157
 
158
158
  | Predicate context | Fields | Operators |
159
159
  | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------- |
160
- | Trace | `traceId`, `threadId`, `resourceId`, `runId`, `sessionId`, `userId`, `organizationId`, `entityName`, `entityType`, `environment`, `status` | `eq`, `ne`, `in`, `notIn`, `exists`, `notExists` |
160
+ | Trace | `traceId`, `threadId`, `resourceId`, `runId`, `sessionId`, `userId`, `organizationId`, `entityName`, `entityType`, `name`, `spanType`, `environment`, `status` | `eq`, `ne`, `in`, `notIn`, `exists`, `notExists` |
161
161
  | Trace metadata | `metadata.<key>` | `eq`, `ne`, `in`, `notIn`, `exists`, `notExists` |
162
- | Trace | `startedAt`, `endedAt`, `durationMs` | `eq`, `ne`, `in`, `notIn`, `lt`, `lte`, `gt`, `gte`, `exists`, `notExists` |
162
+ | Trace | `startedAt`, `endedAt`, `durationMs`, `timeToFirstChunkMs` | `eq`, `ne`, `in`, `notIn`, `lt`, `lte`, `gt`, `gte`, `exists`, `notExists` |
163
163
  | Trace | `tags` | `includes`, `notIncludes`, `exists`, `notExists` |
164
164
  | Span | `name` | `eq`, `ne`, `in`, `notIn`, `exists`, `notExists`, `matches`, `notMatches` |
165
165
  | Span | `spanType`, `model`, `provider`, `status`, `entityType`, `entityId`, `entityName`, `entityVersionId`, `parentEntityVersionId`, `rootEntityVersionId`, `runId`, `sessionId`, `userId`, `organizationId` | `eq`, `ne`, `in`, `notIn`, `exists`, `notExists` |
166
- | Span | `startedAt`, `endedAt`, `durationMs` | `eq`, `ne`, `in`, `notIn`, `lt`, `lte`, `gt`, `gte`, `exists`, `notExists` |
166
+ | Span | `startedAt`, `endedAt`, `durationMs`, `timeToFirstChunkMs` | `eq`, `ne`, `in`, `notIn`, `lt`, `lte`, `gt`, `gte`, `exists`, `notExists` |
167
167
  | Span | `error` | `exists`, `notExists` |
168
168
 
169
+ Trace-scope `name` and `spanType` read the current root span, so `{ op: 'eq', left: { path: 'spanType' }, right: { literal: 'workflow_run' } }` selects traces started by a workflow run. Inside `spans.some` or `spans.none`, the same fields match any span in the trace.
170
+
169
171
  Compose predicates with `{ op: 'and', args: [...] }`, `{ op: 'or', args: [...] }`, and `{ op: 'not', arg: ... }`. Comparison predicates place a field reference on the left and a literal on the right. Membership predicates use a field reference in `value` and a homogeneous literal array in `set`. Tag predicates name the stored tag collection in `path`. `includes` and `notIncludes` also take one tag in `value`, while `exists` and `notExists` take only `op` and `path`. See [Filter by tags](#filter-by-tags). Text predicates use the comparison shape with a string literal. See [Filter by text](#filter-by-text).
170
172
 
171
- String comparisons are case-sensitive, and literals are never coerced. `matches` and `notMatches` are the exception: they compare words case-insensitively. Canonical string fields compare exact stored values. Metadata string values are trimmed before comparison, as described below. Duration predicates require numbers, while timestamp predicates require ISO timestamp strings. A missing value satisfies neither positive nor ordered predicates, although it does satisfy the negative operators `ne` and `notIn`. Combine a negative predicate with `exists` when the field must also be present.
173
+ String comparisons are case-sensitive, and literals are never coerced. `matches` and `notMatches` are the exception: they compare words case-insensitively. Canonical string fields compare exact stored values. Metadata string values are trimmed before comparison, as described below. Duration and time-to-first-chunk predicates require numbers, while timestamp predicates require ISO timestamp strings. A missing value satisfies neither positive nor ordered predicates, although it does satisfy the negative operators `ne` and `notIn`. Combine a negative predicate with `exists` when the field must also be present.
172
174
 
173
175
  ### Filter by root duration
174
176
 
@@ -186,6 +188,30 @@ This top-level predicate doesn't inspect child spans. In contrast, `spans.some`
186
188
 
187
189
  Trace queries exclude incomplete roots before evaluating predicates. As a result, `{ op: 'notExists', path: 'durationMs' }` doesn't find running traces or malformed roots without a usable `endedAt`.
188
190
 
191
+ ### Filter by time to first chunk
192
+
193
+ `timeToFirstChunkMs` is the time in milliseconds from a span's start to the first chunk of its model response. Agent run and model spans record it when the model streams a response. At trace scope, the field reads the current root span's value. Inside `spans.some` or `spans.none`, it reads each related span.
194
+
195
+ This predicate finds traces with a model call that took more than 2 seconds to stream its first chunk:
196
+
197
+ ```typescript
198
+ const slowFirstChunk = {
199
+ spans: {
200
+ some: {
201
+ op: 'and',
202
+ args: [
203
+ { op: 'eq', left: { path: 'spanType' }, right: { literal: 'model_generation' } },
204
+ { op: 'gt', left: { path: 'timeToFirstChunkMs' }, right: { literal: 2000 } },
205
+ ],
206
+ },
207
+ },
208
+ }
209
+ ```
210
+
211
+ The value is `null` when the span didn't stream a chunk, for example a tool call or a workflow run. A `null` value counts as missing, so it matches `notExists` and never matches ordered predicates. A value of `0` isn't missing. It means the first chunk arrived in the same millisecond the span started.
212
+
213
+ Trace query results include the root span's `timeToFirstChunkMs`, and `querySpans()` results include each span's value. Sorting by this field isn't supported. Stores advertise support through the `trace-query-time-to-first-chunk` feature, and the server reports it as the `traceQueryTimeToFirstChunk` capability. Against an older store, results omit the field, a predicate on it returns `501` before storage runs, and field discovery omits it.
214
+
189
215
  ### Filter by context identifiers
190
216
 
191
217
  `runId`, `sessionId`, `userId`, and `organizationId` are available at trace scope and inside `spans.some` / `spans.none`. Trace-scope predicates read the current root span. Span-scope predicates bind to one related current span, so a run recorded only on a child span is found through `spans.some`:
@@ -382,13 +408,16 @@ A query using keyset pagination returns lightweight completed traces and a curso
382
408
  "entityName": "support-agent",
383
409
  "entityType": "agent",
384
410
  "environment": "production",
385
- "status": "success"
411
+ "status": "success",
412
+ "timeToFirstChunkMs": 412
386
413
  }
387
414
  ],
388
415
  "page": { "next": null }
389
416
  }
390
417
  ```
391
418
 
419
+ `timeToFirstChunkMs` is present only when the configured store supports it. See [Filter by time to first chunk](#filter-by-time-to-first-chunk).
420
+
392
421
  The response doesn't include the related spans that matched the predicate. Use [`getTrace()`](https://mastra.ai/reference/client-js/observability) to load the full trace after selecting a result.
393
422
 
394
423
  ### CLI responses
@@ -591,12 +620,12 @@ Discovery returns string values only. Missing values, empty strings, and strings
591
620
 
592
621
  Value suggestions are available for these canonical fields:
593
622
 
594
- | Scope | Fields |
595
- | ----- | ----------------------------------------------------------------------------- |
596
- | Trace | `entityName`, `entityType`, `environment`, `status`, `tags` |
597
- | Spans | `name`, `spanType`, `model`, `provider`, `status`, `entityType`, `entityName` |
623
+ | Scope | Fields |
624
+ | ----- | ------------------------------------------------------------------------------- |
625
+ | Trace | `entityName`, `entityType`, `name`, `spanType`, `environment`, `status`, `tags` |
626
+ | Spans | `name`, `spanType`, `model`, `provider`, `status`, `entityType`, `entityName` |
598
627
 
599
- Each executable top-level string `metadata.<key>` field also supports value suggestions in the `trace` scope. Identifiers, timestamps, durations, errors, and version IDs don't. The fields response still includes canonical fields with `valueSuggestions: false`. The values endpoint rejects those paths with `422 TRACE_QUERY_INVALID`.
628
+ Each executable top-level string `metadata.<key>` field also supports value suggestions in the `trace` scope. Identifiers, timestamps, durations, time to first chunk, errors, and version IDs don't. The fields response still includes canonical fields with `valueSuggestions: false`. The values endpoint rejects those paths with `422 TRACE_QUERY_INVALID`.
600
629
 
601
630
  Both discovery requests require a half-open time range. They use the same current-record semantics as `queryTraces()`: qualifying completed roots satisfy `from <= startedAt < to`, and related values come only from current records joined to those roots by `traceId`. Discovery doesn't accept or apply a draft `where` predicate.
602
631
 
@@ -1,6 +1,6 @@
1
1
  const require_rolldown_runtime = require("./rolldown-runtime-Bd6kNlEP.cjs");
2
2
  const require_http_exception = require("./http-exception-CKDHupKw.cjs");
3
- const require_route_builder = require("./route-builder-2yrD15TL.cjs");
3
+ const require_route_builder = require("./route-builder-TBkBU65d.cjs");
4
4
  const require_server_handlers_error = require("./server/handlers/error.cjs");
5
5
  let zod_v4 = require("zod/v4");
6
6
  //#region src/server/schemas/dynamic-workflows.ts
@@ -379,4 +379,4 @@ Object.defineProperty(exports, "dynamic_workflows_exports", {
379
379
  }
380
380
  });
381
381
 
382
- //# sourceMappingURL=dynamic-workflows-BL3eD0zL.cjs.map
382
+ //# sourceMappingURL=dynamic-workflows-BVW4SyS5.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"dynamic-workflows-BL3eD0zL.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,MA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,SAAS,YAAY,kBAAkB;GAAU;EACpF,SAAS,OAAO;GACd,OAAOC,8BAAAA,YAAY,OAAO,iCAAiC;EAC7D;CACF;AACF,CAAC"}
1
+ {"version":3,"file":"dynamic-workflows-BVW4SyS5.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,O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A,aACA,cACA,aACA,sBACA,OACA,mBACI;EACJ,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,6 +1,6 @@
1
1
  import { r as __exportAll } from "./rolldown-runtime-maW3aOIk.js";
2
2
  import { t as HTTPException } from "./http-exception-CyfxZB6W.js";
3
- import { n as createRoute } from "./route-builder-lBil8Cvo.js";
3
+ import { n as createRoute } from "./route-builder-DzUGCSQT.js";
4
4
  import { handleError } from "./server/handlers/error.js";
5
5
  import { z } from "zod/v4";
6
6
  //#region src/server/schemas/dynamic-workflows.ts
@@ -350,4 +350,4 @@ const DELETE_DYNAMIC_WORKFLOW_ROUTE = createRoute({
350
350
  //#endregion
351
351
  export { dynamic_workflows_exports as a, UPSERT_DYNAMIC_WORKFLOW_ROUTE as i, GET_DYNAMIC_WORKFLOW_ROUTE as n, LIST_DYNAMIC_WORKFLOWS_ROUTE as r, DELETE_DYNAMIC_WORKFLOW_ROUTE as t };
352
352
 
353
- //# sourceMappingURL=dynamic-workflows-BJfoQMo8.js.map
353
+ //# sourceMappingURL=dynamic-workflows-CE-xM2NQ.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"dynamic-workflows-BJfoQMo8.js","names":[],"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,oBAAoB,EACvB,OAAO;CACN,SAAS,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,YAAY,CAAC,CAAC,SAAS;CACjD,UAAU,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC,SAAS;AACvD,CAAC,CAAC,CACD,SAAS;AAMZ,MAAM,qBAAqB;CACzB,aAAa,EAAE,OAAO,CAAC,CAAC,SAAS;CACjC,UAAU,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC,SAAS;AACvD;AACA,MAAM,0BAA0B;CAC9B,IAAI,EAAE,OAAO,CAAC,CAAC,SAAS;CACxB,GAAG;AACL;AAOA,MAAM,gBAAgB,EAAE,MAAM;CAAC,EAAE,OAAO;CAAG,EAAE,OAAO;CAAG,EAAE,QAAQ;CAAG,EAAE,KAAK;AAAC,CAAC;AAC7E,MAAM,gBAA2B,EAAE,MAAM,CACvC,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC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O,eAAe,iBAAiB;GACvC,OAAO;IAAE,SAAS;IAAe,SAAS,YAAY,kBAAkB;GAAU;EACpF,SAAS,OAAO;GACd,OAAO,YAAY,OAAO,iCAAiC;EAC7D;CACF;AACF,CAAC"}
1
+ {"version":3,"file":"dynamic-workflows-CE-xM2NQ.js","names":[],"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,oBAAoB,EACvB,OAAO;CACN,SAAS,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,YAAY,CAAC,CAAC,SAAS;CACjD,UAAU,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC,SAAS;AACvD,CAAC,CAAC,CACD,SAAS;AAMZ,MAAM,qBAAqB;CACzB,aAAa,EAAE,OAAO,CAAC,CAAC,SAAS;CACjC,UAAU,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC,SAAS;AACvD;AACA,MAAM,0BAA0B;CAC9B,IAAI,EAAE,OAAO,CAAC,CAAC,SAAS;CACxB,GAAG;AACL;AAOA,MAAM,gBAAgB,EAAE,MAAM;CAAC,EAAE,OAAO;CAAG,EAAE,OAAO;CAAG,EAAE,QAAQ;CAAG,EAAE,KAAK;AAAC,CAAC;AAC7E,MAAM,gBAA2B,EAAE,MAAM,CACvC,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,GAC7C,EAAE,OAAO,EAAE,SAAS,cAAc,CAAC,CAAC,CAAC,OAAO,CAC9C,CAAC;AACD,MAAM,kBAA6B,EAAE,WACnC,EAAE,MAAM;CACN,EACG,OAAO;EACN,IAAI,EAAE,KAAK;GAAC;GAAM;GAAM;GAAM;GAAO;GAAM;EAAK,CAAC;EACjD,MAAM;EACN,OAAO;CACT,CAAC,CAAC,CACD,OAAO;CACV,EACG,OAAO;EACN,IAAI,EAAE,KAAK,CAA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,sBACA,OACA,mBACI;EACJ,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,OAAO,YAAY,OAAO,kCAAkC;EAC9D;CACF;AACF,CAAC;;;;;;;AAQD,MAAa,gCAAgC,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,IAAI,cAAc,KAAK,EAAE,SAAS,4BAA4B,CAAC;GAEnF,MAAM,QAAQ,MAAM,QAAQ,SAAS,qBAAqB;GAC1D,IAAI,CAAC,OAAO,MAAM,IAAI,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,OAAO,YAAY,OAAO,iCAAiC;EAC7D;CACF;AACF,CAAC"}
@@ -1,8 +1,8 @@
1
1
  const require_http_exception = require("./http-exception-CKDHupKw.cjs");
2
- const require_route_builder = require("./route-builder-2yrD15TL.cjs");
2
+ const require_route_builder = require("./route-builder-TBkBU65d.cjs");
3
3
  const require_server_handlers_error = require("./server/handlers/error.cjs");
4
4
  const require_server_handlers_agents = require("./server/handlers/agents.cjs");
5
- const require_editor_builder = require("./editor-builder-DqHKoEDx.cjs");
5
+ const require_editor_builder = require("./editor-builder-CP7URDqM.cjs");
6
6
  //#region src/server/utils/resolve-builder-model-policy.ts
7
7
  /**
8
8
  * Server-side wrapper around `builderToModelPolicy`.
@@ -364,4 +364,4 @@ Object.defineProperty(exports, "requireBuilderFeature", {
364
364
  }
365
365
  });
366
366
 
367
- //# sourceMappingURL=editor-builder-BOmAPurW.cjs.map
367
+ //# sourceMappingURL=editor-builder-C2dwLp86.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"editor-builder-BOmAPurW.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;C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eAAe,eAAe;IACpC,MAAM,kBAAkB,cAAc,UAAU,CAAC;IACjD,MAAM,uBAAuB,OAAO,eAAe;IACnD,MAAM,sBAAsB,cAAc,cACtC,qBAAqB,aAAa,eAClC,KAAA;IACJ,MAAM,aAAa,qBAAqB,UAAU,cAAc,gBAAgB;IAChF,MAAM,UAAU,qBAAqB,UAAU,WAAW,gBAAgB;IAC1E,MAAM,mBACJ,OAAO,gBAAgB,eAAe,YACtC,gBAAgB,cAChB,YAAY,gBAAgB,aACvB,gBAAgB,WAAW,SAC5B,CAAC;IACP,MAAM,gBACJ,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-C2dwLp86.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;CACvG,IAAI,CAAE,MAAM,wBAAwB,QAAQ,OAAO,GACjD,MAAM,IAAIC,uBAAAA,cAAc,KAAK,EAAE,SAAS,YAAY,CAAC;AAEzD;;;;;;;AAQA,MAAa,oCAAoCC,sBAAAA,YAAY;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C,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,4 +1,4 @@
1
- import { j as providerSchema } from "./agents-DNWDET4U.js";
1
+ import { j as providerSchema } from "./agents-wamaX7m2.js";
2
2
  import { z } from "zod/v4";
3
3
  //#region src/server/schemas/editor-builder.ts
4
4
  /**
@@ -191,4 +191,4 @@ const builderAvailableModelsResponseSchema = z.object({ providers: z.array(provi
191
191
  //#endregion
192
192
  export { builderModelPolicySchema as a, defaultModelEntrySchema as c, providerModelEntrySchema as d, builderAvailableModelsResponseSchema as i, infrastructureStatusResponseSchema as l, agentFeaturesSchema as n, builderPickerSchema as o, agentModelsSchema as r, builderSettingsResponseSchema as s, agentConfigurationSchema as t, pickerAllowlistSchema as u };
193
193
 
194
- //# sourceMappingURL=editor-builder-DHqCWGd2.js.map
194
+ //# sourceMappingURL=editor-builder-C5xHbYcZ.js.map