@mastra/server 1.83.0-alpha.12 → 1.83.0-alpha.13

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 (543) hide show
  1. package/dist/_types/@internal_voice@0.0.44/dist/_types/@internal_core@0.1.4/dist/request-context/index.d.ts +19 -0
  2. package/dist/{a2a-DIcMx6x-.cjs → a2a-Bz7vRGfF.cjs} +9 -6
  3. package/dist/a2a-Bz7vRGfF.cjs.map +1 -0
  4. package/dist/{a2a-DTTGA2Xg.js → a2a-CY85JalK.js} +9 -6
  5. package/dist/a2a-CY85JalK.js.map +1 -0
  6. package/dist/{agent-builder-BNfBksTT.js → agent-builder-Ce1pjSjg.js} +6 -6
  7. package/dist/{agent-builder-BNfBksTT.js.map → agent-builder-Ce1pjSjg.js.map} +1 -1
  8. package/dist/{agent-builder-CopkMfWF.cjs → agent-builder-DWtgp1cb.cjs} +6 -6
  9. package/dist/{agent-builder-CopkMfWF.cjs.map → agent-builder-DWtgp1cb.cjs.map} +1 -1
  10. package/dist/{agents-BCgiMlDq.js → agents-B0OpLdbp.js} +444 -3
  11. package/dist/agents-B0OpLdbp.js.map +1 -0
  12. package/dist/{agents-DjpBmwhv.cjs → agents-BgaBbcwb.cjs} +136 -53
  13. package/dist/agents-BgaBbcwb.cjs.map +1 -0
  14. package/dist/{agents-CTgjTASj.js → agents-BjlUjmb1.js} +136 -53
  15. package/dist/agents-BjlUjmb1.js.map +1 -0
  16. package/dist/{agents-CjcvdF2e.cjs → agents-CH_G37hG.cjs} +521 -2
  17. package/dist/agents-CH_G37hG.cjs.map +1 -0
  18. package/dist/{api-schema-manifest-CkB5OGjC.js → api-schema-manifest-CsTpd03O.js} +9 -9
  19. package/dist/api-schema-manifest-CsTpd03O.js.map +1 -0
  20. package/dist/{api-schema-manifest-CJz_hWjy.cjs → api-schema-manifest-DT9X0fAm.cjs} +9 -9
  21. package/dist/api-schema-manifest-DT9X0fAm.cjs.map +1 -0
  22. package/dist/{background-tasks-CYvlxFz3.js → background-tasks-BKnoXtUN.js} +3 -3
  23. package/dist/{background-tasks-CYvlxFz3.js.map → background-tasks-BKnoXtUN.js.map} +1 -1
  24. package/dist/{background-tasks-Dv9o8cR7.cjs → background-tasks-BqW1_VmH.cjs} +3 -3
  25. package/dist/{background-tasks-Dv9o8cR7.cjs.map → background-tasks-BqW1_VmH.cjs.map} +1 -1
  26. package/dist/{builder-registry-BmrttdGj.js → builder-registry-ByghMyfA.js} +3 -3
  27. package/dist/{builder-registry-BmrttdGj.js.map → builder-registry-ByghMyfA.js.map} +1 -1
  28. package/dist/{builder-registry-CmbtZzbE.cjs → builder-registry-DPsdmtZG.cjs} +3 -3
  29. package/dist/{builder-registry-CmbtZzbE.cjs.map → builder-registry-DPsdmtZG.cjs.map} +1 -1
  30. package/dist/catalogue-CGQdyojN.cjs +1378 -0
  31. package/dist/catalogue-CGQdyojN.cjs.map +1 -0
  32. package/dist/catalogue-CUJevxy3.js +1376 -0
  33. package/dist/catalogue-CUJevxy3.js.map +1 -0
  34. package/dist/{channels-KHhb7hAm.js → channels-DIE-lJkq.js} +3 -3
  35. package/dist/{channels-KHhb7hAm.js.map → channels-DIE-lJkq.js.map} +1 -1
  36. package/dist/{channels-CXwFVxi2.cjs → channels-k5dF1IBc.cjs} +3 -3
  37. package/dist/{channels-CXwFVxi2.cjs.map → channels-k5dF1IBc.cjs.map} +1 -1
  38. package/dist/{constants-CXAvBYcz.js → constants-0xZU_h4R.js} +10 -2
  39. package/dist/constants-0xZU_h4R.js.map +1 -0
  40. package/dist/{constants-DMg8hUOR.cjs → constants-1yTmKUZD.cjs} +15 -1
  41. package/dist/constants-1yTmKUZD.cjs.map +1 -0
  42. package/dist/{conversations-BFqmDglO.cjs → conversations-Bvk5VVVJ.cjs} +6 -5
  43. package/dist/conversations-Bvk5VVVJ.cjs.map +1 -0
  44. package/dist/{conversations-BkX00xDs.js → conversations-DYqwqCWH.js} +6 -5
  45. package/dist/conversations-DYqwqCWH.js.map +1 -0
  46. package/dist/dist-BVw6-hMs.js +1 -0
  47. package/dist/{dist-G8g-Cg67.js → dist-C-Hmkkat.js} +6 -6
  48. package/dist/{dist-G8g-Cg67.js.map → dist-C-Hmkkat.js.map} +1 -1
  49. package/dist/{dist-COfASzWw.cjs → dist-Clh3uSOV.cjs} +11 -11
  50. package/dist/{dist-COfASzWw.cjs.map → dist-Clh3uSOV.cjs.map} +1 -1
  51. package/dist/{dist-3WMLkPSs.cjs → dist-DPgpEz_7.cjs} +1 -1
  52. package/dist/docs/SKILL.md +3 -1
  53. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  54. package/dist/docs/references/docs-server-mcp.md +315 -0
  55. package/dist/docs/references/reference-server-dispatch-route.md +124 -0
  56. package/dist/docs/references/reference-server-invoke-route.md +10 -0
  57. package/dist/{dynamic-workflows-QgKLYkiC.cjs → dynamic-workflows-DPgV6qtS.cjs} +2 -2
  58. package/dist/{dynamic-workflows-QgKLYkiC.cjs.map → dynamic-workflows-DPgV6qtS.cjs.map} +1 -1
  59. package/dist/{dynamic-workflows-CYtakeIQ.js → dynamic-workflows-DmkCJ4Lp.js} +2 -2
  60. package/dist/{dynamic-workflows-CYtakeIQ.js.map → dynamic-workflows-DmkCJ4Lp.js.map} +1 -1
  61. package/dist/{editor-builder-C4H2l6tz.js → editor-builder-CGM0scw2.js} +10 -4
  62. package/dist/editor-builder-CGM0scw2.js.map +1 -0
  63. package/dist/{editor-builder-fe70YP8g.js → editor-builder-CXLdplIj.js} +2 -2
  64. package/dist/{editor-builder-fe70YP8g.js.map → editor-builder-CXLdplIj.js.map} +1 -1
  65. package/dist/{editor-builder-Cqw1npOK.cjs → editor-builder-SP_ledm3.cjs} +10 -4
  66. package/dist/editor-builder-SP_ledm3.cjs.map +1 -0
  67. package/dist/{editor-builder-xQmDgVgJ.cjs → editor-builder-eF2IetF2.cjs} +2 -2
  68. package/dist/{editor-builder-xQmDgVgJ.cjs.map → editor-builder-eF2IetF2.cjs.map} +1 -1
  69. package/dist/{helpers-C9QZKOhz.js → helpers-B56oH6qp.js} +27 -8
  70. package/dist/helpers-B56oH6qp.js.map +1 -0
  71. package/dist/{helpers-0LJI4DxR.cjs → helpers-Dpdta8ai.cjs} +31 -6
  72. package/dist/helpers-Dpdta8ai.cjs.map +1 -0
  73. package/dist/{knowledge-CRkWkTBC.cjs → knowledge-2fms70NN.cjs} +4 -4
  74. package/dist/{knowledge-CRkWkTBC.cjs.map → knowledge-2fms70NN.cjs.map} +1 -1
  75. package/dist/{knowledge-Dfe_CFtt.js → knowledge-BblTTH3z.js} +4 -4
  76. package/dist/{knowledge-Dfe_CFtt.js.map → knowledge-BblTTH3z.js.map} +1 -1
  77. package/dist/{logs-Dg2AWexF.js → logs-D_hKQuvQ.js} +3 -3
  78. package/dist/{logs-Dg2AWexF.js.map → logs-D_hKQuvQ.js.map} +1 -1
  79. package/dist/{logs-B2ov1yZQ.cjs → logs-Deoh0l4I.cjs} +3 -3
  80. package/dist/{logs-B2ov1yZQ.cjs.map → logs-Deoh0l4I.cjs.map} +1 -1
  81. package/dist/{mcp-bsPRIGFX.js → mcp-CSRuYaWN.js} +3 -3
  82. package/dist/{mcp-bsPRIGFX.js.map → mcp-CSRuYaWN.js.map} +1 -1
  83. package/dist/{mcp-Bon4eIV1.cjs → mcp-oWjcmsQb.cjs} +3 -3
  84. package/dist/{mcp-Bon4eIV1.cjs.map → mcp-oWjcmsQb.cjs.map} +1 -1
  85. package/dist/{memory-Dw7xG5nn.js → memory-CGlo-6_V.js} +105 -12
  86. package/dist/memory-CGlo-6_V.js.map +1 -0
  87. package/dist/{memory-BRE3ofvI.cjs → memory-CzSke9Em.cjs} +105 -12
  88. package/dist/memory-CzSke9Em.cjs.map +1 -0
  89. package/dist/{observability-C2HjrCpw.cjs → observability-BCJsmSH0.cjs} +27 -3
  90. package/dist/observability-BCJsmSH0.cjs.map +1 -0
  91. package/dist/{observability-Ca3TxxY7.js → observability-Z2tDxHS1.js} +27 -3
  92. package/dist/observability-Z2tDxHS1.js.map +1 -0
  93. package/dist/{observability-new-endpoints-DnzWjscD.cjs → observability-new-endpoints-C_HEkpZ1.cjs} +153 -3
  94. package/dist/observability-new-endpoints-C_HEkpZ1.cjs.map +1 -0
  95. package/dist/{observability-new-endpoints-B3X2L7cj.js → observability-new-endpoints-dr0XcNkP.js} +153 -3
  96. package/dist/observability-new-endpoints-dr0XcNkP.js.map +1 -0
  97. package/dist/{plans-D_GKFz2x.js → plans-BemJO4-7.js} +7 -6
  98. package/dist/plans-BemJO4-7.js.map +1 -0
  99. package/dist/{plans-_nR8lqgD.cjs → plans-CffjV2_6.cjs} +7 -6
  100. package/dist/plans-CffjV2_6.cjs.map +1 -0
  101. package/dist/{probe-image-size-C2b8QfA7.js → probe-image-size-jA5gozO6.js} +2 -2
  102. package/dist/{probe-image-size-C2b8QfA7.js.map → probe-image-size-jA5gozO6.js.map} +1 -1
  103. package/dist/{probe-image-size-DLuC8QsM.cjs → probe-image-size-qOT5Pn0l.cjs} +2 -2
  104. package/dist/{probe-image-size-DLuC8QsM.cjs.map → probe-image-size-qOT5Pn0l.cjs.map} +1 -1
  105. package/dist/{responses-C_OEJoxU.js → responses-BofWEQYg.js} +11 -8
  106. package/dist/responses-BofWEQYg.js.map +1 -0
  107. package/dist/{responses-CdWbS4jA.cjs → responses-D0mb5ubj.cjs} +11 -8
  108. package/dist/responses-D0mb5ubj.cjs.map +1 -0
  109. package/dist/{route-builder-B9C5vT54.cjs → route-builder-DjTBxSZN.cjs} +10 -10
  110. package/dist/{route-builder-B9C5vT54.cjs.map → route-builder-DjTBxSZN.cjs.map} +1 -1
  111. package/dist/{route-builder-DfDT1g4L.js → route-builder-Dz18c3qm.js} +9 -9
  112. package/dist/{route-builder-DfDT1g4L.js.map → route-builder-Dz18c3qm.js.map} +1 -1
  113. package/dist/{routes-CQZ0Z77B.cjs → routes-01JAJiMe.cjs} +646 -27
  114. package/dist/routes-01JAJiMe.cjs.map +1 -0
  115. package/dist/{routes-CqzWkepR.js → routes-CmkPohqd.js} +593 -28
  116. package/dist/routes-CmkPohqd.js.map +1 -0
  117. package/dist/{schedules-BQvnAe1j.cjs → schedules-BRwhbppl.cjs} +77 -22
  118. package/dist/schedules-BRwhbppl.cjs.map +1 -0
  119. package/dist/{schedules-BcAIELfB.js → schedules-Zct_0ZwE.js} +77 -22
  120. package/dist/schedules-Zct_0ZwE.js.map +1 -0
  121. package/dist/{schema-xsUy1mlm-CAPin6jE.js → schema-TQPB_dl2-CCzMcdDx.js} +9 -6
  122. package/dist/{schema-xsUy1mlm-CAPin6jE.js.map → schema-TQPB_dl2-CCzMcdDx.js.map} +1 -1
  123. package/dist/{schema-xsUy1mlm-pvZI8YC0.cjs → schema-TQPB_dl2-CJX1q58F.cjs} +9 -6
  124. package/dist/{schema-xsUy1mlm-pvZI8YC0.cjs.map → schema-TQPB_dl2-CJX1q58F.cjs.map} +1 -1
  125. package/dist/{scores-DEvPN0kz.cjs → scores-0MyV08tL.cjs} +26 -11
  126. package/dist/scores-0MyV08tL.cjs.map +1 -0
  127. package/dist/{scores-Dm0yu1Pt.js → scores-CVssMyoQ.js} +26 -11
  128. package/dist/scores-CVssMyoQ.js.map +1 -0
  129. package/dist/server/auth/helpers.d.ts +7 -1
  130. package/dist/server/auth/helpers.d.ts.map +1 -1
  131. package/dist/server/auth/index.cjs +4 -2
  132. package/dist/server/auth/index.js +3 -3
  133. package/dist/server/constants.d.ts +8 -1
  134. package/dist/server/constants.d.ts.map +1 -1
  135. package/dist/server/handlers/a2a.cjs +1 -1
  136. package/dist/server/handlers/a2a.d.ts +4 -0
  137. package/dist/server/handlers/a2a.d.ts.map +1 -1
  138. package/dist/server/handlers/a2a.js +1 -1
  139. package/dist/server/handlers/agent-access.cjs +42 -0
  140. package/dist/server/handlers/agent-access.cjs.map +1 -0
  141. package/dist/server/handlers/agent-access.d.ts +19 -0
  142. package/dist/server/handlers/agent-access.d.ts.map +1 -0
  143. package/dist/server/handlers/agent-access.js +39 -0
  144. package/dist/server/handlers/agent-access.js.map +1 -0
  145. package/dist/server/handlers/agent-builder.cjs +1 -1
  146. package/dist/server/handlers/agent-builder.d.ts +32 -0
  147. package/dist/server/handlers/agent-builder.d.ts.map +1 -1
  148. package/dist/server/handlers/agent-builder.js +1 -1
  149. package/dist/server/handlers/agent-controller.cjs +3 -3
  150. package/dist/server/handlers/agent-controller.d.ts +72 -0
  151. package/dist/server/handlers/agent-controller.d.ts.map +1 -1
  152. package/dist/server/handlers/agent-controller.js +3 -3
  153. package/dist/server/handlers/agent-versions.cjs +30 -2
  154. package/dist/server/handlers/agent-versions.cjs.map +1 -1
  155. package/dist/server/handlers/agent-versions.d.ts +12 -0
  156. package/dist/server/handlers/agent-versions.d.ts.map +1 -1
  157. package/dist/server/handlers/agent-versions.js +30 -2
  158. package/dist/server/handlers/agent-versions.js.map +1 -1
  159. package/dist/server/handlers/agents.cjs +1 -1
  160. package/dist/server/handlers/agents.d.ts +91 -2
  161. package/dist/server/handlers/agents.d.ts.map +1 -1
  162. package/dist/server/handlers/agents.js +1 -1
  163. package/dist/server/handlers/auth.cjs +3 -3
  164. package/dist/server/handlers/auth.d.ts +40 -0
  165. package/dist/server/handlers/auth.d.ts.map +1 -1
  166. package/dist/server/handlers/auth.js +3 -3
  167. package/dist/server/handlers/authorship.cjs +1 -1
  168. package/dist/server/handlers/authorship.js +1 -1
  169. package/dist/server/handlers/background-tasks.cjs +1 -1
  170. package/dist/server/handlers/background-tasks.d.ts +8 -0
  171. package/dist/server/handlers/background-tasks.d.ts.map +1 -1
  172. package/dist/server/handlers/background-tasks.js +1 -1
  173. package/dist/server/handlers/builder-registry.cjs +1 -1
  174. package/dist/server/handlers/builder-registry.d.ts +10 -0
  175. package/dist/server/handlers/builder-registry.d.ts.map +1 -1
  176. package/dist/server/handlers/builder-registry.js +1 -1
  177. package/dist/server/handlers/channels.cjs +1 -1
  178. package/dist/server/handlers/channels.d.ts +10 -0
  179. package/dist/server/handlers/channels.d.ts.map +1 -1
  180. package/dist/server/handlers/channels.js +1 -1
  181. package/dist/server/handlers/conversations.cjs +1 -1
  182. package/dist/server/handlers/conversations.d.ts +8 -0
  183. package/dist/server/handlers/conversations.d.ts.map +1 -1
  184. package/dist/server/handlers/conversations.js +1 -1
  185. package/dist/server/handlers/datasets.cjs +2 -2
  186. package/dist/server/handlers/datasets.d.ts +66 -0
  187. package/dist/server/handlers/datasets.d.ts.map +1 -1
  188. package/dist/server/handlers/datasets.js +2 -2
  189. package/dist/server/handlers/dynamic-workflows.cjs +1 -1
  190. package/dist/server/handlers/dynamic-workflows.d.ts +8 -0
  191. package/dist/server/handlers/dynamic-workflows.d.ts.map +1 -1
  192. package/dist/server/handlers/dynamic-workflows.js +1 -1
  193. package/dist/server/handlers/editor-builder.cjs +1 -1
  194. package/dist/server/handlers/editor-builder.d.ts +6 -0
  195. package/dist/server/handlers/editor-builder.d.ts.map +1 -1
  196. package/dist/server/handlers/editor-builder.js +1 -1
  197. package/dist/server/handlers/favorites-enrichment.cjs +1 -1
  198. package/dist/server/handlers/favorites-enrichment.js +1 -1
  199. package/dist/server/handlers/knowledge.cjs +1 -1
  200. package/dist/server/handlers/knowledge.d.ts +18 -0
  201. package/dist/server/handlers/knowledge.d.ts.map +1 -1
  202. package/dist/server/handlers/knowledge.js +1 -1
  203. package/dist/server/handlers/logs.cjs +1 -1
  204. package/dist/server/handlers/logs.d.ts +6 -0
  205. package/dist/server/handlers/logs.d.ts.map +1 -1
  206. package/dist/server/handlers/logs.js +1 -1
  207. package/dist/server/handlers/mcp-client-versions.cjs +2 -2
  208. package/dist/server/handlers/mcp-client-versions.d.ts +14 -0
  209. package/dist/server/handlers/mcp-client-versions.d.ts.map +1 -1
  210. package/dist/server/handlers/mcp-client-versions.js +2 -2
  211. package/dist/server/handlers/mcp.cjs +1 -1
  212. package/dist/server/handlers/mcp.d.ts +42 -0
  213. package/dist/server/handlers/mcp.d.ts.map +1 -1
  214. package/dist/server/handlers/mcp.js +1 -1
  215. package/dist/server/handlers/memory.cjs +1 -1
  216. package/dist/server/handlers/memory.d.ts +52 -0
  217. package/dist/server/handlers/memory.d.ts.map +1 -1
  218. package/dist/server/handlers/memory.js +1 -1
  219. package/dist/server/handlers/observability-new-endpoints.cjs +1 -1
  220. package/dist/server/handlers/observability-new-endpoints.d.ts +153 -1
  221. package/dist/server/handlers/observability-new-endpoints.d.ts.map +1 -1
  222. package/dist/server/handlers/observability-new-endpoints.js +1 -1
  223. package/dist/server/handlers/observability-shared.cjs +2 -1
  224. package/dist/server/handlers/observability-shared.cjs.map +1 -1
  225. package/dist/server/handlers/observability-shared.d.ts +9 -0
  226. package/dist/server/handlers/observability-shared.d.ts.map +1 -1
  227. package/dist/server/handlers/observability-shared.js +2 -2
  228. package/dist/server/handlers/observability-shared.js.map +1 -1
  229. package/dist/server/handlers/observability-signal-context.cjs +1 -1
  230. package/dist/server/handlers/observability-signal-context.js +1 -1
  231. package/dist/server/handlers/observability.cjs +2 -2
  232. package/dist/server/handlers/observability.d.ts +12 -0
  233. package/dist/server/handlers/observability.d.ts.map +1 -1
  234. package/dist/server/handlers/observability.js +2 -2
  235. package/dist/server/handlers/plans.cjs +1 -1
  236. package/dist/server/handlers/plans.d.ts +2 -0
  237. package/dist/server/handlers/plans.d.ts.map +1 -1
  238. package/dist/server/handlers/plans.js +1 -1
  239. package/dist/server/handlers/processor-providers.cjs +1 -1
  240. package/dist/server/handlers/processor-providers.d.ts +4 -0
  241. package/dist/server/handlers/processor-providers.d.ts.map +1 -1
  242. package/dist/server/handlers/processor-providers.js +1 -1
  243. package/dist/server/handlers/processors.cjs +57 -6
  244. package/dist/server/handlers/processors.cjs.map +1 -1
  245. package/dist/server/handlers/processors.d.ts +6 -0
  246. package/dist/server/handlers/processors.d.ts.map +1 -1
  247. package/dist/server/handlers/processors.js +57 -6
  248. package/dist/server/handlers/processors.js.map +1 -1
  249. package/dist/server/handlers/prompt-block-versions.cjs +2 -2
  250. package/dist/server/handlers/prompt-block-versions.d.ts +14 -0
  251. package/dist/server/handlers/prompt-block-versions.d.ts.map +1 -1
  252. package/dist/server/handlers/prompt-block-versions.js +2 -2
  253. package/dist/server/handlers/responses.cjs +1 -1
  254. package/dist/server/handlers/responses.d.ts +17 -11
  255. package/dist/server/handlers/responses.d.ts.map +1 -1
  256. package/dist/server/handlers/responses.js +1 -1
  257. package/dist/server/handlers/responses.storage.cjs +4 -3
  258. package/dist/server/handlers/responses.storage.cjs.map +1 -1
  259. package/dist/server/handlers/responses.storage.d.ts.map +1 -1
  260. package/dist/server/handlers/responses.storage.js +4 -3
  261. package/dist/server/handlers/responses.storage.js.map +1 -1
  262. package/dist/server/handlers/schedules.cjs +1 -1
  263. package/dist/server/handlers/schedules.d.ts +18 -0
  264. package/dist/server/handlers/schedules.d.ts.map +1 -1
  265. package/dist/server/handlers/schedules.js +1 -1
  266. package/dist/server/handlers/scorer-versions.cjs +2 -2
  267. package/dist/server/handlers/scorer-versions.d.ts +14 -0
  268. package/dist/server/handlers/scorer-versions.d.ts.map +1 -1
  269. package/dist/server/handlers/scorer-versions.js +2 -2
  270. package/dist/server/handlers/scores.cjs +1 -1
  271. package/dist/server/handlers/scores.d.ts +12 -0
  272. package/dist/server/handlers/scores.d.ts.map +1 -1
  273. package/dist/server/handlers/scores.js +1 -1
  274. package/dist/server/handlers/stored-agent-favorites.cjs +3 -3
  275. package/dist/server/handlers/stored-agent-favorites.d.ts +4 -0
  276. package/dist/server/handlers/stored-agent-favorites.d.ts.map +1 -1
  277. package/dist/server/handlers/stored-agent-favorites.js +3 -3
  278. package/dist/server/handlers/stored-agents.cjs +41 -3
  279. package/dist/server/handlers/stored-agents.cjs.map +1 -1
  280. package/dist/server/handlers/stored-agents.d.ts +14 -0
  281. package/dist/server/handlers/stored-agents.d.ts.map +1 -1
  282. package/dist/server/handlers/stored-agents.js +41 -3
  283. package/dist/server/handlers/stored-agents.js.map +1 -1
  284. package/dist/server/handlers/stored-mcp-clients.cjs +2 -2
  285. package/dist/server/handlers/stored-mcp-clients.d.ts +10 -0
  286. package/dist/server/handlers/stored-mcp-clients.d.ts.map +1 -1
  287. package/dist/server/handlers/stored-mcp-clients.js +2 -2
  288. package/dist/server/handlers/stored-prompt-blocks.cjs +2 -2
  289. package/dist/server/handlers/stored-prompt-blocks.d.ts +10 -0
  290. package/dist/server/handlers/stored-prompt-blocks.d.ts.map +1 -1
  291. package/dist/server/handlers/stored-prompt-blocks.js +2 -2
  292. package/dist/server/handlers/stored-scorers.cjs +2 -2
  293. package/dist/server/handlers/stored-scorers.d.ts +10 -0
  294. package/dist/server/handlers/stored-scorers.d.ts.map +1 -1
  295. package/dist/server/handlers/stored-scorers.js +2 -2
  296. package/dist/server/handlers/stored-skill-favorites.cjs +3 -3
  297. package/dist/server/handlers/stored-skill-favorites.d.ts +4 -0
  298. package/dist/server/handlers/stored-skill-favorites.d.ts.map +1 -1
  299. package/dist/server/handlers/stored-skill-favorites.js +3 -3
  300. package/dist/server/handlers/stored-skills.cjs +3 -3
  301. package/dist/server/handlers/stored-skills.d.ts +12 -0
  302. package/dist/server/handlers/stored-skills.d.ts.map +1 -1
  303. package/dist/server/handlers/stored-skills.js +3 -3
  304. package/dist/server/handlers/stored-workspaces.cjs +2 -2
  305. package/dist/server/handlers/stored-workspaces.d.ts +10 -0
  306. package/dist/server/handlers/stored-workspaces.d.ts.map +1 -1
  307. package/dist/server/handlers/stored-workspaces.js +2 -2
  308. package/dist/server/handlers/system.cjs +2 -2
  309. package/dist/server/handlers/system.d.ts +4 -0
  310. package/dist/server/handlers/system.d.ts.map +1 -1
  311. package/dist/server/handlers/system.js +2 -2
  312. package/dist/server/handlers/tool-providers.cjs +2 -2
  313. package/dist/server/handlers/tool-providers.d.ts +26 -0
  314. package/dist/server/handlers/tool-providers.d.ts.map +1 -1
  315. package/dist/server/handlers/tool-providers.js +2 -2
  316. package/dist/server/handlers/tools.cjs +2 -1
  317. package/dist/server/handlers/tools.d.ts +20 -0
  318. package/dist/server/handlers/tools.d.ts.map +1 -1
  319. package/dist/server/handlers/tools.js +1 -1
  320. package/dist/server/handlers/utils.cjs +1 -1
  321. package/dist/server/handlers/utils.js +1 -1
  322. package/dist/server/handlers/validate-agent-instructions.cjs +1 -1
  323. package/dist/server/handlers/validate-agent-instructions.js +1 -1
  324. package/dist/server/handlers/vector.cjs +1 -1
  325. package/dist/server/handlers/vector.d.ts +16 -0
  326. package/dist/server/handlers/vector.d.ts.map +1 -1
  327. package/dist/server/handlers/vector.js +1 -1
  328. package/dist/server/handlers/voice.cjs +1 -1
  329. package/dist/server/handlers/voice.d.ts.map +1 -1
  330. package/dist/server/handlers/voice.js +1 -1
  331. package/dist/server/handlers/workflow-builder.cjs +1 -1
  332. package/dist/server/handlers/workflow-builder.d.ts +4 -0
  333. package/dist/server/handlers/workflow-builder.d.ts.map +1 -1
  334. package/dist/server/handlers/workflow-builder.js +1 -1
  335. package/dist/server/handlers/workflows.cjs +2 -1
  336. package/dist/server/handlers/workflows.d.ts +57 -0
  337. package/dist/server/handlers/workflows.d.ts.map +1 -1
  338. package/dist/server/handlers/workflows.js +1 -1
  339. package/dist/server/handlers/workspace.cjs +1 -1
  340. package/dist/server/handlers/workspace.d.ts +103 -23
  341. package/dist/server/handlers/workspace.d.ts.map +1 -1
  342. package/dist/server/handlers/workspace.js +1 -1
  343. package/dist/server/handlers.cjs +17 -17
  344. package/dist/server/handlers.js +17 -17
  345. package/dist/server/mcp/capabilities.d.ts +25 -0
  346. package/dist/server/mcp/capabilities.d.ts.map +1 -0
  347. package/dist/server/mcp/catalogue.d.ts +76 -0
  348. package/dist/server/mcp/catalogue.d.ts.map +1 -0
  349. package/dist/server/mcp/config.d.ts +49 -0
  350. package/dist/server/mcp/config.d.ts.map +1 -0
  351. package/dist/server/mcp/descriptor.d.ts +40 -0
  352. package/dist/server/mcp/descriptor.d.ts.map +1 -0
  353. package/dist/server/mcp/oauth.d.ts +46 -0
  354. package/dist/server/mcp/oauth.d.ts.map +1 -0
  355. package/dist/server/mcp/result-size.d.ts +26 -0
  356. package/dist/server/mcp/result-size.d.ts.map +1 -0
  357. package/dist/server/mcp/route.d.ts +21 -0
  358. package/dist/server/mcp/route.d.ts.map +1 -0
  359. package/dist/server/mcp/schema.d.ts +13 -0
  360. package/dist/server/mcp/schema.d.ts.map +1 -0
  361. package/dist/server/mcp/toolsets/memory.d.ts +8 -0
  362. package/dist/server/mcp/toolsets/memory.d.ts.map +1 -0
  363. package/dist/server/mcp/toolsets/observability.d.ts +4 -0
  364. package/dist/server/mcp/toolsets/observability.d.ts.map +1 -0
  365. package/dist/server/mcp/toolsets/stored-agents.d.ts +8 -0
  366. package/dist/server/mcp/toolsets/stored-agents.d.ts.map +1 -0
  367. package/dist/server/schemas/index.cjs +8 -9
  368. package/dist/server/schemas/index.js +2 -3
  369. package/dist/server/server-adapter/api-schema-manifest.d.ts +1 -1
  370. package/dist/server/server-adapter/index.cjs +45 -1831
  371. package/dist/server/server-adapter/index.d.ts +126 -3
  372. package/dist/server/server-adapter/index.d.ts.map +1 -1
  373. package/dist/server/server-adapter/index.js +7 -1805
  374. package/dist/server/server-adapter/openapi-utils.d.ts +2 -2
  375. package/dist/server/server-adapter/openapi-utils.d.ts.map +1 -1
  376. package/dist/server/server-adapter/routes/a2a.d.ts +4 -0
  377. package/dist/server/server-adapter/routes/a2a.d.ts.map +1 -1
  378. package/dist/server/server-adapter/routes/agent-builder.d.ts +32 -0
  379. package/dist/server/server-adapter/routes/agent-builder.d.ts.map +1 -1
  380. package/dist/server/server-adapter/routes/channels.d.ts +10 -0
  381. package/dist/server/server-adapter/routes/channels.d.ts.map +1 -1
  382. package/dist/server/server-adapter/routes/conversations.d.ts +11 -3
  383. package/dist/server/server-adapter/routes/conversations.d.ts.map +1 -1
  384. package/dist/server/server-adapter/routes/datasets.d.ts +66 -0
  385. package/dist/server/server-adapter/routes/datasets.d.ts.map +1 -1
  386. package/dist/server/server-adapter/routes/editor-builder.d.ts +20 -0
  387. package/dist/server/server-adapter/routes/editor-builder.d.ts.map +1 -1
  388. package/dist/server/server-adapter/routes/index.d.ts +26 -1
  389. package/dist/server/server-adapter/routes/index.d.ts.map +1 -1
  390. package/dist/server/server-adapter/routes/knowledge.d.ts +18 -0
  391. package/dist/server/server-adapter/routes/knowledge.d.ts.map +1 -1
  392. package/dist/server/server-adapter/routes/legacy.d.ts +8 -0
  393. package/dist/server/server-adapter/routes/legacy.d.ts.map +1 -1
  394. package/dist/server/server-adapter/routes/logs.d.ts +6 -0
  395. package/dist/server/server-adapter/routes/logs.d.ts.map +1 -1
  396. package/dist/server/server-adapter/routes/mcp.d.ts +37 -1
  397. package/dist/server/server-adapter/routes/mcp.d.ts.map +1 -1
  398. package/dist/server/server-adapter/routes/memory.d.ts +52 -0
  399. package/dist/server/server-adapter/routes/memory.d.ts.map +1 -1
  400. package/dist/server/server-adapter/routes/observability.d.ts +92 -0
  401. package/dist/server/server-adapter/routes/observability.d.ts.map +1 -1
  402. package/dist/server/server-adapter/routes/processor-providers.d.ts +4 -0
  403. package/dist/server/server-adapter/routes/processor-providers.d.ts.map +1 -1
  404. package/dist/server/server-adapter/routes/processors.d.ts +6 -0
  405. package/dist/server/server-adapter/routes/processors.d.ts.map +1 -1
  406. package/dist/server/server-adapter/routes/responses.d.ts +6 -0
  407. package/dist/server/server-adapter/routes/responses.d.ts.map +1 -1
  408. package/dist/server/server-adapter/routes/route-builder.d.ts +5 -1
  409. package/dist/server/server-adapter/routes/route-builder.d.ts.map +1 -1
  410. package/dist/server/server-adapter/routes/scorers.d.ts +12 -0
  411. package/dist/server/server-adapter/routes/scorers.d.ts.map +1 -1
  412. package/dist/server/server-adapter/routes/stored-mcp-clients.d.ts +24 -0
  413. package/dist/server/server-adapter/routes/stored-mcp-clients.d.ts.map +1 -1
  414. package/dist/server/server-adapter/routes/stored-prompt-blocks.d.ts +24 -0
  415. package/dist/server/server-adapter/routes/stored-prompt-blocks.d.ts.map +1 -1
  416. package/dist/server/server-adapter/routes/stored-scorers.d.ts +24 -0
  417. package/dist/server/server-adapter/routes/stored-scorers.d.ts.map +1 -1
  418. package/dist/server/server-adapter/routes/stored-skills.d.ts +16 -0
  419. package/dist/server/server-adapter/routes/stored-skills.d.ts.map +1 -1
  420. package/dist/server/server-adapter/routes/stored-workspaces.d.ts +10 -0
  421. package/dist/server/server-adapter/routes/stored-workspaces.d.ts.map +1 -1
  422. package/dist/server/server-adapter/routes/system.d.ts +4 -0
  423. package/dist/server/server-adapter/routes/system.d.ts.map +1 -1
  424. package/dist/server/server-adapter/routes/tool-providers.d.ts +26 -0
  425. package/dist/server/server-adapter/routes/tool-providers.d.ts.map +1 -1
  426. package/dist/server/server-adapter/routes/tools.d.ts +6 -0
  427. package/dist/server/server-adapter/routes/tools.d.ts.map +1 -1
  428. package/dist/server/server-adapter/routes/vectors.d.ts +16 -0
  429. package/dist/server/server-adapter/routes/vectors.d.ts.map +1 -1
  430. package/dist/server/server-adapter/routes/workflows.d.ts +50 -0
  431. package/dist/server/server-adapter/routes/workflows.d.ts.map +1 -1
  432. package/dist/server/server-adapter/routes/workspace.d.ts +42 -0
  433. package/dist/server/server-adapter/routes/workspace.d.ts.map +1 -1
  434. package/dist/server-adapter-B7dLE5si.cjs +2386 -0
  435. package/dist/server-adapter-B7dLE5si.cjs.map +1 -0
  436. package/dist/server-adapter-BywLWVKp.js +2189 -0
  437. package/dist/server-adapter-BywLWVKp.js.map +1 -0
  438. package/dist/{tools-Daot5Zgz.cjs → tools-CawMeeZg.cjs} +71 -29
  439. package/dist/tools-CawMeeZg.cjs.map +1 -0
  440. package/dist/{tools-BJFq9JKF.js → tools-oHRh4msa.js} +65 -29
  441. package/dist/tools-oHRh4msa.js.map +1 -0
  442. package/dist/{utils-yedETkNk.js → utils-BfySxdfF.js} +3 -3
  443. package/dist/{utils-yedETkNk.js.map → utils-BfySxdfF.js.map} +1 -1
  444. package/dist/{utils-BXEJ6FZC.cjs → utils-DFhesFfA.cjs} +2 -2
  445. package/dist/{utils-BXEJ6FZC.cjs.map → utils-DFhesFfA.cjs.map} +1 -1
  446. package/dist/{utils-DptI_ERr.cjs → utils-Dn_OA_6N.cjs} +6 -6
  447. package/dist/{utils-DptI_ERr.cjs.map → utils-Dn_OA_6N.cjs.map} +1 -1
  448. package/dist/{utils-CTYtskHa.js → utils-Dv1D6ob-.js} +2 -2
  449. package/dist/{utils-CTYtskHa.js.map → utils-Dv1D6ob-.js.map} +1 -1
  450. package/dist/{vector-CZ26vo6u.js → vector-Bz-glead.js} +2 -2
  451. package/dist/{vector-CZ26vo6u.js.map → vector-Bz-glead.js.map} +1 -1
  452. package/dist/{vector-DBe45tnv.cjs → vector-DIFU_fwU.cjs} +2 -2
  453. package/dist/{vector-DBe45tnv.cjs.map → vector-DIFU_fwU.cjs.map} +1 -1
  454. package/dist/voice-C6bAqs79.js +42 -0
  455. package/dist/voice-C6bAqs79.js.map +1 -0
  456. package/dist/{voice-CBbxcsCM.cjs → voice-Dk0O5mVD.cjs} +29 -9
  457. package/dist/voice-Dk0O5mVD.cjs.map +1 -0
  458. package/dist/{workflow-builder-CkrdTcoM.cjs → workflow-builder-BPUjAdaC.cjs} +5 -5
  459. package/dist/{workflow-builder-CkrdTcoM.cjs.map → workflow-builder-BPUjAdaC.cjs.map} +1 -1
  460. package/dist/{workflow-builder-C5ufahUw.js → workflow-builder-D2fwGsLw.js} +5 -5
  461. package/dist/{workflow-builder-C5ufahUw.js.map → workflow-builder-D2fwGsLw.js.map} +1 -1
  462. package/dist/{workflows-C_Mqj_80.js → workflows-B-QJ0Tnv.js} +38 -7
  463. package/dist/workflows-B-QJ0Tnv.js.map +1 -0
  464. package/dist/{workflows-B5uWFrJ1.cjs → workflows-CwkEHIKW.cjs} +43 -6
  465. package/dist/workflows-CwkEHIKW.cjs.map +1 -0
  466. package/dist/{workspace-BwlPQO3M.js → workspace-CbTB2svI.js} +99 -41
  467. package/dist/workspace-CbTB2svI.js.map +1 -0
  468. package/dist/{workspace-CD9pQ61P.cjs → workspace-CsPtSXQd.cjs} +99 -41
  469. package/dist/workspace-CsPtSXQd.cjs.map +1 -0
  470. package/package.json +14 -7
  471. package/dist/a2a-DIcMx6x-.cjs.map +0 -1
  472. package/dist/a2a-DTTGA2Xg.js.map +0 -1
  473. package/dist/agents-BCgiMlDq.js.map +0 -1
  474. package/dist/agents-CTgjTASj.js.map +0 -1
  475. package/dist/agents-CjcvdF2e.cjs.map +0 -1
  476. package/dist/agents-DjpBmwhv.cjs.map +0 -1
  477. package/dist/api-schema-manifest-CJz_hWjy.cjs.map +0 -1
  478. package/dist/api-schema-manifest-CkB5OGjC.js.map +0 -1
  479. package/dist/constants-CXAvBYcz.js.map +0 -1
  480. package/dist/constants-DMg8hUOR.cjs.map +0 -1
  481. package/dist/conversations-BFqmDglO.cjs.map +0 -1
  482. package/dist/conversations-BkX00xDs.js.map +0 -1
  483. package/dist/dist-4NnakSte.js +0 -1
  484. package/dist/editor-builder-C4H2l6tz.js.map +0 -1
  485. package/dist/editor-builder-Cqw1npOK.cjs.map +0 -1
  486. package/dist/helpers-0LJI4DxR.cjs.map +0 -1
  487. package/dist/helpers-C9QZKOhz.js.map +0 -1
  488. package/dist/memory-BRE3ofvI.cjs.map +0 -1
  489. package/dist/memory-Dw7xG5nn.js.map +0 -1
  490. package/dist/observability-C2HjrCpw.cjs.map +0 -1
  491. package/dist/observability-Ca3TxxY7.js.map +0 -1
  492. package/dist/observability-new-endpoints-B3X2L7cj.js.map +0 -1
  493. package/dist/observability-new-endpoints-DnzWjscD.cjs.map +0 -1
  494. package/dist/plans-D_GKFz2x.js.map +0 -1
  495. package/dist/plans-_nR8lqgD.cjs.map +0 -1
  496. package/dist/responses-C_OEJoxU.js.map +0 -1
  497. package/dist/responses-CdWbS4jA.cjs.map +0 -1
  498. package/dist/routes-CQZ0Z77B.cjs.map +0 -1
  499. package/dist/routes-CqzWkepR.js.map +0 -1
  500. package/dist/routes-CtGp_lBn.cjs +0 -523
  501. package/dist/routes-CtGp_lBn.cjs.map +0 -1
  502. package/dist/routes-MRZFTKei.js +0 -446
  503. package/dist/routes-MRZFTKei.js.map +0 -1
  504. package/dist/schedules-BQvnAe1j.cjs.map +0 -1
  505. package/dist/schedules-BcAIELfB.js.map +0 -1
  506. package/dist/scores-DEvPN0kz.cjs.map +0 -1
  507. package/dist/scores-Dm0yu1Pt.js.map +0 -1
  508. package/dist/server/server-adapter/index.cjs.map +0 -1
  509. package/dist/server/server-adapter/index.js.map +0 -1
  510. package/dist/tools-BJFq9JKF.js.map +0 -1
  511. package/dist/tools-Daot5Zgz.cjs.map +0 -1
  512. package/dist/voice-CBbxcsCM.cjs.map +0 -1
  513. package/dist/voice-CzFWhWPJ.js +0 -22
  514. package/dist/voice-CzFWhWPJ.js.map +0 -1
  515. package/dist/workflows-B5uWFrJ1.cjs.map +0 -1
  516. package/dist/workflows-C_Mqj_80.js.map +0 -1
  517. package/dist/workspace-BwlPQO3M.js.map +0 -1
  518. package/dist/workspace-CD9pQ61P.cjs.map +0 -1
  519. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/_types/@internal_ai-sdk-v4@0.0.95/dist/index.d.ts +0 -0
  520. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/_types/@internal_ai-sdk-v5@0.0.95/dist/index.d.ts +0 -0
  521. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/_types/@internal_ai-v6@0.0.95/dist/index.d.ts +0 -0
  522. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/_types/@standard-schema_spec@1.1.0/dist/index.d.ts +0 -0
  523. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/_types/@types_json-schema@7.0.15/index.d.ts +0 -0
  524. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/index.d.ts +0 -0
  525. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/null-to-undefined.d.ts +0 -0
  526. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/provider-compats/anthropic.d.ts +0 -0
  527. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/provider-compats/deepseek.d.ts +0 -0
  528. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/provider-compats/google.d.ts +0 -0
  529. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/provider-compats/meta.d.ts +0 -0
  530. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/provider-compats/openai-reasoning.d.ts +0 -0
  531. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/provider-compats/openai.d.ts +0 -0
  532. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/schema-compatibility-v3.d.ts +0 -0
  533. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/schema-compatibility-v4.d.ts +0 -0
  534. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/schema-compatibility.d.ts +0 -0
  535. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/schema.d.ts +0 -0
  536. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/schema.types.d.ts +0 -0
  537. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/standard-schema/standard-schema.d.ts +0 -0
  538. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/standard-schema/standard-schema.types.d.ts +0 -0
  539. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/standard-schema-compat.d.ts +0 -0
  540. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/types.d.ts +0 -0
  541. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/utils.d.ts +0 -0
  542. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/dist/zod-to-json.d.ts +0 -0
  543. /package/dist/_types/{@mastra_schema-compat@1.4.0-alpha.1 → @mastra_schema-compat@1.4.0-alpha.2}/package.json +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"editor-builder-xQmDgVgJ.cjs","names":["z","providerSchema"],"sources":["../src/server/schemas/editor-builder.ts"],"sourcesContent":["import { z } from 'zod/v4';\nimport { providerSchema } from './agents';\n\n/**\n * Agent feature flags for the builder.\n *\n * Wire format: each key is an optional boolean. The server normalizes admin\n * input via `resolveAgentFeatures` (default-on semantics): any omitted key\n * resolves to `true`; admins opt out by setting a key to `false`. The\n * `GET /editor/builder/settings` response always carries a fully-resolved\n * object — clients should still use strict `=== true` checks.\n *\n * Special cases:\n * - `browser`: only resolves to `true` when `configuration.agent.browser` is\n * provided. Omitted with no config ⇒ silently `false` (no warning).\n * Explicit `true` with no config ⇒ warns and downgrades to `false`.\n */\nexport const agentFeaturesSchema = z.object({\n tools: z.boolean().optional(),\n agents: z.boolean().optional(),\n workflows: z.boolean().optional(),\n scorers: z.boolean().optional(),\n skills: z.boolean().optional(),\n memory: z.boolean().optional(),\n variables: z.boolean().optional(),\n favorites: z.boolean().optional(),\n avatarUpload: z.boolean().optional(),\n browser: z.boolean().optional(),\n /**\n * Whether the model picker is visible in the Agent Builder.\n * Omitted ⇒ picker visible (default-on). Explicit `false` ⇒ picker hidden\n * (locked mode); `models.default` is required and applied.\n */\n model: z.boolean().optional(),\n});\n\n/**\n * Allowlist + default-model entries for {@link agentModelsSchema}.\n *\n * Four standalone schemas (known × custom × entry × default) joined with `z.union`.\n * The schema does NOT validate `provider` against the runtime registry — invalid strings\n * surface as warnings during Phase 4 config validation.\n *\n * NOTE: `z.union(...).extend()` does not exist; that's why these are separate schemas.\n */\n// All four schemas are `.strict()` so typos like `modelID` or `Provider` are\n// rejected up-front instead of silently widening the policy.\nconst knownProviderEntrySchema = z\n .object({\n provider: z.string().min(1),\n modelId: z.string().min(1).optional(),\n })\n .strict();\n\nconst customProviderEntrySchema = z\n .object({\n kind: z.literal('custom'),\n provider: z.string().min(1),\n modelId: z.string().min(1).optional(),\n })\n .strict();\n\nconst knownDefaultModelEntrySchema = z\n .object({\n provider: z.string().min(1),\n modelId: z.string().min(1),\n })\n .strict();\n\nconst customDefaultModelEntrySchema = z\n .object({\n kind: z.literal('custom'),\n provider: z.string().min(1),\n modelId: z.string().min(1),\n })\n .strict();\n\n// Custom-tagged variants must come first so the discriminator (`kind: 'custom'`)\n// wins over the more permissive known-provider schemas. Otherwise the union\n// silently drops the `kind` field on matching inputs.\nexport const providerModelEntrySchema = z.union([customProviderEntrySchema, knownProviderEntrySchema]);\nexport const defaultModelEntrySchema = z.union([customDefaultModelEntrySchema, knownDefaultModelEntrySchema]);\n\n/**\n * Admin-controlled model allowlist + default for the Agent Builder.\n */\nexport const agentModelsSchema = z.object({\n allowed: z.array(providerModelEntrySchema).optional(),\n default: defaultModelEntrySchema.optional(),\n});\n\n/**\n * Admin-controlled allowlist for one of the builder pickers (tools/agents/workflows).\n *\n * Semantics:\n * - omitted ⇒ unrestricted (all registered IDs shown in the picker).\n * - `allowed: []` ⇒ empty picker (explicit lockdown).\n * - `allowed: [...ids]` ⇒ only the listed IDs are shown.\n */\nexport const pickerAllowlistSchema = z\n .object({\n allowed: z.array(z.string()).optional(),\n })\n .strict();\n\n/**\n * Agent configuration (pinned, non-overridable settings).\n *\n * Known structured field: `models` (Phase 1 contracts).\n * Other keys flow through unchanged for forward compatibility.\n */\nexport const agentConfigurationSchema = z\n .object({\n models: agentModelsSchema.optional(),\n tools: pickerAllowlistSchema.optional(),\n agents: pickerAllowlistSchema.optional(),\n workflows: pickerAllowlistSchema.optional(),\n })\n .catchall(z.unknown());\n\n/**\n * Resolved picker visibility returned in `BuilderSettingsResponse`.\n *\n * Per kind:\n * - `null` ⇒ unrestricted (show all registered entries).\n * - `string[]` ⇒ explicit allowlist (may be empty to show none).\n */\nexport const builderPickerSchema = z.object({\n visibleTools: z.array(z.string()).nullable(),\n visibleAgents: z.array(z.string()).nullable(),\n visibleWorkflows: z.array(z.string()).nullable(),\n});\n\n/**\n * Derived `BuilderModelPolicy`. Server-owned shape so the playground hook is a\n * thin selector and the UI never re-derives policy from `features` / `configuration`.\n *\n * Mirrors `BuilderModelPolicy` from `@mastra/core/agent-builder/ee`:\n * - `active: false` ⇒ all other fields ignored.\n * - `active: true` + `pickerVisible: false` (locked) ⇒ `default` set in valid configs.\n * - `allowed`/`default` are passed through verbatim when present.\n */\nexport const builderModelPolicySchema = z.object({\n active: z.boolean(),\n pickerVisible: z.boolean().optional(),\n allowed: z.array(providerModelEntrySchema).optional(),\n default: defaultModelEntrySchema.optional(),\n});\n\n/**\n * Response schema for GET /editor/builder/settings\n */\nexport const builderSettingsResponseSchema = z.object({\n enabled: z.boolean(),\n features: z\n .object({\n agent: agentFeaturesSchema.optional(),\n })\n .optional(),\n configuration: z\n .object({\n agent: agentConfigurationSchema.optional(),\n })\n .optional(),\n modelPolicy: builderModelPolicySchema.optional(),\n /**\n * Resolved picker visibility for tools/agents/workflows. Always present when\n * the builder is enabled. Omitted when the builder is disabled.\n */\n picker: builderPickerSchema.optional(),\n /**\n * Non-fatal warnings produced by `EditorAgentBuilder`'s constructor-time\n * validation (e.g. allowlist entries with unknown provider strings, or\n * picker allowlist entries that don't match a registered ID). UI surfaces\n * these as a banner in the Builder admin view.\n */\n modelPolicyWarnings: z.array(z.string()).optional(),\n});\n\n/**\n * Infrastructure status response for Agent Builder admin diagnostics.\n *\n * Reports the Agent Builder-specific primitive configuration plus lightweight\n * runtime resolution state where useful.\n */\nexport const infrastructureStatusResponseSchema = z.object({\n channels: z.object({\n providers: z.array(\n z.object({\n id: z.string(),\n name: z.string(),\n isConfigured: z.boolean(),\n routeCount: z.number(),\n }),\n ),\n }),\n browser: z.object({\n type: z.string().nullable(),\n provider: z.string().nullable(),\n env: z.string().nullable(),\n registered: z.boolean(),\n availableProviders: z.array(z.string()),\n config: z.array(z.object({ key: z.string(), value: z.string() })),\n }),\n workspace: z.object({\n type: z.string().nullable(),\n workspaceId: z.string().nullable(),\n name: z.string().nullable(),\n source: z.string().nullable(),\n registered: z.boolean(),\n hasFilesystem: z.boolean(),\n hasSandbox: z.boolean(),\n filesystemProvider: z.string().nullable(),\n sandboxProvider: z.string().nullable(),\n config: z.array(z.object({ key: z.string(), value: z.string() })),\n }),\n registries: z.object({\n skillsSh: z.object({\n enabled: z.boolean(),\n }),\n }),\n});\n\n/**\n * Response schema for GET /editor/builder/models/available.\n *\n * Same provider shape as GET /agents/providers, but each provider's `models`\n * list is already filtered by the active builder model policy (server applies\n * the EE allowlist). Providers with no allowed models are omitted entirely so\n * the Studio model picker can render the response verbatim.\n */\nexport const builderAvailableModelsResponseSchema = z.object({\n providers: z.array(providerSchema),\n});\n\nexport type BuilderAvailableModelsResponse = z.infer<typeof builderAvailableModelsResponseSchema>;\n\nexport type InfrastructureStatus = z.infer<typeof infrastructureStatusResponseSchema>;\n\nexport type AgentFeatures = z.infer<typeof agentFeaturesSchema>;\nexport type AgentConfiguration = z.infer<typeof agentConfigurationSchema>;\nexport type BuilderSettingsResponse = z.infer<typeof builderSettingsResponseSchema>;\nexport type ProviderModelEntrySchema = z.infer<typeof providerModelEntrySchema>;\nexport type DefaultModelEntrySchema = z.infer<typeof defaultModelEntrySchema>;\nexport type AgentModelsSchema = z.infer<typeof agentModelsSchema>;\nexport type BuilderModelPolicySchema = z.infer<typeof builderModelPolicySchema>;\nexport type PickerAllowlistSchema = z.infer<typeof pickerAllowlistSchema>;\nexport type BuilderPickerSchema = z.infer<typeof builderPickerSchema>;\n"],"mappings":";;;;;;;;;;;;;;;;;AAiBA,MAAa,sBAAsBA,OAAAA,EAAE,OAAO;CAC1C,OAAOA,OAAAA,EAAE,QAAQ,CAAC,CAAC,SAAS;CAC5B,QAAQA,OAAAA,EAAE,QAAQ,CAAC,CAAC,SAAS;CAC7B,WAAWA,OAAAA,EAAE,QAAQ,CAAC,CAAC,SAAS;CAChC,SAASA,OAAAA,EAAE,QAAQ,CAAC,CAAC,SAAS;CAC9B,QAAQA,OAAAA,EAAE,QAAQ,CAAC,CAAC,SAAS;CAC7B,QAAQA,OAAAA,EAAE,QAAQ,CAAC,CAAC,SAAS;CAC7B,WAAWA,OAAAA,EAAE,QAAQ,CAAC,CAAC,SAAS;CAChC,WAAWA,OAAAA,EAAE,QAAQ,CAAC,CAAC,SAAS;CAChC,cAAcA,OAAAA,EAAE,QAAQ,CAAC,CAAC,SAAS;CACnC,SAASA,OAAAA,EAAE,QAAQ,CAAC,CAAC,SAAS;;;;;;CAM9B,OAAOA,OAAAA,EAAE,QAAQ,CAAC,CAAC,SAAS;AAC9B,CAAC;;;;;;;;;;AAaD,MAAM,2BAA2BA,OAAAA,EAC9B,OAAO;CACN,UAAUA,OAAAA,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;CAC1B,SAASA,OAAAA,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;AACtC,CAAC,CAAC,CACD,OAAO;AAEV,MAAM,4BAA4BA,OAAAA,EAC/B,OAAO;CACN,MAA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AA,EAAE,MAAMC,eAAAA,cAAc,EACnC,CAAC"}
1
+ {"version":3,"file":"editor-builder-eF2IetF2.cjs","names":["z","providerSchema"],"sources":["../src/server/schemas/editor-builder.ts"],"sourcesContent":["import { z } from 'zod/v4';\nimport { providerSchema } from './agents';\n\n/**\n * Agent feature flags for the builder.\n *\n * Wire format: each key is an optional boolean. The server normalizes admin\n * input via `resolveAgentFeatures` (default-on semantics): any omitted key\n * resolves to `true`; admins opt out by setting a key to `false`. The\n * `GET /editor/builder/settings` response always carries a fully-resolved\n * object — clients should still use strict `=== true` checks.\n *\n * Special cases:\n * - `browser`: only resolves to `true` when `configuration.agent.browser` is\n * provided. Omitted with no config ⇒ silently `false` (no warning).\n * Explicit `true` with no config ⇒ warns and downgrades to `false`.\n */\nexport const agentFeaturesSchema = z.object({\n tools: z.boolean().optional(),\n agents: z.boolean().optional(),\n workflows: z.boolean().optional(),\n scorers: z.boolean().optional(),\n skills: z.boolean().optional(),\n memory: z.boolean().optional(),\n variables: z.boolean().optional(),\n favorites: z.boolean().optional(),\n avatarUpload: z.boolean().optional(),\n browser: z.boolean().optional(),\n /**\n * Whether the model picker is visible in the Agent Builder.\n * Omitted ⇒ picker visible (default-on). Explicit `false` ⇒ picker hidden\n * (locked mode); `models.default` is required and applied.\n */\n model: z.boolean().optional(),\n});\n\n/**\n * Allowlist + default-model entries for {@link agentModelsSchema}.\n *\n * Four standalone schemas (known × custom × entry × default) joined with `z.union`.\n * The schema does NOT validate `provider` against the runtime registry — invalid strings\n * surface as warnings during Phase 4 config validation.\n *\n * NOTE: `z.union(...).extend()` does not exist; that's why these are separate schemas.\n */\n// All four schemas are `.strict()` so typos like `modelID` or `Provider` are\n// rejected up-front instead of silently widening the policy.\nconst knownProviderEntrySchema = z\n .object({\n provider: z.string().min(1),\n modelId: z.string().min(1).optional(),\n })\n .strict();\n\nconst customProviderEntrySchema = z\n .object({\n kind: z.literal('custom'),\n provider: z.string().min(1),\n modelId: z.string().min(1).optional(),\n })\n .strict();\n\nconst knownDefaultModelEntrySchema = z\n .object({\n provider: z.string().min(1),\n modelId: z.string().min(1),\n })\n .strict();\n\nconst customDefaultModelEntrySchema = z\n .object({\n kind: z.literal('custom'),\n provider: z.string().min(1),\n modelId: z.string().min(1),\n })\n .strict();\n\n// Custom-tagged variants must come first so the discriminator (`kind: 'custom'`)\n// wins over the more permissive known-provider schemas. Otherwise the union\n// silently drops the `kind` field on matching inputs.\nexport const providerModelEntrySchema = z.union([customProviderEntrySchema, knownProviderEntrySchema]);\nexport const defaultModelEntrySchema = z.union([customDefaultModelEntrySchema, knownDefaultModelEntrySchema]);\n\n/**\n * Admin-controlled model allowlist + default for the Agent Builder.\n */\nexport const agentModelsSchema = z.object({\n allowed: z.array(providerModelEntrySchema).optional(),\n default: defaultModelEntrySchema.optional(),\n});\n\n/**\n * Admin-controlled allowlist for one of the builder pickers (tools/agents/workflows).\n *\n * Semantics:\n * - omitted ⇒ unrestricted (all registered IDs shown in the picker).\n * - `allowed: []` ⇒ empty picker (explicit lockdown).\n * - `allowed: [...ids]` ⇒ only the listed IDs are shown.\n */\nexport const pickerAllowlistSchema = z\n .object({\n allowed: z.array(z.string()).optional(),\n })\n .strict();\n\n/**\n * Agent configuration (pinned, non-overridable settings).\n *\n * Known structured field: `models` (Phase 1 contracts).\n * Other keys flow through unchanged for forward compatibility.\n */\nexport const agentConfigurationSchema = z\n .object({\n models: agentModelsSchema.optional(),\n tools: pickerAllowlistSchema.optional(),\n agents: pickerAllowlistSchema.optional(),\n workflows: pickerAllowlistSchema.optional(),\n })\n .catchall(z.unknown());\n\n/**\n * Resolved picker visibility returned in `BuilderSettingsResponse`.\n *\n * Per kind:\n * - `null` ⇒ unrestricted (show all registered entries).\n * - `string[]` ⇒ explicit allowlist (may be empty to show none).\n */\nexport const builderPickerSchema = z.object({\n visibleTools: z.array(z.string()).nullable(),\n visibleAgents: z.array(z.string()).nullable(),\n visibleWorkflows: z.array(z.string()).nullable(),\n});\n\n/**\n * Derived `BuilderModelPolicy`. Server-owned shape so the playground hook is a\n * thin selector and the UI never re-derives policy from `features` / `configuration`.\n *\n * Mirrors `BuilderModelPolicy` from `@mastra/core/agent-builder/ee`:\n * - `active: false` ⇒ all other fields ignored.\n * - `active: true` + `pickerVisible: false` (locked) ⇒ `default` set in valid configs.\n * - `allowed`/`default` are passed through verbatim when present.\n */\nexport const builderModelPolicySchema = z.object({\n active: z.boolean(),\n pickerVisible: z.boolean().optional(),\n allowed: z.array(providerModelEntrySchema).optional(),\n default: defaultModelEntrySchema.optional(),\n});\n\n/**\n * Response schema for GET /editor/builder/settings\n */\nexport const builderSettingsResponseSchema = z.object({\n enabled: z.boolean(),\n features: z\n .object({\n agent: agentFeaturesSchema.optional(),\n })\n .optional(),\n configuration: z\n .object({\n agent: agentConfigurationSchema.optional(),\n })\n .optional(),\n modelPolicy: builderModelPolicySchema.optional(),\n /**\n * Resolved picker visibility for tools/agents/workflows. Always present when\n * the builder is enabled. Omitted when the builder is disabled.\n */\n picker: builderPickerSchema.optional(),\n /**\n * Non-fatal warnings produced by `EditorAgentBuilder`'s constructor-time\n * validation (e.g. allowlist entries with unknown provider strings, or\n * picker allowlist entries that don't match a registered ID). UI surfaces\n * these as a banner in the Builder admin view.\n */\n modelPolicyWarnings: z.array(z.string()).optional(),\n});\n\n/**\n * Infrastructure status response for Agent Builder admin diagnostics.\n *\n * Reports the Agent Builder-specific primitive configuration plus lightweight\n * runtime resolution state where useful.\n */\nexport const infrastructureStatusResponseSchema = z.object({\n channels: z.object({\n providers: z.array(\n z.object({\n id: z.string(),\n name: z.string(),\n isConfigured: z.boolean(),\n routeCount: z.number(),\n }),\n ),\n }),\n browser: z.object({\n type: z.string().nullable(),\n provider: z.string().nullable(),\n env: z.string().nullable(),\n registered: z.boolean(),\n availableProviders: z.array(z.string()),\n config: z.array(z.object({ key: z.string(), value: z.string() })),\n }),\n workspace: z.object({\n type: z.string().nullable(),\n workspaceId: z.string().nullable(),\n name: z.string().nullable(),\n source: z.string().nullable(),\n registered: z.boolean(),\n hasFilesystem: z.boolean(),\n hasSandbox: z.boolean(),\n filesystemProvider: z.string().nullable(),\n sandboxProvider: z.string().nullable(),\n config: z.array(z.object({ key: z.string(), value: z.string() })),\n }),\n registries: z.object({\n skillsSh: z.object({\n enabled: z.boolean(),\n }),\n }),\n});\n\n/**\n * Response schema for GET /editor/builder/models/available.\n *\n * Same provider shape as GET /agents/providers, but each provider's `models`\n * list is already filtered by the active builder model policy (server applies\n * the EE allowlist). Providers with no allowed models are omitted entirely so\n * the Studio model picker can render the response verbatim.\n */\nexport const builderAvailableModelsResponseSchema = z.object({\n providers: z.array(providerSchema),\n});\n\nexport type BuilderAvailableModelsResponse = z.infer<typeof builderAvailableModelsResponseSchema>;\n\nexport type InfrastructureStatus = z.infer<typeof infrastructureStatusResponseSchema>;\n\nexport type AgentFeatures = z.infer<typeof agentFeaturesSchema>;\nexport type AgentConfiguration = z.infer<typeof agentConfigurationSchema>;\nexport type BuilderSettingsResponse = z.infer<typeof builderSettingsResponseSchema>;\nexport type ProviderModelEntrySchema = z.infer<typeof providerModelEntrySchema>;\nexport type DefaultModelEntrySchema = z.infer<typeof defaultModelEntrySchema>;\nexport type AgentModelsSchema = z.infer<typeof agentModelsSchema>;\nexport type BuilderModelPolicySchema = z.infer<typeof builderModelPolicySchema>;\nexport type PickerAllowlistSchema = z.infer<typeof pickerAllowlistSchema>;\nexport type BuilderPickerSchema = z.infer<typeof builderPickerSchema>;\n"],"mappings":";;;;;;;;;;;;;;;;;AAiBA,MAAa,sBAAsBA,OAAAA,EAAE,OAAO;CAC1C,OAAOA,OAAAA,EAAE,QAAQ,CAAC,CAAC,SAAS;CAC5B,QAAQA,OAAAA,EAAE,QAAQ,CAAC,CAAC,SAAS;CAC7B,WAAWA,OAAAA,EAAE,QAAQ,CAAC,CAAC,SAAS;CAChC,SAASA,OAAAA,EAAE,QAAQ,CAAC,CAAC,SAAS;CAC9B,QAAQA,OAAAA,EAAE,QAAQ,CAAC,CAAC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B,QAAQA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;EAC5B,YAAYA,OAAAA,EAAE,QAAQ;EACtB,eAAeA,OAAAA,EAAE,QAAQ;EACzB,YAAYA,OAAAA,EAAE,QAAQ;EACtB,oBAAoBA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;EACxC,iBAAiBA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;EACrC,QAAQA,OAAAA,EAAE,MAAMA,OAAAA,EAAE,OAAO;GAAE,KAAKA,OAAAA,EAAE,OAAO;GAAG,OAAOA,OAAAA,EAAE,OAAO;EAAE,CAAC,CAAC;CAClE,CAAC;CACD,YAAYA,OAAAA,EAAE,OAAO,EACnB,UAAUA,OAAAA,EAAE,OAAO,EACjB,SAASA,OAAAA,EAAE,QAAQ,EACrB,CAAC,EACH,CAAC;AACH,CAAC;;;;;;;;;AAUD,MAAa,uCAAuCA,OAAAA,EAAE,OAAO,EAC3D,WAAWA,OAAAA,EAAE,MAAMC,eAAAA,cAAc,EACnC,CAAC"}
@@ -1,6 +1,6 @@
1
- import { d as MASTRA_USER_PERMISSIONS_KEY, f as MASTRA_USER_ROLES_KEY, n as MASTRA_AUTH_TOKEN_KEY, s as MASTRA_RESOURCE_ID_KEY, t as MASTRA_AUTH_MODE_KEY, u as MASTRA_USER_KEY } from "./constants-CXAvBYcz.js";
1
+ import { c as MASTRA_RESOURCE_ID_KEY, d as MASTRA_USER_KEY, f as MASTRA_USER_PERMISSIONS_KEY, n as MASTRA_AUTH_TOKEN_KEY, o as MASTRA_NORMALIZED_USER_KEY, p as MASTRA_USER_ROLES_KEY, t as MASTRA_AUTH_MODE_KEY } from "./constants-0xZU_h4R.js";
2
2
  import { t as HTTPException } from "./http-exception-CzaWkxMl.js";
3
- import { CompositeAuth } from "@mastra/core/server";
3
+ import { CompositeAuth, normalizeMastraUser } from "@mastra/core/server";
4
4
  import { Hono } from "hono";
5
5
  import { HonoRequest } from "hono/request";
6
6
  // src/server/auth/custom-route-matcher.ts
@@ -343,14 +343,22 @@ function supportsSessionRefresh(authConfig) {
343
343
  return typeof authConfig.getSessionIdFromRequest === "function" && typeof authConfig.refreshSession === "function" && typeof authConfig.getSessionHeaders === "function";
344
344
  }
345
345
  /**
346
+ * Whether auth is bypassed for this path/method: the dev playground (only when no auth
347
+ * provider is configured), paths that are not protected, and public paths (unless the
348
+ * route forces auth with `requiresAuth: true`).
349
+ */
350
+ const isAuthBypassed = ({ path, method, getHeader, authConfig, customRouteAuthConfig, requiresAuth }) => {
351
+ if (!(typeof authConfig.authenticateToken === "function") && isDevPlaygroundRequest(path, method, getHeader, authConfig, customRouteAuthConfig)) return true;
352
+ if (!isProtectedPath(path, method, authConfig, customRouteAuthConfig)) return true;
353
+ return !requiresAuth && (canAccessPublicly(path, method, authConfig) || isCustomRoutePublic(path, method, customRouteAuthConfig));
354
+ };
355
+ /**
346
356
  * Single auth middleware: authenticate → authorize.
347
357
  * Skip checks (dev playground, unprotected path, public path) are evaluated once.
348
358
  */
349
359
  const coreAuthMiddleware = async (ctx) => {
350
- const { path, method, getHeader, mastra, authConfig, customRouteAuthConfig, requestContext, rawRequest, token, requiresAuth } = ctx;
351
- if (!(typeof authConfig.authenticateToken === "function") && isDevPlaygroundRequest(path, method, getHeader, authConfig, customRouteAuthConfig)) return pass;
352
- if (!isProtectedPath(path, method, authConfig, customRouteAuthConfig)) return pass;
353
- if (!requiresAuth && (canAccessPublicly(path, method, authConfig) || isCustomRoutePublic(path, method, customRouteAuthConfig))) return pass;
360
+ const { path, method, mastra, authConfig, customRouteAuthConfig, requestContext, rawRequest, token } = ctx;
361
+ if (isAuthBypassed(ctx)) return pass;
354
362
  let user;
355
363
  let refreshHeaders;
356
364
  const authRequest = adaptToMastraAuthRequest(rawRequest);
@@ -416,6 +424,12 @@ const coreAuthMiddleware = async (ctx) => {
416
424
  };
417
425
  requestContext.set(MASTRA_USER_KEY, user);
418
426
  requestContext.set("user", user);
427
+ try {
428
+ const normalizedUser = ("toMastraUser" in authConfig && typeof authConfig.toMastraUser === "function" ? authConfig.toMastraUser : normalizeMastraUser).call(authConfig, user);
429
+ if (normalizedUser && typeof normalizedUser.id === "string" && normalizedUser.id.trim()) requestContext.set(MASTRA_NORMALIZED_USER_KEY, normalizedUser);
430
+ } catch (normalizeError) {
431
+ mastra.getLogger()?.warn("Failed to normalize authenticated user to MastraUser; callbacks will see user: undefined", { error: normalizeError instanceof Error ? { message: normalizeError.message } : normalizeError });
432
+ }
419
433
  let effectiveToken = token;
420
434
  if (!effectiveToken && rawRequest instanceof Request) {
421
435
  const cookieHeader = rawRequest.headers.get("cookie");
@@ -457,6 +471,11 @@ const coreAuthMiddleware = async (ctx) => {
457
471
  const roles = await rbacProvider.getRoles(user);
458
472
  requestContext.set(MASTRA_USER_ROLES_KEY, roles);
459
473
  requestContext.set("userRoles", roles);
474
+ const normalizedUser = requestContext.get(MASTRA_NORMALIZED_USER_KEY);
475
+ if (normalizedUser && !normalizedUser.role && Array.isArray(roles) && typeof roles[0] === "string") requestContext.set(MASTRA_NORMALIZED_USER_KEY, {
476
+ ...normalizedUser,
477
+ role: roles[0]
478
+ });
460
479
  }
461
480
  }
462
481
  } catch (rbacError) {
@@ -567,6 +586,6 @@ const checkRules = async (rules, path, method, user) => {
567
586
  }
568
587
  return false;
569
588
  };
570
- export { findMatchingCustomRoute as a, isDevPlaygroundRequest as c, matchesOrIncludes as d, pathMatchesPattern as f, CustomRouteMatcher as g, defaultAuthConfig as h, coreAuthMiddleware as i, isProtectedCustomRoute as l, supportsSessionRefresh as m, canAccessPublicly as n, getAuthenticatedUser as o, pathMatchesRule as p, checkRules as r, isCustomRoutePublic as s, authorizeAuthenticatedUser as t, isProtectedPath as u };
589
+ export { CustomRouteMatcher as _, findMatchingCustomRoute as a, isCustomRoutePublic as c, isProtectedPath as d, matchesOrIncludes as f, defaultAuthConfig as g, supportsSessionRefresh as h, coreAuthMiddleware as i, isDevPlaygroundRequest as l, pathMatchesRule as m, canAccessPublicly as n, getAuthenticatedUser as o, pathMatchesPattern as p, checkRules as r, isAuthBypassed as s, authorizeAuthenticatedUser as t, isProtectedCustomRoute as u };
571
590
 
572
- //# sourceMappingURL=helpers-C9QZKOhz.js.map
591
+ //# sourceMappingURL=helpers-B56oH6qp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"helpers-B56oH6qp.js","names":[],"sources":["../src/server/auth/custom-route-matcher.ts","../src/server/auth/defaults.ts","../src/server/auth/path-pattern.ts","../src/server/auth/helpers.ts"],"sourcesContent":["import { Hono } from 'hono';\nimport { HonoRequest } from 'hono/request';\n\n/** A custom route as the internal custom-route Hono app registers it. */\nexport interface CustomRouteMatcherEntry {\n method: string;\n path: string;\n /**\n * How many handlers (route middleware + handler) the route registers. Hono stores\n * each one as its own router entry, so mirror the count to build the same router.\n */\n handlerCount?: number;\n}\n\nexport interface CustomRouteMatch<T> {\n entry: T;\n index: number;\n params: Record<string, string>;\n}\n\ntype Marker = (...args: unknown[]) => undefined;\n\nconst noopMiddleware: Marker = () => undefined;\nconst paramRequest = new Request('http://localhost/');\n\n/**\n * Answers \"which custom route will run for this request?\" using the same Hono router\n * the custom-route bridge dispatches with (`buildCustomRouteHandler`), registered in\n * the same order with the same paths and methods. Auth decisions use this instead\n * of a separate pattern matcher, so they can't disagree with dispatch on precedence,\n * case, trailing slashes, percent-decoding or HEAD handling.\n */\nexport class CustomRouteMatcher<T extends CustomRouteMatcherEntry> {\n readonly #app = new Hono();\n readonly #indexByHandler = new Map<unknown, number>();\n readonly #entries: readonly T[];\n\n constructor(entries: readonly T[]) {\n this.#entries = entries;\n // Same global middleware as the custom-route app, so the router sees the same table.\n this.#app.use('*', noopMiddleware as never);\n entries.forEach((entry, index) => {\n const marker: Marker = () => undefined;\n this.#indexByHandler.set(marker, index);\n const handlers = Array.from({ length: Math.max(1, entry.handlerCount ?? 1) }, () => marker as never);\n if (entry.method === 'ALL') {\n this.#app.all(entry.path, handlers[0]!, ...handlers.slice(1));\n } else {\n this.#app.on(entry.method, entry.path, handlers[0]!, ...handlers.slice(1));\n }\n });\n }\n\n /**\n * Match a path the way Hono dispatches it, i.e. `path` is already in the form\n * `getPath()` returns (no query string, percent-decoded once).\n * Throws if Hono can't build a router for the registered paths.\n */\n matchPath(path: string, method: string): CustomRouteMatch<T> | undefined {\n const upper = method.toUpperCase();\n // Hono serves HEAD with the GET handler.\n const dispatchMethod = upper === 'HEAD' ? 'GET' : upper;\n const result = this.#app.router.match(dispatchMethod, path);\n const handlers = result[0];\n for (let i = 0; i < handlers.length; i++) {\n const index = this.#indexByHandler.get(handlers[i]![0][0]);\n if (index === undefined) continue; // the global middleware\n const request = new HonoRequest(paramRequest, path, result as never);\n request.routeIndex = i;\n return { entry: this.#entries[index]!, index, params: request.param() as Record<string, string> };\n }\n return undefined;\n }\n\n /**\n * Match the full URL handed to the custom-route app. Parses it the same way\n * (`new Request(url)` then Hono's `getPath`), so dot segments, encoded characters\n * and the query string are handled exactly as dispatch handles them.\n * Throws if the URL can't be parsed.\n */\n matchUrl(url: string, method: string): CustomRouteMatch<T> | undefined {\n const path = this.#app.getPath(new Request(url));\n return this.matchPath(path, method);\n }\n\n /**\n * Converts a raw request path (as Express/Koa/Fastify see it, not yet decoded) to\n * the path Hono would dispatch when the bridge forwards it. Throws on an\n * unparseable path.\n */\n dispatchPathForRawPath(rawPath: string): string {\n return this.#app.getPath(new Request(`http://localhost${rawPath}`));\n }\n}\n\nconst MAX_CACHED_MATCHERS = 32;\nconst matcherCache = new Map<string, CustomRouteMatcher<CustomRouteMatcherEntry & { key: string }>>();\n\n/**\n * Builds (and caches) a matcher from `customRouteAuthConfig` keys. Keys are\n * `METHOD:path` in registration order, which is the order the server registers\n * custom routes with the custom-route app.\n */\nexport function getCustomRouteAuthConfigMatcher(\n keys: readonly string[],\n): CustomRouteMatcher<CustomRouteMatcherEntry & { key: string }> {\n const signature = JSON.stringify(keys);\n const cached = matcherCache.get(signature);\n if (cached) {\n matcherCache.delete(signature);\n matcherCache.set(signature, cached);\n return cached;\n }\n\n const entries: Array<CustomRouteMatcherEntry & { key: string }> = [];\n for (const key of keys) {\n const colonIndex = key.indexOf(':');\n if (colonIndex === -1) continue; // malformed key\n entries.push({ key, method: key.substring(0, colonIndex).toUpperCase(), path: key.substring(colonIndex + 1) });\n }\n\n const matcher = new CustomRouteMatcher(entries);\n matcherCache.set(signature, matcher);\n if (matcherCache.size > MAX_CACHED_MATCHERS) {\n matcherCache.delete(matcherCache.keys().next().value!);\n }\n return matcher;\n}\n","import type { MastraAuthConfig } from '@mastra/core/server';\n\n// Default configuration that can be extended by clients\nexport const defaultAuthConfig: MastraAuthConfig = {\n protected: ['/api/*'],\n public: ['/api', '/api/auth/*'],\n // Simple rule system\n rules: [\n // Admin users can do anything\n {\n condition: user => {\n if (typeof user === 'object' && user !== null) {\n if ('isAdmin' in user) {\n return !!user.isAdmin;\n }\n\n if ('role' in user) {\n return user.role === 'admin';\n }\n }\n return false;\n },\n allow: true,\n },\n ],\n};\n","/**\n * Path pattern matching utility\n * Inlined from regexparam v3.0.0 (MIT License)\n * https://github.com/lukeed/regexparam\n *\n * Copyright (c) Luke Edwards <luke.edwards05@gmail.com> (lukeed.com)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nexport interface ParsedPattern {\n keys: string[] | false;\n pattern: RegExp;\n}\n\n/**\n * Parse a route pattern into a RegExp\n * Supports:\n * - Named parameters: /users/:id\n * - Optional parameters: /users/:id?\n * - Wildcards: /files/*\n * - Mixed patterns: /api/:version/users/:id\n */\nexport function parse(input: string | RegExp, loose?: boolean): ParsedPattern {\n if (input instanceof RegExp) return { keys: false, pattern: input };\n\n let c: string;\n let o: number;\n let tmp: string | undefined;\n let ext: number;\n const keys: string[] = [];\n let pattern = '';\n const arr = input.split('/');\n\n arr[0] || arr.shift();\n\n while ((tmp = arr.shift())) {\n c = tmp[0]!;\n if (c === '*') {\n keys.push(c);\n pattern += tmp[1] === '?' ? '(?:/(.*))?' : '/(.*)';\n } else if (c === ':') {\n o = tmp.indexOf('?', 1);\n ext = tmp.indexOf('.', 1);\n keys.push(tmp.substring(1, ~o ? o : ~ext ? ext : tmp.length));\n pattern += !!~o && !~ext ? '(?:/([^/]+?))?' : '/([^/]+?)';\n if (~ext) pattern += (~o ? '?' : '') + '\\\\' + tmp.substring(ext);\n } else {\n // Escape regex metacharacters so static segments stay literal. Without this,\n // a public route like '/a.b' would also match '/axb' and could skip auth for\n // a later protected route the framework dispatches instead.\n pattern += '/' + tmp.replace(/([.+*?^${}()|[\\]\\\\])/g, '\\\\$1');\n }\n }\n\n return {\n keys: keys,\n pattern: new RegExp('^' + pattern + (loose ? '(?=$|/)' : '/?$'), 'i'),\n };\n}\n\n/**\n * Test if a path matches a pattern\n */\nexport function matchPath(path: string, pattern: string | RegExp): boolean {\n const { pattern: regex } = parse(pattern);\n return regex.test(path);\n}\n","import type { ISessionProvider, MastraUser } from '@mastra/core/auth';\nimport type { IRBACProvider, EEUser } from '@mastra/core/auth/ee';\nimport type { Mastra } from '@mastra/core/mastra';\nimport { CompositeAuth, normalizeMastraUser } from '@mastra/core/server';\nimport type { ApiRoute, IMastraAuthProvider, MastraAuthConfig, MastraAuthRequest } from '@mastra/core/server';\n\nimport {\n MASTRA_RESOURCE_ID_KEY,\n MASTRA_USER_KEY,\n MASTRA_NORMALIZED_USER_KEY,\n MASTRA_USER_PERMISSIONS_KEY,\n MASTRA_USER_ROLES_KEY,\n MASTRA_AUTH_TOKEN_KEY,\n MASTRA_AUTH_MODE_KEY,\n} from '../constants';\nimport { HTTPException } from '../http-exception';\nimport { CustomRouteMatcher, getCustomRouteAuthConfigMatcher } from './custom-route-matcher';\nimport { defaultAuthConfig } from './defaults';\nimport { parse } from './path-pattern';\n\n// Re-export request-context key constants so custom middleware can read namespaced\n// auth state without importing internal paths.\nexport {\n MASTRA_USER_KEY,\n MASTRA_NORMALIZED_USER_KEY,\n MASTRA_USER_PERMISSIONS_KEY,\n MASTRA_USER_ROLES_KEY,\n} from '../constants';\n\ntype CustomRouteAuthDecision = 'protected' | 'public' | 'none';\n\n/**\n * Decide auth for a request from the custom route the custom-route app will dispatch\n * it to (see `CustomRouteMatcher`), not from whichever pattern happens to match.\n *\n * Fails closed:\n * - an exact `METHOD:path` (or `ALL:path`) entry that requires auth always wins, so a\n * path registered as protected is never served without auth;\n * - `path` may be a raw request path (Express, Koa, Fastify) or one Hono already\n * decoded, so it's resolved both ways and is only public if every reading lands on\n * a public route, and protected if any reading lands on a protected one;\n * - if the routes or the path can't be parsed, the request is treated as protected.\n */\nconst resolveCustomRouteAuth = (\n path: string,\n method: string,\n customRouteAuthConfig: Map<string, boolean>,\n): CustomRouteAuthDecision => {\n const upperMethod = method.toUpperCase();\n const methods = upperMethod === 'HEAD' ? ['HEAD', 'GET'] : [upperMethod];\n for (const m of methods) {\n if (customRouteAuthConfig.get(`${m}:${path}`) === true || customRouteAuthConfig.get(`ALL:${path}`) === true) {\n return 'protected';\n }\n }\n\n // Adapters pin the current request by appending `METHOD:path` to a copy of the map.\n // As the last entry it only decides when no earlier route matches, so resolve the\n // rest with a cached matcher and fall back to it, instead of building a new router\n // for every request path.\n const keys = [...customRouteAuthConfig.keys()];\n const lastKey = keys[keys.length - 1];\n const pinnedKey =\n lastKey !== undefined && methods.some(m => lastKey === `${m}:${path}` || lastKey === `ALL:${path}`)\n ? lastKey\n : undefined;\n\n let matcher: ReturnType<typeof getCustomRouteAuthConfigMatcher>;\n const candidates = new Set<string>([path]);\n try {\n matcher = getCustomRouteAuthConfigMatcher(pinnedKey ? keys.slice(0, -1) : keys);\n candidates.add(matcher.dispatchPathForRawPath(path));\n } catch {\n return 'protected';\n }\n\n let matchedPublic = false;\n let unmatched = false;\n for (const candidate of candidates) {\n let key: string | undefined;\n try {\n key = matcher.matchPath(candidate, upperMethod)?.entry.key;\n } catch {\n return 'protected';\n }\n if (key === undefined && pinnedKey && candidate === path) {\n key = pinnedKey;\n }\n if (key === undefined) {\n unmatched = true;\n continue;\n }\n if (customRouteAuthConfig.get(key) !== false) {\n return 'protected';\n }\n matchedPublic = true;\n }\n\n return matchedPublic && !unmatched ? 'public' : 'none';\n};\n\n/**\n * Check if a request will be handled by a registered custom route that requires\n * authentication. The route that decides is the one the custom-route app dispatches\n * to (first registered match), using Hono's own matching. Returns false when no\n * custom route handles the request.\n */\nexport const isProtectedCustomRoute = (\n path: string,\n method: string,\n customRouteAuthConfig?: Map<string, boolean>,\n): boolean => {\n if (!customRouteAuthConfig || customRouteAuthConfig.size === 0) {\n return false;\n }\n return resolveCustomRouteAuth(path, method, customRouteAuthConfig) === 'protected';\n};\n\nconst apiRouteMatchers = new WeakMap<\n readonly ApiRoute[],\n { signature: string; matcher: CustomRouteMatcher<ApiRoute> }\n>();\n\n/**\n * Find the custom API route Hono dispatches `path` to, with its decoded path params.\n * `path` is in the form Hono's `c.req.path` returns (no query string, decoded once).\n * Matching follows Hono: first registered match wins, case-sensitive, strict\n * trailing slash, and HEAD is served by GET routes.\n */\nexport const findMatchingCustomRoute = (\n path: string,\n method: string,\n apiRoutes?: ApiRoute[],\n): { route: ApiRoute; params: Record<string, string> } | undefined => {\n if (!apiRoutes || apiRoutes.length === 0) return undefined;\n\n const signature = JSON.stringify(apiRoutes.map(route => `${route.method}:${route.path}`));\n let cached = apiRouteMatchers.get(apiRoutes);\n if (!cached || cached.signature !== signature) {\n cached = { signature, matcher: new CustomRouteMatcher(apiRoutes) };\n apiRouteMatchers.set(apiRoutes, cached);\n }\n\n try {\n const match = cached.matcher.matchPath(path, method);\n return match ? { route: match.entry, params: match.params } : undefined;\n } catch {\n // Hono can't route these paths either, so no custom route handles the request.\n return undefined;\n }\n};\n\n/**\n * Check if request is from dev playground\n * @param getHeader - Function to get header value from request\n * @param customRouteAuthConfig - Map of custom route auth configurations\n */\nexport const isDevPlaygroundRequest = (\n path: string,\n method: string,\n getHeader: (name: string) => string | undefined,\n authConfig: MastraAuthConfig,\n customRouteAuthConfig?: Map<string, boolean>,\n): boolean => {\n const protectedAccess = [...(defaultAuthConfig.protected || []), ...(authConfig.protected || [])];\n return (\n process.env.MASTRA_DEV === 'true' &&\n // Allow if path doesn't match protected patterns AND is not a protected custom route\n ((!isAnyMatch(path, method, protectedAccess) && !isProtectedCustomRoute(path, method, customRouteAuthConfig)) ||\n // Or if has playground header\n getHeader('x-mastra-dev-playground') === 'true')\n );\n};\n\n/**\n * Check if a request will be handled by a custom route registered as public\n * (`requiresAuth: false`). Uses the same dispatch-order resolution as\n * `isProtectedCustomRoute`, and returns false (not public) when no custom route\n * handles the request or the answer is ambiguous.\n */\nexport const isCustomRoutePublic = (\n path: string,\n method: string,\n customRouteAuthConfig?: Map<string, boolean>,\n): boolean => {\n if (!customRouteAuthConfig || customRouteAuthConfig.size === 0) {\n return false;\n }\n return resolveCustomRouteAuth(path, method, customRouteAuthConfig) === 'public';\n};\n\n// NOTE: This uses isProtectedCustomRoute (default-allow for unknown paths) rather than\n// !isCustomRoutePublic (default-deny). This is intentional — all registered server and\n// custom routes are auth-checked via registerRoute/checkRouteAuth regardless of this\n// function. The '/api/*' protected pattern exists as a user-facing override mechanism.\n// The old default-deny logic incorrectly blocked non-API paths (e.g. '/', '/agents')\n// which prevented the studio login page from loading in production.\nexport const isProtectedPath = (\n path: string,\n method: string,\n authConfig: MastraAuthConfig,\n customRouteAuthConfig?: Map<string, boolean>,\n): boolean => {\n const protectedAccess = [...(defaultAuthConfig.protected || []), ...(authConfig.protected || [])];\n return isAnyMatch(path, method, protectedAccess) || isProtectedCustomRoute(path, method, customRouteAuthConfig);\n};\n\nexport const canAccessPublicly = (path: string, method: string, authConfig: MastraAuthConfig): boolean => {\n // Check if this path+method combination is publicly accessible\n const publicAccess = [...(defaultAuthConfig.public || []), ...(authConfig.public || [])];\n\n return isAnyMatch(path, method, publicAccess);\n};\n\nconst isAnyMatch = (\n path: string,\n method: string,\n patterns: MastraAuthConfig['protected'] | MastraAuthConfig['public'],\n): boolean => {\n if (!patterns) {\n return false;\n }\n\n for (const patternPathOrMethod of patterns) {\n if (patternPathOrMethod instanceof RegExp) {\n if (patternPathOrMethod.test(path)) {\n return true;\n }\n }\n\n if (typeof patternPathOrMethod === 'string' && pathMatchesPattern(path, patternPathOrMethod)) {\n return true;\n }\n\n if (Array.isArray(patternPathOrMethod) && patternPathOrMethod.length === 2) {\n const [pattern, methodOrMethods] = patternPathOrMethod;\n if (pathMatchesPattern(path, pattern) && matchesOrIncludes(methodOrMethods, method)) {\n return true;\n }\n }\n }\n\n return false;\n};\n\nexport const pathMatchesPattern = (path: string, pattern: string): boolean => {\n // Use regexparam for battle-tested path matching\n // Supports:\n // - Exact paths: '/api/users'\n // - Wildcards: '/api/agents/*' matches '/api/agents/123'\n // - Path parameters: '/users/:id' matches '/users/123'\n // - Optional parameters: '/users/:id?' matches '/users' and '/users/123'\n // - Mixed patterns: '/api/:version/users/:id/profile'\n const { pattern: regex } = parse(pattern);\n return regex.test(path);\n};\n\nexport const pathMatchesRule = (path: string, rulePath: string | RegExp | string[] | undefined): boolean => {\n if (!rulePath) return true; // No path specified means all paths\n\n if (typeof rulePath === 'string') {\n return pathMatchesPattern(path, rulePath);\n }\n\n if (rulePath instanceof RegExp) {\n return rulePath.test(path);\n }\n\n if (Array.isArray(rulePath)) {\n return rulePath.some(p => pathMatchesPattern(path, p));\n }\n\n return false;\n};\n\nexport const matchesOrIncludes = (values: string | string[], value: string): boolean => {\n if (typeof values === 'string') {\n return values === value;\n }\n\n if (Array.isArray(values)) {\n return values.includes(value);\n }\n\n return false;\n};\n\n// ── Core auth middleware ──\n// Framework-agnostic auth logic extracted from adapter middlewares.\n// Each adapter builds an AuthMiddlewareContext and delegates to coreAuthMiddleware.\n\nexport interface AuthMiddlewareContext {\n path: string;\n method: string;\n getHeader: (name: string) => string | undefined;\n mastra: Mastra;\n authConfig: MastraAuthConfig;\n customRouteAuthConfig?: Map<string, boolean>;\n requestContext: { get: (key: string) => unknown; set: (key: string, value: unknown) => void };\n rawRequest: MastraAuthRequest;\n token: string | null;\n buildAuthorizeContext: () => unknown;\n /** When true, force authentication even if the path matches a public pattern. */\n requiresAuth?: boolean;\n}\n\nexport type AuthResult =\n | { action: 'next'; headers?: Record<string, string> }\n | { action: 'error'; status: number; body: Record<string, unknown>; headers?: Record<string, string> };\n\nconst pass: AuthResult = { action: 'next' };\n\n/**\n * Lets an app's `authorize(path, method, user, context)` read `context.get('requestContext')` and\n * `context.get('mastra')` on every adapter, as it can on Hono, so per-caller values (the Knowledge scope) bind\n * the same way everywhere. Hono and NestJS contexts already answer `get`; Express, Fastify and Koa pass a web\n * Request, Elysia its own context, and adapters with no builder pass nothing.\n */\nconst withAuthorizeVariables = (\n base: unknown,\n ctx: Pick<AuthMiddlewareContext, 'mastra' | 'requestContext' | 'customRouteAuthConfig' | 'rawRequest'>,\n): unknown => {\n const variables: Record<string, unknown> = {\n mastra: ctx.mastra,\n requestContext: ctx.requestContext,\n customRouteAuthConfig: ctx.customRouteAuthConfig,\n };\n const get = (key: string) => variables[key];\n if (base === null || base === undefined) {\n return { get, req: ctx.rawRequest };\n }\n if (typeof base === 'object' && typeof (base as { get?: unknown }).get !== 'function') {\n Object.defineProperty(base, 'get', { value: get, configurable: true });\n }\n return base;\n};\n\nconst adaptToMastraAuthRequest = (request: MastraAuthRequest): MastraAuthRequest => {\n if (!(request instanceof Request)) {\n return request;\n }\n\n return {\n raw: request,\n headers: request.headers,\n header: name => request.headers.get(name) ?? undefined,\n };\n};\n\nexport interface GetAuthenticatedUserOptions {\n mastra: Mastra;\n token: string;\n request: MastraAuthRequest;\n}\n\nexport const getAuthenticatedUser = async <TUser = unknown>({\n mastra,\n token,\n request,\n}: GetAuthenticatedUserOptions): Promise<TUser | null> => {\n const normalizedToken = token.replace(/^Bearer\\s+/i, '').trim();\n if (!normalizedToken) {\n return null;\n }\n\n const authConfig = mastra.getServer()?.auth;\n if (!authConfig || typeof authConfig.authenticateToken !== 'function') {\n return null;\n }\n\n return (await authConfig.authenticateToken(normalizedToken, request)) as TUser | null;\n};\n\n/**\n * Check if an auth config object supports transparent session refresh.\n * Returns true if the auth provider implements the necessary ISessionProvider methods.\n */\nexport function supportsSessionRefresh(\n authConfig: MastraAuthConfig | IMastraAuthProvider,\n): authConfig is (MastraAuthConfig | IMastraAuthProvider) &\n Pick<ISessionProvider, 'refreshSession' | 'getSessionIdFromRequest' | 'getSessionHeaders'> {\n return (\n typeof (authConfig as any).getSessionIdFromRequest === 'function' &&\n typeof (authConfig as any).refreshSession === 'function' &&\n typeof (authConfig as any).getSessionHeaders === 'function'\n );\n}\n\n/**\n * Whether auth is bypassed for this path/method: the dev playground (only when no auth\n * provider is configured), paths that are not protected, and public paths (unless the\n * route forces auth with `requiresAuth: true`).\n */\nexport const isAuthBypassed = ({\n path,\n method,\n getHeader,\n authConfig,\n customRouteAuthConfig,\n requiresAuth,\n}: Pick<\n AuthMiddlewareContext,\n 'path' | 'method' | 'getHeader' | 'authConfig' | 'customRouteAuthConfig' | 'requiresAuth'\n>): boolean => {\n // Only bypass auth for dev playground when no real auth provider is configured.\n // When auth IS configured (has authenticateToken), we need the full auth flow\n // so user/roles/permissions are set in requestContext.\n const hasAuthProvider = typeof authConfig.authenticateToken === 'function';\n if (!hasAuthProvider && isDevPlaygroundRequest(path, method, getHeader, authConfig, customRouteAuthConfig)) {\n return true;\n }\n\n if (!isProtectedPath(path, method, authConfig, customRouteAuthConfig)) {\n return true;\n }\n\n // When a route explicitly requires auth (requiresAuth: true), skip the\n // public-path bypass so the user is still authenticated and permissions\n // are injected into the request context.\n return (\n !requiresAuth &&\n (canAccessPublicly(path, method, authConfig) || isCustomRoutePublic(path, method, customRouteAuthConfig))\n );\n};\n\n/**\n * Single auth middleware: authenticate → authorize.\n * Skip checks (dev playground, unprotected path, public path) are evaluated once.\n */\nexport const coreAuthMiddleware = async (ctx: AuthMiddlewareContext): Promise<AuthResult> => {\n const { path, method, mastra, authConfig, customRouteAuthConfig, requestContext, rawRequest, token } = ctx;\n\n // ── Skip checks (evaluated once) ──\n\n if (isAuthBypassed(ctx)) {\n return pass;\n }\n\n // ── Authentication ──\n\n let user: unknown;\n let refreshHeaders: Record<string, string> | undefined;\n const authRequest = adaptToMastraAuthRequest(rawRequest);\n\n type ConsumePendingResponseHeadersFn = (request: typeof authRequest) => Record<string, string> | undefined;\n const mergePendingProviderHeaders = (request: typeof authRequest = authRequest) => {\n const consume = (authConfig as { consumePendingResponseHeaders?: ConsumePendingResponseHeadersFn })\n .consumePendingResponseHeaders;\n if (typeof consume !== 'function') return;\n let pending: Record<string, string> | undefined;\n try {\n pending = consume.call(authConfig, request);\n } catch {\n // Forwarding a rotated cookie is best-effort; never fail auth over it.\n return;\n }\n if (!pending) return;\n refreshHeaders = { ...(refreshHeaders ?? {}), ...pending };\n };\n\n try {\n if (typeof authConfig.authenticateToken === 'function') {\n user = await authConfig.authenticateToken(token ?? '', authRequest);\n mergePendingProviderHeaders();\n } else {\n throw new Error('No token verification method configured');\n }\n\n // If authentication failed, attempt transparent session refresh before returning 401.\n // This handles expired access tokens without requiring client-side refresh logic.\n if (!user && supportsSessionRefresh(authConfig) && rawRequest instanceof Request) {\n let retryHttpError: HTTPException | undefined;\n try {\n const sessionId = authConfig.getSessionIdFromRequest(rawRequest);\n if (sessionId) {\n const newSession = await authConfig.refreshSession(sessionId);\n if (newSession) {\n // Refresh succeeded — build updated session headers and re-authenticate.\n // We create a synthetic request with the new session cookie so\n // authenticateToken (which reads cookies from the request) picks up\n // the refreshed session instead of the expired one.\n refreshHeaders = authConfig.getSessionHeaders(newSession);\n const refreshedCookie = Object.entries(refreshHeaders)\n .filter(([k]) => k.toLowerCase() === 'set-cookie')\n .map(([, v]) => v.split(';')[0]) // Extract name=value before attributes\n .join('; ');\n if (refreshedCookie) {\n const refreshedRequest = new Request(rawRequest.url, {\n method: rawRequest.method,\n headers: new Headers(rawRequest.headers),\n });\n refreshedRequest.headers.set('Cookie', refreshedCookie);\n // Pass the refreshed cookie value as the token so authenticateToken\n // picks up the new session instead of the stale original.\n // Auth providers typically read cookies from the request object, but\n // some may also inspect the token parameter directly.\n const cookieValue = refreshedCookie.includes('=')\n ? refreshedCookie.split('=').slice(1).join('=')\n : refreshedCookie;\n try {\n const retryAuthRequest = adaptToMastraAuthRequest(refreshedRequest);\n user = await authConfig.authenticateToken(cookieValue, retryAuthRequest);\n mergePendingProviderHeaders(retryAuthRequest);\n } catch (retryErr) {\n retryHttpError = retryErr instanceof HTTPException ? retryErr : undefined;\n throw retryErr;\n }\n }\n if (!user) {\n refreshHeaders = undefined;\n }\n }\n }\n } catch (refreshErr) {\n refreshHeaders = undefined;\n // An explicit HTTP error from the retried authenticateToken goes to the outer handler.\n if (retryHttpError === refreshErr) throw refreshErr;\n mastra.getLogger()?.debug('Session refresh failed, falling back to 401', {\n error: refreshErr instanceof Error ? { message: refreshErr.message } : refreshErr,\n });\n }\n }\n\n if (!user) {\n return { action: 'error', status: 401, body: { error: 'Invalid or expired token' }, headers: refreshHeaders };\n }\n\n requestContext.set(MASTRA_USER_KEY, user);\n // Backward-compat: also write the legacy `'user'` key so existing\n // middleware and integrations that read `requestContext.get('user')`\n // (including built-in FGA route enforcement, memory handlers, and the\n // documented public surface) keep working. New code should prefer\n // `MASTRA_USER_KEY` to avoid collisions with caller-supplied keys.\n requestContext.set('user', user);\n\n // Normalize the authenticated user to the stable MastraUser shape consumed\n // by DynamicArgument callbacks. Must run before mapUserToResourceId:\n // CompositeAuth's resource-id mapping consumes its authenticated-provider\n // bookkeeping while toMastraUser only peeks at it. Best-effort — a user\n // shape the default normalization can't handle leaves the key unset\n // (callbacks see `user: undefined`) instead of failing the request.\n try {\n const toMastraUser =\n 'toMastraUser' in authConfig && typeof authConfig.toMastraUser === 'function'\n ? (authConfig.toMastraUser as (user: unknown) => MastraUser)\n : normalizeMastraUser;\n const normalizedUser = toMastraUser.call(authConfig, user);\n if (normalizedUser && typeof normalizedUser.id === 'string' && normalizedUser.id.trim()) {\n requestContext.set(MASTRA_NORMALIZED_USER_KEY, normalizedUser);\n }\n } catch (normalizeError) {\n mastra\n .getLogger()\n ?.warn('Failed to normalize authenticated user to MastraUser; callbacks will see user: undefined', {\n error: normalizeError instanceof Error ? { message: normalizeError.message } : normalizeError,\n });\n }\n\n // Store the raw auth token so downstream code (e.g., editor MCP client\n // resolution) can forward it when connecting to auth-protected MCP servers.\n // The token may arrive via Authorization header, apiKey query param, or\n // cookie (SimpleAuth sets `mastra-token`). Check all sources so the\n // forwarded value is available regardless of how the user authenticated.\n let effectiveToken = token;\n if (!effectiveToken && rawRequest instanceof Request) {\n const cookieHeader = rawRequest.headers.get('cookie');\n if (cookieHeader) {\n const match = cookieHeader.match(/mastra-token=([^;]+)/);\n if (match?.[1]) effectiveToken = match[1];\n }\n }\n if (effectiveToken) {\n requestContext.set(MASTRA_AUTH_TOKEN_KEY, effectiveToken);\n }\n\n if (typeof authConfig.mapUserToResourceId === 'function') {\n try {\n const resourceId = authConfig.mapUserToResourceId(user);\n // CompositeAuth validates the authenticating provider's mapper. It can\n // return undefined when that provider never configured a mapper.\n if (resourceId !== undefined || !(authConfig instanceof CompositeAuth)) {\n if (typeof resourceId !== 'string' || !resourceId.trim()) {\n throw new Error('mapUserToResourceId must return a non-empty string for the authenticated user');\n }\n requestContext.set(MASTRA_RESOURCE_ID_KEY, resourceId);\n }\n } catch (mapError) {\n mastra.getLogger()?.error('mapUserToResourceId failed', {\n error: mapError instanceof Error ? { message: mapError.message, stack: mapError.stack } : mapError,\n });\n return {\n action: 'error',\n status: 500,\n body: { error: 'Failed to map authenticated user to a resource ID' },\n headers: refreshHeaders,\n };\n }\n }\n\n try {\n // Determine which RBAC provider to use based on auth mode\n const authMode = requestContext.get(MASTRA_AUTH_MODE_KEY);\n const serverConfig = mastra.getServer();\n const studioConfig = mastra.getStudio?.();\n // Use studio RBAC if this is a studio request, otherwise use server RBAC\n const rbacProvider = (authMode === 'studio' ? (studioConfig?.rbac ?? serverConfig?.rbac) : serverConfig?.rbac) as\n | IRBACProvider<EEUser>\n | undefined;\n\n if (rbacProvider) {\n if (!user || typeof user !== 'object' || !('id' in user)) {\n mastra.getLogger()?.warn('RBAC: authenticated user missing required \"id\" field, skipping permission loading');\n } else {\n const permissions = await rbacProvider.getPermissions(user as EEUser);\n requestContext.set(MASTRA_USER_PERMISSIONS_KEY, permissions);\n // Backward-compat alias for callers reading the legacy key.\n requestContext.set('userPermissions', permissions);\n\n const roles = await rbacProvider.getRoles(user as EEUser);\n requestContext.set(MASTRA_USER_ROLES_KEY, roles);\n // Backward-compat alias for callers reading the legacy key.\n requestContext.set('userRoles', roles);\n\n // Populate the normalized user's role from RBAC when the auth\n // provider's user carried none: primary role = first RBAC role.\n const normalizedUser = requestContext.get(MASTRA_NORMALIZED_USER_KEY) as MastraUser | undefined;\n if (normalizedUser && !normalizedUser.role && Array.isArray(roles) && typeof roles[0] === 'string') {\n requestContext.set(MASTRA_NORMALIZED_USER_KEY, { ...normalizedUser, role: roles[0] });\n }\n }\n }\n } catch (rbacError) {\n mastra.getLogger()?.error('RBAC: failed to load user permissions/roles', {\n error: rbacError instanceof Error ? { message: rbacError.message, stack: rbacError.stack } : rbacError,\n });\n }\n } catch (err) {\n mastra.getLogger()?.error('Authentication error', {\n error: err instanceof Error ? { message: err.message, stack: err.stack } : err,\n });\n // Explicit HTTP errors from auth callbacks keep their status/message; anything else is redacted.\n // The HTTPException message is sent to the client, so callers must keep it safe (no internal details).\n if (err instanceof HTTPException && err.status >= 400 && err.status <= 599) {\n return { action: 'error', status: err.status, body: { error: err.message }, headers: refreshHeaders };\n }\n return { action: 'error', status: 401, body: { error: 'Invalid or expired token' }, headers: refreshHeaders };\n }\n\n // ── Authorization ──\n\n const authorizationError = await authorizeAuthenticatedUser({\n path,\n method,\n user,\n mastra,\n authConfig,\n customRouteAuthConfig,\n requestContext,\n rawRequest,\n buildAuthorizeContext: ctx.buildAuthorizeContext,\n });\n if (authorizationError) {\n return { action: 'error', ...authorizationError, headers: refreshHeaders };\n }\n\n return refreshHeaders ? { action: 'next', headers: refreshHeaders } : pass;\n};\n\nexport interface AuthorizeAuthenticatedUserContext {\n path: string;\n method: string;\n user: unknown;\n mastra: Mastra;\n authConfig: MastraAuthConfig;\n customRouteAuthConfig?: Map<string, boolean>;\n requestContext: AuthMiddlewareContext['requestContext'];\n rawRequest: MastraAuthRequest;\n buildAuthorizeContext: () => unknown;\n}\n\n/**\n * The authorization step of server auth for an already authenticated user:\n * `authorizeUser`, `authorize(path, method, user)`, `rules`, or the RBAC default rules.\n * Returns null when the user may access `method path`.\n */\nexport const authorizeAuthenticatedUser = async (\n ctx: AuthorizeAuthenticatedUserContext,\n): Promise<{ status: number; body: Record<string, unknown> } | null> => {\n const { path, method, user, mastra, authConfig, requestContext, rawRequest } = ctx;\n const denied = { status: 403, body: { error: 'Access denied' } };\n\n if ('authorizeUser' in authConfig && typeof authConfig.authorizeUser === 'function') {\n try {\n const isAuthorized = await authConfig.authorizeUser(user, adaptToMastraAuthRequest(rawRequest));\n return isAuthorized ? null : denied;\n } catch (err) {\n mastra.getLogger()?.error('Authorization error in authorizeUser', {\n error: err instanceof Error ? { message: err.message, stack: err.stack } : err,\n });\n return { status: 500, body: { error: 'Authorization error' } };\n }\n }\n\n if ('authorize' in authConfig && typeof authConfig.authorize === 'function') {\n try {\n const authorizeCtx = withAuthorizeVariables(ctx.buildAuthorizeContext(), {\n mastra,\n requestContext,\n customRouteAuthConfig: ctx.customRouteAuthConfig,\n rawRequest,\n });\n const isAuthorized = await authConfig.authorize(path, method, user, authorizeCtx as any);\n return isAuthorized ? null : denied;\n } catch (err) {\n mastra.getLogger()?.error('Authorization error in authorize', {\n error: err instanceof Error ? { message: err.message, stack: err.stack } : err,\n path,\n method,\n });\n return { status: 500, body: { error: 'Authorization error' } };\n }\n }\n\n if ('rules' in authConfig && authConfig.rules && authConfig.rules.length > 0) {\n return (await checkRules(authConfig.rules, path, method, user)) ? null : denied;\n }\n\n // No explicit authorization configured (authorizeUser, authorize, or rules)\n // Check if RBAC is configured - if not, allow authenticated users through\n // (auth-only mode = authenticated users get full access)\n const rbacProvider =\n requestContext.get(MASTRA_AUTH_MODE_KEY) === 'studio'\n ? (mastra.getStudio?.()?.rbac ?? mastra.getServer()?.rbac)\n : mastra.getServer()?.rbac;\n if (rbacProvider) {\n if (defaultAuthConfig.rules && defaultAuthConfig.rules.length > 0) {\n return (await checkRules(defaultAuthConfig.rules, path, method, user)) ? null : denied;\n }\n return denied;\n }\n\n return null;\n};\n\n// Check authorization rules\nexport const checkRules = async (\n rules: MastraAuthConfig['rules'],\n path: string,\n method: string,\n user: unknown,\n): Promise<boolean> => {\n // Go through rules in order (first match wins)\n for (const i in rules || []) {\n const rule = rules?.[i]!;\n // Check if rule applies to this path\n if (!pathMatchesRule(path, rule.path)) {\n continue;\n }\n\n // Check if rule applies to this method\n if (rule.methods && !matchesOrIncludes(rule.methods, method)) {\n continue;\n }\n\n // Rule matches, so it decides. A failed condition denies instead of\n // falling through to a broader rule further down the list.\n const condition = rule.condition;\n if (typeof condition === 'function') {\n return await Promise.resolve()\n .then(() => condition(user))\n .then(result => !!result)\n .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8hUOR.cjs");
1
+ const require_constants = require("./constants-1yTmKUZD.cjs");
2
2
  const require_http_exception = require("./http-exception-Co3MbFUf.cjs");
3
3
  let _mastra_core_server = require("@mastra/core/server");
4
4
  let hono = require("hono");
@@ -343,14 +343,22 @@ function supportsSessionRefresh(authConfig) {
343
343
  return typeof authConfig.getSessionIdFromRequest === "function" && typeof authConfig.refreshSession === "function" && typeof authConfig.getSessionHeaders === "function";
344
344
  }
345
345
  /**
346
+ * Whether auth is bypassed for this path/method: the dev playground (only when no auth
347
+ * provider is configured), paths that are not protected, and public paths (unless the
348
+ * route forces auth with `requiresAuth: true`).
349
+ */
350
+ const isAuthBypassed = ({ path, method, getHeader, authConfig, customRouteAuthConfig, requiresAuth }) => {
351
+ if (!(typeof authConfig.authenticateToken === "function") && isDevPlaygroundRequest(path, method, getHeader, authConfig, customRouteAuthConfig)) return true;
352
+ if (!isProtectedPath(path, method, authConfig, customRouteAuthConfig)) return true;
353
+ return !requiresAuth && (canAccessPublicly(path, method, authConfig) || isCustomRoutePublic(path, method, customRouteAuthConfig));
354
+ };
355
+ /**
346
356
  * Single auth middleware: authenticate → authorize.
347
357
  * Skip checks (dev playground, unprotected path, public path) are evaluated once.
348
358
  */
349
359
  const coreAuthMiddleware = async (ctx) => {
350
- const { path, method, getHeader, mastra, authConfig, customRouteAuthConfig, requestContext, rawRequest, token, requiresAuth } = ctx;
351
- if (!(typeof authConfig.authenticateToken === "function") && isDevPlaygroundRequest(path, method, getHeader, authConfig, customRouteAuthConfig)) return pass;
352
- if (!isProtectedPath(path, method, authConfig, customRouteAuthConfig)) return pass;
353
- if (!requiresAuth && (canAccessPublicly(path, method, authConfig) || isCustomRoutePublic(path, method, customRouteAuthConfig))) return pass;
360
+ const { path, method, mastra, authConfig, customRouteAuthConfig, requestContext, rawRequest, token } = ctx;
361
+ if (isAuthBypassed(ctx)) return pass;
354
362
  let user;
355
363
  let refreshHeaders;
356
364
  const authRequest = adaptToMastraAuthRequest(rawRequest);
@@ -416,6 +424,12 @@ const coreAuthMiddleware = async (ctx) => {
416
424
  };
417
425
  requestContext.set(require_constants.MASTRA_USER_KEY, user);
418
426
  requestContext.set("user", user);
427
+ try {
428
+ const normalizedUser = ("toMastraUser" in authConfig && typeof authConfig.toMastraUser === "function" ? authConfig.toMastraUser : _mastra_core_server.normalizeMastraUser).call(authConfig, user);
429
+ if (normalizedUser && typeof normalizedUser.id === "string" && normalizedUser.id.trim()) requestContext.set(require_constants.MASTRA_NORMALIZED_USER_KEY, normalizedUser);
430
+ } catch (normalizeError) {
431
+ mastra.getLogger()?.warn("Failed to normalize authenticated user to MastraUser; callbacks will see user: undefined", { error: normalizeError instanceof Error ? { message: normalizeError.message } : normalizeError });
432
+ }
419
433
  let effectiveToken = token;
420
434
  if (!effectiveToken && rawRequest instanceof Request) {
421
435
  const cookieHeader = rawRequest.headers.get("cookie");
@@ -457,6 +471,11 @@ const coreAuthMiddleware = async (ctx) => {
457
471
  const roles = await rbacProvider.getRoles(user);
458
472
  requestContext.set(require_constants.MASTRA_USER_ROLES_KEY, roles);
459
473
  requestContext.set("userRoles", roles);
474
+ const normalizedUser = requestContext.get(require_constants.MASTRA_NORMALIZED_USER_KEY);
475
+ if (normalizedUser && !normalizedUser.role && Array.isArray(roles) && typeof roles[0] === "string") requestContext.set(require_constants.MASTRA_NORMALIZED_USER_KEY, {
476
+ ...normalizedUser,
477
+ role: roles[0]
478
+ });
460
479
  }
461
480
  }
462
481
  } catch (rbacError) {
@@ -615,6 +634,12 @@ Object.defineProperty(exports, "getAuthenticatedUser", {
615
634
  return getAuthenticatedUser;
616
635
  }
617
636
  });
637
+ Object.defineProperty(exports, "isAuthBypassed", {
638
+ enumerable: true,
639
+ get: function() {
640
+ return isAuthBypassed;
641
+ }
642
+ });
618
643
  Object.defineProperty(exports, "isCustomRoutePublic", {
619
644
  enumerable: true,
620
645
  get: function() {
@@ -664,4 +689,4 @@ Object.defineProperty(exports, "supportsSessionRefresh", {
664
689
  }
665
690
  });
666
691
 
667
- //# sourceMappingURL=helpers-0LJI4DxR.cjs.map
692
+ //# sourceMappingURL=helpers-Dpdta8ai.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"helpers-Dpdta8ai.cjs","names":["Hono","HonoRequest","HTTPException","MASTRA_USER_KEY","normalizeMastraUser","MASTRA_NORMALIZED_USER_KEY","MASTRA_AUTH_TOKEN_KEY","CompositeAuth","MASTRA_RESOURCE_ID_KEY","MASTRA_AUTH_MODE_KEY","MASTRA_USER_PERMISSIONS_KEY","MASTRA_USER_ROLES_KEY"],"sources":["../src/server/auth/custom-route-matcher.ts","../src/server/auth/defaults.ts","../src/server/auth/path-pattern.ts","../src/server/auth/helpers.ts"],"sourcesContent":["import { Hono } from 'hono';\nimport { HonoRequest } from 'hono/request';\n\n/** A custom route as the internal custom-route Hono app registers it. */\nexport interface CustomRouteMatcherEntry {\n method: string;\n path: string;\n /**\n * How many handlers (route middleware + handler) the route registers. Hono stores\n * each one as its own router entry, so mirror the count to build the same router.\n */\n handlerCount?: number;\n}\n\nexport interface CustomRouteMatch<T> {\n entry: T;\n index: number;\n params: Record<string, string>;\n}\n\ntype Marker = (...args: unknown[]) => undefined;\n\nconst noopMiddleware: Marker = () => undefined;\nconst paramRequest = new Request('http://localhost/');\n\n/**\n * Answers \"which custom route will run for this request?\" using the same Hono router\n * the custom-route bridge dispatches with (`buildCustomRouteHandler`), registered in\n * the same order with the same paths and methods. Auth decisions use this instead\n * of a separate pattern matcher, so they can't disagree with dispatch on precedence,\n * case, trailing slashes, percent-decoding or HEAD handling.\n */\nexport class CustomRouteMatcher<T extends CustomRouteMatcherEntry> {\n readonly #app = new Hono();\n readonly #indexByHandler = new Map<unknown, number>();\n readonly #entries: readonly T[];\n\n constructor(entries: readonly T[]) {\n this.#entries = entries;\n // Same global middleware as the custom-route app, so the router sees the same table.\n this.#app.use('*', noopMiddleware as never);\n entries.forEach((entry, index) => {\n const marker: Marker = () => undefined;\n this.#indexByHandler.set(marker, index);\n const handlers = Array.from({ length: Math.max(1, entry.handlerCount ?? 1) }, () => marker as never);\n if (entry.method === 'ALL') {\n this.#app.all(entry.path, handlers[0]!, ...handlers.slice(1));\n } else {\n this.#app.on(entry.method, entry.path, handlers[0]!, ...handlers.slice(1));\n }\n });\n }\n\n /**\n * Match a path the way Hono dispatches it, i.e. `path` is already in the form\n * `getPath()` returns (no query string, percent-decoded once).\n * Throws if Hono can't build a router for the registered paths.\n */\n matchPath(path: string, method: string): CustomRouteMatch<T> | undefined {\n const upper = method.toUpperCase();\n // Hono serves HEAD with the GET handler.\n const dispatchMethod = upper === 'HEAD' ? 'GET' : upper;\n const result = this.#app.router.match(dispatchMethod, path);\n const handlers = result[0];\n for (let i = 0; i < handlers.length; i++) {\n const index = this.#indexByHandler.get(handlers[i]![0][0]);\n if (index === undefined) continue; // the global middleware\n const request = new HonoRequest(paramRequest, path, result as never);\n request.routeIndex = i;\n return { entry: this.#entries[index]!, index, params: request.param() as Record<string, string> };\n }\n return undefined;\n }\n\n /**\n * Match the full URL handed to the custom-route app. Parses it the same way\n * (`new Request(url)` then Hono's `getPath`), so dot segments, encoded characters\n * and the query string are handled exactly as dispatch handles them.\n * Throws if the URL can't be parsed.\n */\n matchUrl(url: string, method: string): CustomRouteMatch<T> | undefined {\n const path = this.#app.getPath(new Request(url));\n return this.matchPath(path, method);\n }\n\n /**\n * Converts a raw request path (as Express/Koa/Fastify see it, not yet decoded) to\n * the path Hono would dispatch when the bridge forwards it. Throws on an\n * unparseable path.\n */\n dispatchPathForRawPath(rawPath: string): string {\n return this.#app.getPath(new Request(`http://localhost${rawPath}`));\n }\n}\n\nconst MAX_CACHED_MATCHERS = 32;\nconst matcherCache = new Map<string, CustomRouteMatcher<CustomRouteMatcherEntry & { key: string }>>();\n\n/**\n * Builds (and caches) a matcher from `customRouteAuthConfig` keys. Keys are\n * `METHOD:path` in registration order, which is the order the server registers\n * custom routes with the custom-route app.\n */\nexport function getCustomRouteAuthConfigMatcher(\n keys: readonly string[],\n): CustomRouteMatcher<CustomRouteMatcherEntry & { key: string }> {\n const signature = JSON.stringify(keys);\n const cached = matcherCache.get(signature);\n if (cached) {\n matcherCache.delete(signature);\n matcherCache.set(signature, cached);\n return cached;\n }\n\n const entries: Array<CustomRouteMatcherEntry & { key: string }> = [];\n for (const key of keys) {\n const colonIndex = key.indexOf(':');\n if (colonIndex === -1) continue; // malformed key\n entries.push({ key, method: key.substring(0, colonIndex).toUpperCase(), path: key.substring(colonIndex + 1) });\n }\n\n const matcher = new CustomRouteMatcher(entries);\n matcherCache.set(signature, matcher);\n if (matcherCache.size > MAX_CACHED_MATCHERS) {\n matcherCache.delete(matcherCache.keys().next().value!);\n }\n return matcher;\n}\n","import type { MastraAuthConfig } from '@mastra/core/server';\n\n// Default configuration that can be extended by clients\nexport const defaultAuthConfig: MastraAuthConfig = {\n protected: ['/api/*'],\n public: ['/api', '/api/auth/*'],\n // Simple rule system\n rules: [\n // Admin users can do anything\n {\n condition: user => {\n if (typeof user === 'object' && user !== null) {\n if ('isAdmin' in user) {\n return !!user.isAdmin;\n }\n\n if ('role' in user) {\n return user.role === 'admin';\n }\n }\n return false;\n },\n allow: true,\n },\n ],\n};\n","/**\n * Path pattern matching utility\n * Inlined from regexparam v3.0.0 (MIT License)\n * https://github.com/lukeed/regexparam\n *\n * Copyright (c) Luke Edwards <luke.edwards05@gmail.com> (lukeed.com)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nexport interface ParsedPattern {\n keys: string[] | false;\n pattern: RegExp;\n}\n\n/**\n * Parse a route pattern into a RegExp\n * Supports:\n * - Named parameters: /users/:id\n * - Optional parameters: /users/:id?\n * - Wildcards: /files/*\n * - Mixed patterns: /api/:version/users/:id\n */\nexport function parse(input: string | RegExp, loose?: boolean): ParsedPattern {\n if (input instanceof RegExp) return { keys: false, pattern: input };\n\n let c: string;\n let o: number;\n let tmp: string | undefined;\n let ext: number;\n const keys: string[] = [];\n let pattern = '';\n const arr = input.split('/');\n\n arr[0] || arr.shift();\n\n while ((tmp = arr.shift())) {\n c = tmp[0]!;\n if (c === '*') {\n keys.push(c);\n pattern += tmp[1] === '?' ? '(?:/(.*))?' : '/(.*)';\n } else if (c === ':') {\n o = tmp.indexOf('?', 1);\n ext = tmp.indexOf('.', 1);\n keys.push(tmp.substring(1, ~o ? o : ~ext ? ext : tmp.length));\n pattern += !!~o && !~ext ? '(?:/([^/]+?))?' : '/([^/]+?)';\n if (~ext) pattern += (~o ? '?' : '') + '\\\\' + tmp.substring(ext);\n } else {\n // Escape regex metacharacters so static segments stay literal. Without this,\n // a public route like '/a.b' would also match '/axb' and could skip auth for\n // a later protected route the framework dispatches instead.\n pattern += '/' + tmp.replace(/([.+*?^${}()|[\\]\\\\])/g, '\\\\$1');\n }\n }\n\n return {\n keys: keys,\n pattern: new RegExp('^' + pattern + (loose ? '(?=$|/)' : '/?$'), 'i'),\n };\n}\n\n/**\n * Test if a path matches a pattern\n */\nexport function matchPath(path: string, pattern: string | RegExp): boolean {\n const { pattern: regex } = parse(pattern);\n return regex.test(path);\n}\n","import type { ISessionProvider, MastraUser } from '@mastra/core/auth';\nimport type { IRBACProvider, EEUser } from '@mastra/core/auth/ee';\nimport type { Mastra } from '@mastra/core/mastra';\nimport { CompositeAuth, normalizeMastraUser } from '@mastra/core/server';\nimport type { ApiRoute, IMastraAuthProvider, MastraAuthConfig, MastraAuthRequest } from '@mastra/core/server';\n\nimport {\n MASTRA_RESOURCE_ID_KEY,\n MASTRA_USER_KEY,\n MASTRA_NORMALIZED_USER_KEY,\n MASTRA_USER_PERMISSIONS_KEY,\n MASTRA_USER_ROLES_KEY,\n MASTRA_AUTH_TOKEN_KEY,\n MASTRA_AUTH_MODE_KEY,\n} from '../constants';\nimport { HTTPException } from '../http-exception';\nimport { CustomRouteMatcher, getCustomRouteAuthConfigMatcher } from './custom-route-matcher';\nimport { defaultAuthConfig } from './defaults';\nimport { parse } from './path-pattern';\n\n// Re-export request-context key constants so custom middleware can read namespaced\n// auth state without importing internal paths.\nexport {\n MASTRA_USER_KEY,\n MASTRA_NORMALIZED_USER_KEY,\n MASTRA_USER_PERMISSIONS_KEY,\n MASTRA_USER_ROLES_KEY,\n} from '../constants';\n\ntype CustomRouteAuthDecision = 'protected' | 'public' | 'none';\n\n/**\n * Decide auth for a request from the custom route the custom-route app will dispatch\n * it to (see `CustomRouteMatcher`), not from whichever pattern happens to match.\n *\n * Fails closed:\n * - an exact `METHOD:path` (or `ALL:path`) entry that requires auth always wins, so a\n * path registered as protected is never served without auth;\n * - `path` may be a raw request path (Express, Koa, Fastify) or one Hono already\n * decoded, so it's resolved both ways and is only public if every reading lands on\n * a public route, and protected if any reading lands on a protected one;\n * - if the routes or the path can't be parsed, the request is treated as protected.\n */\nconst resolveCustomRouteAuth = (\n path: string,\n method: string,\n customRouteAuthConfig: Map<string, boolean>,\n): CustomRouteAuthDecision => {\n const upperMethod = method.toUpperCase();\n const methods = upperMethod === 'HEAD' ? ['HEAD', 'GET'] : [upperMethod];\n for (const m of methods) {\n if (customRouteAuthConfig.get(`${m}:${path}`) === true || customRouteAuthConfig.get(`ALL:${path}`) === true) {\n return 'protected';\n }\n }\n\n // Adapters pin the current request by appending `METHOD:path` to a copy of the map.\n // As the last entry it only decides when no earlier route matches, so resolve the\n // rest with a cached matcher and fall back to it, instead of building a new router\n // for every request path.\n const keys = [...customRouteAuthConfig.keys()];\n const lastKey = keys[keys.length - 1];\n const pinnedKey =\n lastKey !== undefined && methods.some(m => lastKey === `${m}:${path}` || lastKey === `ALL:${path}`)\n ? lastKey\n : undefined;\n\n let matcher: ReturnType<typeof getCustomRouteAuthConfigMatcher>;\n const candidates = new Set<string>([path]);\n try {\n matcher = getCustomRouteAuthConfigMatcher(pinnedKey ? keys.slice(0, -1) : keys);\n candidates.add(matcher.dispatchPathForRawPath(path));\n } catch {\n return 'protected';\n }\n\n let matchedPublic = false;\n let unmatched = false;\n for (const candidate of candidates) {\n let key: string | undefined;\n try {\n key = matcher.matchPath(candidate, upperMethod)?.entry.key;\n } catch {\n return 'protected';\n }\n if (key === undefined && pinnedKey && candidate === path) {\n key = pinnedKey;\n }\n if (key === undefined) {\n unmatched = true;\n continue;\n }\n if (customRouteAuthConfig.get(key) !== false) {\n return 'protected';\n }\n matchedPublic = true;\n }\n\n return matchedPublic && !unmatched ? 'public' : 'none';\n};\n\n/**\n * Check if a request will be handled by a registered custom route that requires\n * authentication. The route that decides is the one the custom-route app dispatches\n * to (first registered match), using Hono's own matching. Returns false when no\n * custom route handles the request.\n */\nexport const isProtectedCustomRoute = (\n path: string,\n method: string,\n customRouteAuthConfig?: Map<string, boolean>,\n): boolean => {\n if (!customRouteAuthConfig || customRouteAuthConfig.size === 0) {\n return false;\n }\n return resolveCustomRouteAuth(path, method, customRouteAuthConfig) === 'protected';\n};\n\nconst apiRouteMatchers = new WeakMap<\n readonly ApiRoute[],\n { signature: string; matcher: CustomRouteMatcher<ApiRoute> }\n>();\n\n/**\n * Find the custom API route Hono dispatches `path` to, with its decoded path params.\n * `path` is in the form Hono's `c.req.path` returns (no query string, decoded once).\n * Matching follows Hono: first registered match wins, case-sensitive, strict\n * trailing slash, and HEAD is served by GET routes.\n */\nexport const findMatchingCustomRoute = (\n path: string,\n method: string,\n apiRoutes?: ApiRoute[],\n): { route: ApiRoute; params: Record<string, string> } | undefined => {\n if (!apiRoutes || apiRoutes.length === 0) return undefined;\n\n const signature = JSON.stringify(apiRoutes.map(route => `${route.method}:${route.path}`));\n let cached = apiRouteMatchers.get(apiRoutes);\n if (!cached || cached.signature !== signature) {\n cached = { signature, matcher: new CustomRouteMatcher(apiRoutes) };\n apiRouteMatchers.set(apiRoutes, cached);\n }\n\n try {\n const match = cached.matcher.matchPath(path, method);\n return match ? { route: match.entry, params: match.params } : undefined;\n } catch {\n // Hono can't route these paths either, so no custom route handles the request.\n return undefined;\n }\n};\n\n/**\n * Check if request is from dev playground\n * @param getHeader - Function to get header value from request\n * @param customRouteAuthConfig - Map of custom route auth configurations\n */\nexport const isDevPlaygroundRequest = (\n path: string,\n method: string,\n getHeader: (name: string) => string | undefined,\n authConfig: MastraAuthConfig,\n customRouteAuthConfig?: Map<string, boolean>,\n): boolean => {\n const protectedAccess = [...(defaultAuthConfig.protected || []), ...(authConfig.protected || [])];\n return (\n process.env.MASTRA_DEV === 'true' &&\n // Allow if path doesn't match protected patterns AND is not a protected custom route\n ((!isAnyMatch(path, method, protectedAccess) && !isProtectedCustomRoute(path, method, customRouteAuthConfig)) ||\n // Or if has playground header\n getHeader('x-mastra-dev-playground') === 'true')\n );\n};\n\n/**\n * Check if a request will be handled by a custom route registered as public\n * (`requiresAuth: false`). Uses the same dispatch-order resolution as\n * `isProtectedCustomRoute`, and returns false (not public) when no custom route\n * handles the request or the answer is ambiguous.\n */\nexport const isCustomRoutePublic = (\n path: string,\n method: string,\n customRouteAuthConfig?: Map<string, boolean>,\n): boolean => {\n if (!customRouteAuthConfig || customRouteAuthConfig.size === 0) {\n return false;\n }\n return resolveCustomRouteAuth(path, method, customRouteAuthConfig) === 'public';\n};\n\n// NOTE: This uses isProtectedCustomRoute (default-allow for unknown paths) rather than\n// !isCustomRoutePublic (default-deny). This is intentional — all registered server and\n// custom routes are auth-checked via registerRoute/checkRouteAuth regardless of this\n// function. The '/api/*' protected pattern exists as a user-facing override mechanism.\n// The old default-deny logic incorrectly blocked non-API paths (e.g. '/', '/agents')\n// which prevented the studio login page from loading in production.\nexport const isProtectedPath = (\n path: string,\n method: string,\n authConfig: MastraAuthConfig,\n customRouteAuthConfig?: Map<string, boolean>,\n): boolean => {\n const protectedAccess = [...(defaultAuthConfig.protected || []), ...(authConfig.protected || [])];\n return isAnyMatch(path, method, protectedAccess) || isProtectedCustomRoute(path, method, customRouteAuthConfig);\n};\n\nexport const canAccessPublicly = (path: string, method: string, authConfig: MastraAuthConfig): boolean => {\n // Check if this path+method combination is publicly accessible\n const publicAccess = [...(defaultAuthConfig.public || []), ...(authConfig.public || [])];\n\n return isAnyMatch(path, method, publicAccess);\n};\n\nconst isAnyMatch = (\n path: string,\n method: string,\n patterns: MastraAuthConfig['protected'] | MastraAuthConfig['public'],\n): boolean => {\n if (!patterns) {\n return false;\n }\n\n for (const patternPathOrMethod of patterns) {\n if (patternPathOrMethod instanceof RegExp) {\n if (patternPathOrMethod.test(path)) {\n return true;\n }\n }\n\n if (typeof patternPathOrMethod === 'string' && pathMatchesPattern(path, patternPathOrMethod)) {\n return true;\n }\n\n if (Array.isArray(patternPathOrMethod) && patternPathOrMethod.length === 2) {\n const [pattern, methodOrMethods] = patternPathOrMethod;\n if (pathMatchesPattern(path, pattern) && matchesOrIncludes(methodOrMethods, method)) {\n return true;\n }\n }\n }\n\n return false;\n};\n\nexport const pathMatchesPattern = (path: string, pattern: string): boolean => {\n // Use regexparam for battle-tested path matching\n // Supports:\n // - Exact paths: '/api/users'\n // - Wildcards: '/api/agents/*' matches '/api/agents/123'\n // - Path parameters: '/users/:id' matches '/users/123'\n // - Optional parameters: '/users/:id?' matches '/users' and '/users/123'\n // - Mixed patterns: '/api/:version/users/:id/profile'\n const { pattern: regex } = parse(pattern);\n return regex.test(path);\n};\n\nexport const pathMatchesRule = (path: string, rulePath: string | RegExp | string[] | undefined): boolean => {\n if (!rulePath) return true; // No path specified means all paths\n\n if (typeof rulePath === 'string') {\n return pathMatchesPattern(path, rulePath);\n }\n\n if (rulePath instanceof RegExp) {\n return rulePath.test(path);\n }\n\n if (Array.isArray(rulePath)) {\n return rulePath.some(p => pathMatchesPattern(path, p));\n }\n\n return false;\n};\n\nexport const matchesOrIncludes = (values: string | string[], value: string): boolean => {\n if (typeof values === 'string') {\n return values === value;\n }\n\n if (Array.isArray(values)) {\n return values.includes(value);\n }\n\n return false;\n};\n\n// ── Core auth middleware ──\n// Framework-agnostic auth logic extracted from adapter middlewares.\n// Each adapter builds an AuthMiddlewareContext and delegates to coreAuthMiddleware.\n\nexport interface AuthMiddlewareContext {\n path: string;\n method: string;\n getHeader: (name: string) => string | undefined;\n mastra: Mastra;\n authConfig: MastraAuthConfig;\n customRouteAuthConfig?: Map<string, boolean>;\n requestContext: { get: (key: string) => unknown; set: (key: string, value: unknown) => void };\n rawRequest: MastraAuthRequest;\n token: string | null;\n buildAuthorizeContext: () => unknown;\n /** When true, force authentication even if the path matches a public pattern. */\n requiresAuth?: boolean;\n}\n\nexport type AuthResult =\n | { action: 'next'; headers?: Record<string, string> }\n | { action: 'error'; status: number; body: Record<string, unknown>; headers?: Record<string, string> };\n\nconst pass: AuthResult = { action: 'next' };\n\n/**\n * Lets an app's `authorize(path, method, user, context)` read `context.get('requestContext')` and\n * `context.get('mastra')` on every adapter, as it can on Hono, so per-caller values (the Knowledge scope) bind\n * the same way everywhere. Hono and NestJS contexts already answer `get`; Express, Fastify and Koa pass a web\n * Request, Elysia its own context, and adapters with no builder pass nothing.\n */\nconst withAuthorizeVariables = (\n base: unknown,\n ctx: Pick<AuthMiddlewareContext, 'mastra' | 'requestContext' | 'customRouteAuthConfig' | 'rawRequest'>,\n): unknown => {\n const variables: Record<string, unknown> = {\n mastra: ctx.mastra,\n requestContext: ctx.requestContext,\n customRouteAuthConfig: ctx.customRouteAuthConfig,\n };\n const get = (key: string) => variables[key];\n if (base === null || base === undefined) {\n return { get, req: ctx.rawRequest };\n }\n if (typeof base === 'object' && typeof (base as { get?: unknown }).get !== 'function') {\n Object.defineProperty(base, 'get', { value: get, configurable: true });\n }\n return base;\n};\n\nconst adaptToMastraAuthRequest = (request: MastraAuthRequest): MastraAuthRequest => {\n if (!(request instanceof Request)) {\n return request;\n }\n\n return {\n raw: request,\n headers: request.headers,\n header: name => request.headers.get(name) ?? undefined,\n };\n};\n\nexport interface GetAuthenticatedUserOptions {\n mastra: Mastra;\n token: string;\n request: MastraAuthRequest;\n}\n\nexport const getAuthenticatedUser = async <TUser = unknown>({\n mastra,\n token,\n request,\n}: GetAuthenticatedUserOptions): Promise<TUser | null> => {\n const normalizedToken = token.replace(/^Bearer\\s+/i, '').trim();\n if (!normalizedToken) {\n return null;\n }\n\n const authConfig = mastra.getServer()?.auth;\n if (!authConfig || typeof authConfig.authenticateToken !== 'function') {\n return null;\n }\n\n return (await authConfig.authenticateToken(normalizedToken, request)) as TUser | null;\n};\n\n/**\n * Check if an auth config object supports transparent session refresh.\n * Returns true if the auth provider implements the necessary ISessionProvider methods.\n */\nexport function supportsSessionRefresh(\n authConfig: MastraAuthConfig | IMastraAuthProvider,\n): authConfig is (MastraAuthConfig | IMastraAuthProvider) &\n Pick<ISessionProvider, 'refreshSession' | 'getSessionIdFromRequest' | 'getSessionHeaders'> {\n return (\n typeof (authConfig as any).getSessionIdFromRequest === 'function' &&\n typeof (authConfig as any).refreshSession === 'function' &&\n typeof (authConfig as any).getSessionHeaders === 'function'\n );\n}\n\n/**\n * Whether auth is bypassed for this path/method: the dev playground (only when no auth\n * provider is configured), paths that are not protected, and public paths (unless the\n * route forces auth with `requiresAuth: true`).\n */\nexport const isAuthBypassed = ({\n path,\n method,\n getHeader,\n authConfig,\n customRouteAuthConfig,\n requiresAuth,\n}: Pick<\n AuthMiddlewareContext,\n 'path' | 'method' | 'getHeader' | 'authConfig' | 'customRouteAuthConfig' | 'requiresAuth'\n>): boolean => {\n // Only bypass auth for dev playground when no real auth provider is configured.\n // When auth IS configured (has authenticateToken), we need the full auth flow\n // so user/roles/permissions are set in requestContext.\n const hasAuthProvider = typeof authConfig.authenticateToken === 'function';\n if (!hasAuthProvider && isDevPlaygroundRequest(path, method, getHeader, authConfig, customRouteAuthConfig)) {\n return true;\n }\n\n if (!isProtectedPath(path, method, authConfig, customRouteAuthConfig)) {\n return true;\n }\n\n // When a route explicitly requires auth (requiresAuth: true), skip the\n // public-path bypass so the user is still authenticated and permissions\n // are injected into the request context.\n return (\n !requiresAuth &&\n (canAccessPublicly(path, method, authConfig) || isCustomRoutePublic(path, method, customRouteAuthConfig))\n );\n};\n\n/**\n * Single auth middleware: authenticate → authorize.\n * Skip checks (dev playground, unprotected path, public path) are evaluated once.\n */\nexport const coreAuthMiddleware = async (ctx: AuthMiddlewareContext): Promise<AuthResult> => {\n const { path, method, mastra, authConfig, customRouteAuthConfig, requestContext, rawRequest, token } = ctx;\n\n // ── Skip checks (evaluated once) ──\n\n if (isAuthBypassed(ctx)) {\n return pass;\n }\n\n // ── Authentication ──\n\n let user: unknown;\n let refreshHeaders: Record<string, string> | undefined;\n const authRequest = adaptToMastraAuthRequest(rawRequest);\n\n type ConsumePendingResponseHeadersFn = (request: typeof authRequest) => Record<string, string> | undefined;\n const mergePendingProviderHeaders = (request: typeof authRequest = authRequest) => {\n const consume = (authConfig as { consumePendingResponseHeaders?: ConsumePendingResponseHeadersFn })\n .consumePendingResponseHeaders;\n if (typeof consume !== 'function') return;\n let pending: Record<string, string> | undefined;\n try {\n pending = consume.call(authConfig, request);\n } catch {\n // Forwarding a rotated cookie is best-effort; never fail auth over it.\n return;\n }\n if (!pending) return;\n refreshHeaders = { ...(refreshHeaders ?? {}), ...pending };\n };\n\n try {\n if (typeof authConfig.authenticateToken === 'function') {\n user = await authConfig.authenticateToken(token ?? '', authRequest);\n mergePendingProviderHeaders();\n } else {\n throw new Error('No token verification method configured');\n }\n\n // If authentication failed, attempt transparent session refresh before returning 401.\n // This handles expired access tokens without requiring client-side refresh logic.\n if (!user && supportsSessionRefresh(authConfig) && rawRequest instanceof Request) {\n let retryHttpError: HTTPException | undefined;\n try {\n const sessionId = authConfig.getSessionIdFromRequest(rawRequest);\n if (sessionId) {\n const newSession = await authConfig.refreshSession(sessionId);\n if (newSession) {\n // Refresh succeeded — build updated session headers and re-authenticate.\n // We create a synthetic request with the new session cookie so\n // authenticateToken (which reads cookies from the request) picks up\n // the refreshed session instead of the expired one.\n refreshHeaders = authConfig.getSessionHeaders(newSession);\n const refreshedCookie = Object.entries(refreshHeaders)\n .filter(([k]) => k.toLowerCase() === 'set-cookie')\n .map(([, v]) => v.split(';')[0]) // Extract name=value before attributes\n .join('; ');\n if (refreshedCookie) {\n const refreshedRequest = new Request(rawRequest.url, {\n method: rawRequest.method,\n headers: new Headers(rawRequest.headers),\n });\n refreshedRequest.headers.set('Cookie', refreshedCookie);\n // Pass the refreshed cookie value as the token so authenticateToken\n // picks up the new session instead of the stale original.\n // Auth providers typically read cookies from the request object, but\n // some may also inspect the token parameter directly.\n const cookieValue = refreshedCookie.includes('=')\n ? refreshedCookie.split('=').slice(1).join('=')\n : refreshedCookie;\n try {\n const retryAuthRequest = adaptToMastraAuthRequest(refreshedRequest);\n user = await authConfig.authenticateToken(cookieValue, retryAuthRequest);\n mergePendingProviderHeaders(retryAuthRequest);\n } catch (retryErr) {\n retryHttpError = retryErr instanceof HTTPException ? retryErr : undefined;\n throw retryErr;\n }\n }\n if (!user) {\n refreshHeaders = undefined;\n }\n }\n }\n } catch (refreshErr) {\n refreshHeaders = undefined;\n // An explicit HTTP error from the retried authenticateToken goes to the outer handler.\n if (retryHttpError === refreshErr) throw refreshErr;\n mastra.getLogger()?.debug('Session refresh failed, falling back to 401', {\n error: refreshErr instanceof Error ? { message: refreshErr.message } : refreshErr,\n });\n }\n }\n\n if (!user) {\n return { action: 'error', status: 401, body: { error: 'Invalid or expired token' }, headers: refreshHeaders };\n }\n\n requestContext.set(MASTRA_USER_KEY, user);\n // Backward-compat: also write the legacy `'user'` key so existing\n // middleware and integrations that read `requestContext.get('user')`\n // (including built-in FGA route enforcement, memory handlers, and the\n // documented public surface) keep working. New code should prefer\n // `MASTRA_USER_KEY` to avoid collisions with caller-supplied keys.\n requestContext.set('user', user);\n\n // Normalize the authenticated user to the stable MastraUser shape consumed\n // by DynamicArgument callbacks. Must run before mapUserToResourceId:\n // CompositeAuth's resource-id mapping consumes its authenticated-provider\n // bookkeeping while toMastraUser only peeks at it. Best-effort — a user\n // shape the default normalization can't handle leaves the key unset\n // (callbacks see `user: undefined`) instead of failing the request.\n try {\n const toMastraUser =\n 'toMastraUser' in authConfig && typeof authConfig.toMastraUser === 'function'\n ? (authConfig.toMastraUser as (user: unknown) => MastraUser)\n : normalizeMastraUser;\n const normalizedUser = toMastraUser.call(authConfig, user);\n if (normalizedUser && typeof normalizedUser.id === 'string' && normalizedUser.id.trim()) {\n requestContext.set(MASTRA_NORMALIZED_USER_KEY, normalizedUser);\n }\n } catch (normalizeError) {\n mastra\n .getLogger()\n ?.warn('Failed to normalize authenticated user to MastraUser; callbacks will see user: undefined', {\n error: normalizeError instanceof Error ? { message: normalizeError.message } : normalizeError,\n });\n }\n\n // Store the raw auth token so downstream code (e.g., editor MCP client\n // resolution) can forward it when connecting to auth-protected MCP servers.\n // The token may arrive via Authorization header, apiKey query param, or\n // cookie (SimpleAuth sets `mastra-token`). Check all sources so the\n // forwarded value is available regardless of how the user authenticated.\n let effectiveToken = token;\n if (!effectiveToken && rawRequest instanceof Request) {\n const cookieHeader = rawRequest.headers.get('cookie');\n if (cookieHeader) {\n const match = cookieHeader.match(/mastra-token=([^;]+)/);\n if (match?.[1]) effectiveToken = match[1];\n }\n }\n if (effectiveToken) {\n requestContext.set(MASTRA_AUTH_TOKEN_KEY, effectiveToken);\n }\n\n if (typeof authConfig.mapUserToResourceId === 'function') {\n try {\n const resourceId = authConfig.mapUserToResourceId(user);\n // CompositeAuth validates the authenticating provider's mapper. It can\n // return undefined when that provider never configured a mapper.\n if (resourceId !== undefined || !(authConfig instanceof CompositeAuth)) {\n if (typeof resourceId !== 'string' || !resourceId.trim()) {\n throw new Error('mapUserToResourceId must return a non-empty string for the authenticated user');\n }\n requestContext.set(MASTRA_RESOURCE_ID_KEY, resourceId);\n }\n } catch (mapError) {\n mastra.getLogger()?.error('mapUserToResourceId failed', {\n error: mapError instanceof Error ? { message: mapError.message, stack: mapError.stack } : mapError,\n });\n return {\n action: 'error',\n status: 500,\n body: { error: 'Failed to map authenticated user to a resource ID' },\n headers: refreshHeaders,\n };\n }\n }\n\n try {\n // Determine which RBAC provider to use based on auth mode\n const authMode = requestContext.get(MASTRA_AUTH_MODE_KEY);\n const serverConfig = mastra.getServer();\n const studioConfig = mastra.getStudio?.();\n // Use studio RBAC if this is a studio request, otherwise use server RBAC\n const rbacProvider = (authMode === 'studio' ? (studioConfig?.rbac ?? serverConfig?.rbac) : serverConfig?.rbac) as\n | IRBACProvider<EEUser>\n | undefined;\n\n if (rbacProvider) {\n if (!user || typeof user !== 'object' || !('id' in user)) {\n mastra.getLogger()?.warn('RBAC: authenticated user missing required \"id\" field, skipping permission loading');\n } else {\n const permissions = await rbacProvider.getPermissions(user as EEUser);\n requestContext.set(MASTRA_USER_PERMISSIONS_KEY, permissions);\n // Backward-compat alias for callers reading the legacy key.\n requestContext.set('userPermissions', permissions);\n\n const roles = await rbacProvider.getRoles(user as EEUser);\n requestContext.set(MASTRA_USER_ROLES_KEY, roles);\n // Backward-compat alias for callers reading the legacy key.\n requestContext.set('userRoles', roles);\n\n // Populate the normalized user's role from RBAC when the auth\n // provider's user carried none: primary role = first RBAC role.\n const normalizedUser = requestContext.get(MASTRA_NORMALIZED_USER_KEY) as MastraUser | undefined;\n if (normalizedUser && !normalizedUser.role && Array.isArray(roles) && typeof roles[0] === 'string') {\n requestContext.set(MASTRA_NORMALIZED_USER_KEY, { ...normalizedUser, role: roles[0] });\n }\n }\n }\n } catch (rbacError) {\n mastra.getLogger()?.error('RBAC: failed to load user permissions/roles', {\n error: rbacError instanceof Error ? { message: rbacError.message, stack: rbacError.stack } : rbacError,\n });\n }\n } catch (err) {\n mastra.getLogger()?.error('Authentication error', {\n error: err instanceof Error ? { message: err.message, stack: err.stack } : err,\n });\n // Explicit HTTP errors from auth callbacks keep their status/message; anything else is redacted.\n // The HTTPException message is sent to the client, so callers must keep it safe (no internal details).\n if (err instanceof HTTPException && err.status >= 400 && err.status <= 599) {\n return { action: 'error', status: err.status, body: { error: err.message }, headers: refreshHeaders };\n }\n return { action: 'error', status: 401, body: { error: 'Invalid or expired token' }, headers: refreshHeaders };\n }\n\n // ── Authorization ──\n\n const authorizationError = await authorizeAuthenticatedUser({\n path,\n method,\n user,\n mastra,\n authConfig,\n customRouteAuthConfig,\n requestContext,\n rawRequest,\n buildAuthorizeContext: ctx.buildAuthorizeContext,\n });\n if (authorizationError) {\n return { action: 'error', ...authorizationError, headers: refreshHeaders };\n }\n\n return refreshHeaders ? { action: 'next', headers: refreshHeaders } : pass;\n};\n\nexport interface AuthorizeAuthenticatedUserContext {\n path: string;\n method: string;\n user: unknown;\n mastra: Mastra;\n authConfig: MastraAuthConfig;\n customRouteAuthConfig?: Map<string, boolean>;\n requestContext: AuthMiddlewareContext['requestContext'];\n rawRequest: MastraAuthRequest;\n buildAuthorizeContext: () => unknown;\n}\n\n/**\n * The authorization step of server auth for an already authenticated user:\n * `authorizeUser`, `authorize(path, method, user)`, `rules`, or the RBAC default rules.\n * Returns null when the user may access `method path`.\n */\nexport const authorizeAuthenticatedUser = async (\n ctx: AuthorizeAuthenticatedUserContext,\n): Promise<{ status: number; body: Record<string, unknown> } | null> => {\n const { path, method, user, mastra, authConfig, requestContext, rawRequest } = ctx;\n const denied = { status: 403, body: { error: 'Access denied' } };\n\n if ('authorizeUser' in authConfig && typeof authConfig.authorizeUser === 'function') {\n try {\n const isAuthorized = await authConfig.authorizeUser(user, adaptToMastraAuthRequest(rawRequest));\n return isAuthorized ? null : denied;\n } catch (err) {\n mastra.getLogger()?.error('Authorization error in authorizeUser', {\n error: err instanceof Error ? { message: err.message, stack: err.stack } : err,\n });\n return { status: 500, body: { error: 'Authorization error' } };\n }\n }\n\n if ('authorize' in authConfig && typeof authConfig.authorize === 'function') {\n try {\n const authorizeCtx = withAuthorizeVariables(ctx.buildAuthorizeContext(), {\n mastra,\n requestContext,\n customRouteAuthConfig: ctx.customRouteAuthConfig,\n rawRequest,\n });\n const isAuthorized = await authConfig.authorize(path, method, user, authorizeCtx as any);\n return isAuthorized ? null : denied;\n } catch (err) {\n mastra.getLogger()?.error('Authorization error in authorize', {\n error: err instanceof Error ? { message: err.message, stack: err.stack } : err,\n path,\n method,\n });\n return { status: 500, body: { error: 'Authorization error' } };\n }\n }\n\n if ('rules' in authConfig && authConfig.rules && authConfig.rules.length > 0) {\n return (await checkRules(authConfig.rules, path, method, user)) ? null : denied;\n }\n\n // No explicit authorization configured (authorizeUser, authorize, or rules)\n // Check if RBAC is configured - if not, allow authenticated users through\n // (auth-only mode = authenticated users get full access)\n const rbacProvider =\n requestContext.get(MASTRA_AUTH_MODE_KEY) === 'studio'\n ? (mastra.getStudio?.()?.rbac ?? mastra.getServer()?.rbac)\n : mastra.getServer()?.rbac;\n if (rbacProvider) {\n if (defaultAuthConfig.rules && defaultAuthConfig.rules.length > 0) {\n return (await checkRules(defaultAuthConfig.rules, path, method, user)) ? null : denied;\n }\n return denied;\n }\n\n return null;\n};\n\n// Check authorization rules\nexport const checkRules = async (\n rules: MastraAuthConfig['rules'],\n path: string,\n method: string,\n user: unknown,\n): Promise<boolean> => {\n // Go through rules in order (first match wins)\n for (const i in rules || []) {\n const rule = rules?.[i]!;\n // Check if rule applies to this path\n if (!pathMatchesRule(path, rule.path)) {\n continue;\n }\n\n // Check if rule applies to this method\n if (rule.methods && !matchesOrIncludes(rule.methods, method)) {\n continue;\n }\n\n // Rule matches, so it decides. A failed condition denies instead of\n // falling through to a broader rule further down the list.\n const condition = rule.condition;\n if (typeof condition === 'function') {\n return await Promise.resolve()\n .then(() => condition(user))\n .then(result => !!result)\n .catch(() => false);\n }\n return !!rule.allow;\n }\n\n // No matching rules, deny by default\n return false;\n};\n"],"mappings":";;;;;;AAsBA,MAAM,uBAA+B,KAAA;AACrC,MAAM,eAAe,IAAI,QAAQ,mBAAmB;;;;;;;;AASpD,IAAa,qBAAb,MAAmE;CACjE,OAAgB,IAAIA,KAAAA,KAAK;CACzB,kCAA2B,IAAI,IAAqB;CACpD;CAEA,YAAY,SAAuB;EACjC,KAAK,WAAW;EAEhB,KAAK,KAAK,IAAI,KAAK,cAAuB;EAC1C,QAAQ,SAAS,OAAO,UAAU;GAChC,MAAM,eAAuB,KAAA;GAC7B,KAAK,gBAAgB,IAAI,QAAQ,KAAK;GACtC,MAAM,WAAW,MAAM,KAAK,EAAE,QAAQ,KAAK,IAAI,GAAG,MAAM,gBAAgB,CAAC,EAAE,SAAS,MAAe;GACnG,IAAI,MAAM,WAAW,OACnB,KAAK,KAAK,IAAI,MAAM,MAAM,SAAS,IAAK,GAAG,SAAS,MAAM,CAAC,CAAC;QAE5D,KAAK,KAAK,GAAG,MAAM,QAAQ,MAAM,MAAM,SAAS,IAAK,GAAG,SAAS,MAAM,CAAC,CAAC;EAE7E,CAAC;CACH;;;;;;CAOA,UAAU,MAAc,QAAiD;EACvE,MAAM,QAAQ,OAAO,YAAY;EAEjC,MAAM,iBAAiB,UAAU,SAAS,QAAQ;EAClD,MAAM,SAAS,KAAK,KAAK,OAAO,MAAM,gBAAgB,IAAI;EAC1D,MAAM,WAAW,OAAO;EACxB,KAAK,IAAI,IAAI,GAAG,IAAI,SAAS,QAAQ,KAAK;GACxC,MAAM,QAAQ,KAAK,gBAAgB,IAAI,SAAS,EAAE,CAAE,EAAE,CAAC,EAAE;GACzD,IAAI,UAAU,KAAA,GAAW;GACzB,MAAM,UAAU,IAAIC,aAAAA,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AAK;EACvB,IAAI,OAAO,cAAc,YACvB,OAAO,MAAM,QAAQ,QAAQ,CAAC,CAC3B,WAAW,UAAU,IAAI,CAAC,CAAC,CAC3B,MAAK,WAAU,CAAC,CAAC,MAAM,CAAC,CACxB,YAAY,KAAK;EAEtB,OAAO,CAAC,CAAC,KAAK;CAChB;CAGA,OAAO;AACT"}
@@ -1,8 +1,8 @@
1
1
  const require_rolldown_runtime = require("./rolldown-runtime-10nMEhjP.cjs");
2
- const require_constants = require("./constants-DMg8hUOR.cjs");
3
- const require_utils = require("./utils-BXEJ6FZC.cjs");
2
+ const require_constants = require("./constants-1yTmKUZD.cjs");
3
+ const require_utils = require("./utils-DFhesFfA.cjs");
4
4
  const require_http_exception = require("./http-exception-Co3MbFUf.cjs");
5
- const require_route_builder = require("./route-builder-B9C5vT54.cjs");
5
+ const require_route_builder = require("./route-builder-DjTBxSZN.cjs");
6
6
  const require_server_handlers_error = require("./server/handlers/error.cjs");
7
7
  let zod_v4 = require("zod/v4");
8
8
  let _mastra_core_knowledge = require("@mastra/core/knowledge");
@@ -570,4 +570,4 @@ Object.defineProperty(exports, "STREAM_KNOWLEDGE_EVENTS_ROUTE", {
570
570
  }
571
571
  });
572
572
 
573
- //# sourceMappingURL=knowledge-CRkWkTBC.cjs.map
573
+ //# sourceMappingURL=knowledge-2fms70NN.cjs.map