@mastra/server 1.79.0-alpha.10 → 1.79.0-alpha.12

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