@mastra/server 1.81.0-alpha.2 → 1.82.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (243) hide show
  1. package/dist/{a2a-eUB3oDRN.cjs → a2a-CIq9dtbC.cjs} +3 -3
  2. package/dist/{a2a-eUB3oDRN.cjs.map → a2a-CIq9dtbC.cjs.map} +1 -1
  3. package/dist/{a2a-UYs7rzN2.js → a2a-DULF2hBd.js} +3 -3
  4. package/dist/{a2a-UYs7rzN2.js.map → a2a-DULF2hBd.js.map} +1 -1
  5. package/dist/{agent-builder-DwfHzUnt.cjs → agent-builder-CX7Rgay-.cjs} +4 -4
  6. package/dist/{agent-builder-DwfHzUnt.cjs.map → agent-builder-CX7Rgay-.cjs.map} +1 -1
  7. package/dist/{agent-builder-5dpawFJf.js → agent-builder-C_H7OUVX.js} +4 -4
  8. package/dist/{agent-builder-5dpawFJf.js.map → agent-builder-C_H7OUVX.js.map} +1 -1
  9. package/dist/{agents-BuI0JjjX.js → agents-NRBk4JAs.js} +4 -4
  10. package/dist/{agents-BuI0JjjX.js.map → agents-NRBk4JAs.js.map} +1 -1
  11. package/dist/{agents-BjdRPzyV.cjs → agents-SvkxJW48.cjs} +4 -4
  12. package/dist/{agents-BjdRPzyV.cjs.map → agents-SvkxJW48.cjs.map} +1 -1
  13. package/dist/{api-schema-manifest-GgyfF4dw.cjs → api-schema-manifest-BMJwl8fK.cjs} +2 -2
  14. package/dist/{api-schema-manifest-GgyfF4dw.cjs.map → api-schema-manifest-BMJwl8fK.cjs.map} +1 -1
  15. package/dist/{api-schema-manifest-DafznVYs.js → api-schema-manifest-CEMyoduN.js} +2 -2
  16. package/dist/{api-schema-manifest-DafznVYs.js.map → api-schema-manifest-CEMyoduN.js.map} +1 -1
  17. package/dist/{background-tasks-BkYNmUcf.js → background-tasks-DhQ6upHK.js} +2 -2
  18. package/dist/{background-tasks-BkYNmUcf.js.map → background-tasks-DhQ6upHK.js.map} +1 -1
  19. package/dist/{background-tasks-Civclnuq.cjs → background-tasks-Kcx2YtW0.cjs} +2 -2
  20. package/dist/{background-tasks-Civclnuq.cjs.map → background-tasks-Kcx2YtW0.cjs.map} +1 -1
  21. package/dist/{builder-registry-DHVK50Ba.js → builder-registry-6TFaV4oT.js} +2 -2
  22. package/dist/{builder-registry-DHVK50Ba.js.map → builder-registry-6TFaV4oT.js.map} +1 -1
  23. package/dist/{builder-registry-CamBJItc.cjs → builder-registry-CkPRx_vx.cjs} +2 -2
  24. package/dist/{builder-registry-CamBJItc.cjs.map → builder-registry-CkPRx_vx.cjs.map} +1 -1
  25. package/dist/{channels-EqvuQQbv.cjs → channels-Bfkp5vYI.cjs} +2 -2
  26. package/dist/{channels-EqvuQQbv.cjs.map → channels-Bfkp5vYI.cjs.map} +1 -1
  27. package/dist/{channels-LNR2QIkc.js → channels-hhQ3vD30.js} +2 -2
  28. package/dist/{channels-LNR2QIkc.js.map → channels-hhQ3vD30.js.map} +1 -1
  29. package/dist/{constants-ohUUT3Vg.js → constants-CXAvBYcz.js} +9 -2
  30. package/dist/constants-CXAvBYcz.js.map +1 -0
  31. package/dist/{constants-Co1XjPjd.cjs → constants-DMg8hUOR.cjs} +14 -1
  32. package/dist/constants-DMg8hUOR.cjs.map +1 -0
  33. package/dist/{conversations-fdXV9K0J.js → conversations-CVvZOu1K.js} +3 -3
  34. package/dist/{conversations-fdXV9K0J.js.map → conversations-CVvZOu1K.js.map} +1 -1
  35. package/dist/{conversations-ORTpTqBg.cjs → conversations-Ds6aiCMU.cjs} +3 -3
  36. package/dist/{conversations-ORTpTqBg.cjs.map → conversations-Ds6aiCMU.cjs.map} +1 -1
  37. package/dist/{dist-BEtxPxkM.cjs → dist-4RWkx1DC.cjs} +1 -1
  38. package/dist/dist-BOLBpPgs.js +1 -0
  39. package/dist/{dist-CR3PolEz.cjs → dist-CRO6e62N.cjs} +583 -3539
  40. package/dist/dist-CRO6e62N.cjs.map +1 -0
  41. package/dist/{dist-CmG4sN60.js → dist-DwXaR0sc.js} +585 -3541
  42. package/dist/dist-DwXaR0sc.js.map +1 -0
  43. package/dist/docs/SKILL.md +2 -1
  44. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  45. package/dist/docs/references/docs-studio-knowledge.md +81 -0
  46. package/dist/{editor-builder-DxGZ7IN5.js → editor-builder-BG38irXi.js} +2 -2
  47. package/dist/{editor-builder-DxGZ7IN5.js.map → editor-builder-BG38irXi.js.map} +1 -1
  48. package/dist/{editor-builder-6l27BFzD.cjs → editor-builder-CcSeAW18.cjs} +2 -2
  49. package/dist/{editor-builder-6l27BFzD.cjs.map → editor-builder-CcSeAW18.cjs.map} +1 -1
  50. package/dist/{helpers-CE1fJdLM.cjs → helpers-BKtUXhz2.cjs} +26 -3
  51. package/dist/helpers-BKtUXhz2.cjs.map +1 -0
  52. package/dist/{helpers-CMCXsowL.js → helpers-DNq3LtLq.js} +26 -3
  53. package/dist/helpers-DNq3LtLq.js.map +1 -0
  54. package/dist/knowledge-DykIi0wH.js +431 -0
  55. package/dist/knowledge-DykIi0wH.js.map +1 -0
  56. package/dist/knowledge-qu0om3W7.cjs +474 -0
  57. package/dist/knowledge-qu0om3W7.cjs.map +1 -0
  58. package/dist/{logs-BbaBP2LD.js → logs-B57_NKDn.js} +2 -2
  59. package/dist/{logs-BbaBP2LD.js.map → logs-B57_NKDn.js.map} +1 -1
  60. package/dist/{logs-DI-h9uHR.cjs → logs-BJN3M88A.cjs} +2 -2
  61. package/dist/{logs-DI-h9uHR.cjs.map → logs-BJN3M88A.cjs.map} +1 -1
  62. package/dist/{mcp-CMw0sq0y.cjs → mcp-B9BILfJP.cjs} +2 -2
  63. package/dist/{mcp-CMw0sq0y.cjs.map → mcp-B9BILfJP.cjs.map} +1 -1
  64. package/dist/{mcp-DN9mT9q4.js → mcp-BkmWZD6M.js} +2 -2
  65. package/dist/{mcp-DN9mT9q4.js.map → mcp-BkmWZD6M.js.map} +1 -1
  66. package/dist/{memory-Buhi6kZ-.cjs → memory-Dqod_AK9.cjs} +2 -2
  67. package/dist/{memory-Buhi6kZ-.cjs.map → memory-Dqod_AK9.cjs.map} +1 -1
  68. package/dist/{memory-BTR95ujT.js → memory-ipOCmg0C.js} +2 -2
  69. package/dist/{memory-BTR95ujT.js.map → memory-ipOCmg0C.js.map} +1 -1
  70. package/dist/{observability-pX3wmG8T.js → observability-CbJDt-WY.js} +2 -2
  71. package/dist/{observability-pX3wmG8T.js.map → observability-CbJDt-WY.js.map} +1 -1
  72. package/dist/{observability-new-endpoints-BrB2CKix.cjs → observability-new-endpoints-7KCQHib3.cjs} +2 -2
  73. package/dist/{observability-new-endpoints-BrB2CKix.cjs.map → observability-new-endpoints-7KCQHib3.cjs.map} +1 -1
  74. package/dist/{observability-new-endpoints-CQNVjYYq.js → observability-new-endpoints-DrDPcAjm.js} +2 -2
  75. package/dist/{observability-new-endpoints-CQNVjYYq.js.map → observability-new-endpoints-DrDPcAjm.js.map} +1 -1
  76. package/dist/{observability-DRbDeN1X.cjs → observability-wSQo-vXB.cjs} +2 -2
  77. package/dist/{observability-DRbDeN1X.cjs.map → observability-wSQo-vXB.cjs.map} +1 -1
  78. package/dist/{plans-D9BGMVkL.js → plans-BRf1-Sch.js} +3 -3
  79. package/dist/{plans-D9BGMVkL.js.map → plans-BRf1-Sch.js.map} +1 -1
  80. package/dist/{plans-BHQFsFRU.cjs → plans-Cq23qQ48.cjs} +3 -3
  81. package/dist/{plans-BHQFsFRU.cjs.map → plans-Cq23qQ48.cjs.map} +1 -1
  82. package/dist/{probe-image-size-BjNoJxWf.js → probe-image-size-BGSAADKy.js} +2 -2
  83. package/dist/{probe-image-size-BjNoJxWf.js.map → probe-image-size-BGSAADKy.js.map} +1 -1
  84. package/dist/{probe-image-size-jS0ECSlc.cjs → probe-image-size-CsYWL1Gs.cjs} +2 -2
  85. package/dist/{probe-image-size-jS0ECSlc.cjs.map → probe-image-size-CsYWL1Gs.cjs.map} +1 -1
  86. package/dist/{responses-Cb-9JV9A.js → responses-CGy87E_N.js} +3 -3
  87. package/dist/{responses-Cb-9JV9A.js.map → responses-CGy87E_N.js.map} +1 -1
  88. package/dist/{responses-4_RCBNJB.cjs → responses-CPTdr5VE.cjs} +3 -3
  89. package/dist/{responses-4_RCBNJB.cjs.map → responses-CPTdr5VE.cjs.map} +1 -1
  90. package/dist/{routes-BqWcvAcz.cjs → routes-BCpGBudO.cjs} +79 -22
  91. package/dist/routes-BCpGBudO.cjs.map +1 -0
  92. package/dist/{routes-4X2kSYEG.js → routes-DZgJrVh5.js} +62 -23
  93. package/dist/routes-DZgJrVh5.js.map +1 -0
  94. package/dist/{schedules-CQPodXrR.js → schedules-CGViSLZC.js} +2 -2
  95. package/dist/{schedules-CQPodXrR.js.map → schedules-CGViSLZC.js.map} +1 -1
  96. package/dist/{schedules-CL4IU7kS.cjs → schedules-D8ShgpY3.cjs} +2 -2
  97. package/dist/{schedules-CL4IU7kS.cjs.map → schedules-D8ShgpY3.cjs.map} +1 -1
  98. package/dist/{scores-DnEcBe2i.cjs → scores-BZ0Iz_0O.cjs} +2 -2
  99. package/dist/{scores-DnEcBe2i.cjs.map → scores-BZ0Iz_0O.cjs.map} +1 -1
  100. package/dist/{scores-DqImg-o-.js → scores-DqSDYRs0.js} +2 -2
  101. package/dist/{scores-DqImg-o-.js.map → scores-DqSDYRs0.js.map} +1 -1
  102. package/dist/server/auth/helpers.d.ts.map +1 -1
  103. package/dist/server/auth/index.cjs +2 -2
  104. package/dist/server/auth/index.js +2 -2
  105. package/dist/server/constants.d.ts +7 -1
  106. package/dist/server/constants.d.ts.map +1 -1
  107. package/dist/server/fga-permissions.d.ts.map +1 -1
  108. package/dist/server/handlers/a2a.cjs +1 -1
  109. package/dist/server/handlers/a2a.js +1 -1
  110. package/dist/server/handlers/agent-builder.cjs +1 -1
  111. package/dist/server/handlers/agent-builder.js +1 -1
  112. package/dist/server/handlers/agent-controller.cjs +2 -2
  113. package/dist/server/handlers/agent-controller.js +2 -2
  114. package/dist/server/handlers/agent-versions.cjs +1 -1
  115. package/dist/server/handlers/agent-versions.js +1 -1
  116. package/dist/server/handlers/agents.cjs +1 -1
  117. package/dist/server/handlers/agents.js +1 -1
  118. package/dist/server/handlers/auth.cjs +2 -2
  119. package/dist/server/handlers/auth.js +2 -2
  120. package/dist/server/handlers/authorship.cjs +1 -1
  121. package/dist/server/handlers/authorship.js +1 -1
  122. package/dist/server/handlers/background-tasks.cjs +1 -1
  123. package/dist/server/handlers/background-tasks.js +1 -1
  124. package/dist/server/handlers/builder-registry.cjs +1 -1
  125. package/dist/server/handlers/builder-registry.js +1 -1
  126. package/dist/server/handlers/channels.cjs +1 -1
  127. package/dist/server/handlers/channels.js +1 -1
  128. package/dist/server/handlers/conversations.cjs +1 -1
  129. package/dist/server/handlers/conversations.js +1 -1
  130. package/dist/server/handlers/datasets.cjs +1 -1
  131. package/dist/server/handlers/datasets.js +1 -1
  132. package/dist/server/handlers/editor-builder.cjs +1 -1
  133. package/dist/server/handlers/editor-builder.js +1 -1
  134. package/dist/server/handlers/favorites-enrichment.cjs +1 -1
  135. package/dist/server/handlers/favorites-enrichment.js +1 -1
  136. package/dist/server/handlers/knowledge.cjs +10 -0
  137. package/dist/server/handlers/knowledge.d.ts +237 -0
  138. package/dist/server/handlers/knowledge.d.ts.map +1 -0
  139. package/dist/server/handlers/knowledge.js +1 -0
  140. package/dist/server/handlers/logs.cjs +1 -1
  141. package/dist/server/handlers/logs.js +1 -1
  142. package/dist/server/handlers/mcp-client-versions.cjs +1 -1
  143. package/dist/server/handlers/mcp-client-versions.js +1 -1
  144. package/dist/server/handlers/mcp.cjs +1 -1
  145. package/dist/server/handlers/mcp.js +1 -1
  146. package/dist/server/handlers/memory.cjs +1 -1
  147. package/dist/server/handlers/memory.js +1 -1
  148. package/dist/server/handlers/observability-new-endpoints.cjs +1 -1
  149. package/dist/server/handlers/observability-new-endpoints.js +1 -1
  150. package/dist/server/handlers/observability.cjs +2 -2
  151. package/dist/server/handlers/observability.js +2 -2
  152. package/dist/server/handlers/plans.cjs +1 -1
  153. package/dist/server/handlers/plans.js +1 -1
  154. package/dist/server/handlers/prompt-block-versions.cjs +1 -1
  155. package/dist/server/handlers/prompt-block-versions.js +1 -1
  156. package/dist/server/handlers/responses.cjs +1 -1
  157. package/dist/server/handlers/responses.js +1 -1
  158. package/dist/server/handlers/responses.storage.cjs +1 -1
  159. package/dist/server/handlers/responses.storage.js +1 -1
  160. package/dist/server/handlers/schedules.cjs +1 -1
  161. package/dist/server/handlers/schedules.js +1 -1
  162. package/dist/server/handlers/scorer-versions.cjs +1 -1
  163. package/dist/server/handlers/scorer-versions.js +1 -1
  164. package/dist/server/handlers/scores.cjs +1 -1
  165. package/dist/server/handlers/scores.js +1 -1
  166. package/dist/server/handlers/stored-agent-favorites.cjs +2 -2
  167. package/dist/server/handlers/stored-agent-favorites.js +2 -2
  168. package/dist/server/handlers/stored-agents.cjs +2 -2
  169. package/dist/server/handlers/stored-agents.js +2 -2
  170. package/dist/server/handlers/stored-mcp-clients.cjs +1 -1
  171. package/dist/server/handlers/stored-mcp-clients.js +1 -1
  172. package/dist/server/handlers/stored-prompt-blocks.cjs +1 -1
  173. package/dist/server/handlers/stored-prompt-blocks.js +1 -1
  174. package/dist/server/handlers/stored-scorers.cjs +1 -1
  175. package/dist/server/handlers/stored-scorers.js +1 -1
  176. package/dist/server/handlers/stored-skill-favorites.cjs +2 -2
  177. package/dist/server/handlers/stored-skill-favorites.js +2 -2
  178. package/dist/server/handlers/stored-skills.cjs +2 -2
  179. package/dist/server/handlers/stored-skills.js +2 -2
  180. package/dist/server/handlers/stored-workspaces.cjs +1 -1
  181. package/dist/server/handlers/stored-workspaces.js +1 -1
  182. package/dist/server/handlers/system.cjs +1 -1
  183. package/dist/server/handlers/system.js +1 -1
  184. package/dist/server/handlers/tool-providers.cjs +1 -1
  185. package/dist/server/handlers/tool-providers.js +1 -1
  186. package/dist/server/handlers/tools.cjs +1 -1
  187. package/dist/server/handlers/tools.js +1 -1
  188. package/dist/server/handlers/utils.cjs +1 -1
  189. package/dist/server/handlers/utils.js +1 -1
  190. package/dist/server/handlers/validate-agent-instructions.cjs +1 -1
  191. package/dist/server/handlers/validate-agent-instructions.js +1 -1
  192. package/dist/server/handlers/workflow-builder.cjs +1 -1
  193. package/dist/server/handlers/workflow-builder.js +1 -1
  194. package/dist/server/handlers/workflows.cjs +1 -1
  195. package/dist/server/handlers/workflows.js +1 -1
  196. package/dist/server/handlers/workspace.d.ts +23 -23
  197. package/dist/server/handlers.cjs +13 -13
  198. package/dist/server/handlers.js +13 -13
  199. package/dist/server/schemas/knowledge.d.ts +58 -0
  200. package/dist/server/schemas/knowledge.d.ts.map +1 -0
  201. package/dist/server/server-adapter/index.cjs +21 -6
  202. package/dist/server/server-adapter/index.cjs.map +1 -1
  203. package/dist/server/server-adapter/index.d.ts +1 -1
  204. package/dist/server/server-adapter/index.d.ts.map +1 -1
  205. package/dist/server/server-adapter/index.js +18 -7
  206. package/dist/server/server-adapter/index.js.map +1 -1
  207. package/dist/server/server-adapter/routes/fga-manifest.d.ts.map +1 -1
  208. package/dist/server/server-adapter/routes/index.d.ts +29 -0
  209. package/dist/server/server-adapter/routes/index.d.ts.map +1 -1
  210. package/dist/server/server-adapter/routes/knowledge.d.ts +231 -0
  211. package/dist/server/server-adapter/routes/knowledge.d.ts.map +1 -0
  212. package/dist/{tools-BFpuzQsz.js → tools-CtELrYsA.js} +4 -4
  213. package/dist/{tools-BFpuzQsz.js.map → tools-CtELrYsA.js.map} +1 -1
  214. package/dist/{tools-Dy_j6URC.cjs → tools-DtRHH9Hr.cjs} +4 -4
  215. package/dist/{tools-Dy_j6URC.cjs.map → tools-DtRHH9Hr.cjs.map} +1 -1
  216. package/dist/{utils-BbYUI6Yn.cjs → utils-9PRHHTGC.cjs} +7 -3
  217. package/dist/utils-9PRHHTGC.cjs.map +1 -0
  218. package/dist/{utils-DHxjw4Tn.js → utils-B15w-1hm.js} +7 -3
  219. package/dist/utils-B15w-1hm.js.map +1 -0
  220. package/dist/{utils-BnH77wPf.cjs → utils-bQ6Jhog6.cjs} +2 -2
  221. package/dist/{utils-BnH77wPf.cjs.map → utils-bQ6Jhog6.cjs.map} +1 -1
  222. package/dist/{utils-YEuwVEc2.js → utils-qaBKOShQ.js} +2 -2
  223. package/dist/{utils-YEuwVEc2.js.map → utils-qaBKOShQ.js.map} +1 -1
  224. package/dist/{workflow-builder--W9PMW13.js → workflow-builder-6I2HiKcF.js} +2 -2
  225. package/dist/{workflow-builder--W9PMW13.js.map → workflow-builder-6I2HiKcF.js.map} +1 -1
  226. package/dist/{workflow-builder-CT7JOoW6.cjs → workflow-builder-CQzvZvwC.cjs} +2 -2
  227. package/dist/{workflow-builder-CT7JOoW6.cjs.map → workflow-builder-CQzvZvwC.cjs.map} +1 -1
  228. package/dist/{workflows-DPIRVRN9.js → workflows-ClfVyB1p.js} +3 -3
  229. package/dist/{workflows-DPIRVRN9.js.map → workflows-ClfVyB1p.js.map} +1 -1
  230. package/dist/{workflows-BAOfWBkr.cjs → workflows-DgSo-eBG.cjs} +3 -3
  231. package/dist/{workflows-BAOfWBkr.cjs.map → workflows-DgSo-eBG.cjs.map} +1 -1
  232. package/package.json +9 -9
  233. package/dist/constants-Co1XjPjd.cjs.map +0 -1
  234. package/dist/constants-ohUUT3Vg.js.map +0 -1
  235. package/dist/dist-BQ1uFC_1.js +0 -1
  236. package/dist/dist-CR3PolEz.cjs.map +0 -1
  237. package/dist/dist-CmG4sN60.js.map +0 -1
  238. package/dist/helpers-CE1fJdLM.cjs.map +0 -1
  239. package/dist/helpers-CMCXsowL.js.map +0 -1
  240. package/dist/routes-4X2kSYEG.js.map +0 -1
  241. package/dist/routes-BqWcvAcz.cjs.map +0 -1
  242. package/dist/utils-BbYUI6Yn.cjs.map +0 -1
  243. package/dist/utils-DHxjw4Tn.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"helpers-DNq3LtLq.js","names":[],"sources":["../src/server/auth/defaults.ts","../src/server/auth/path-pattern.ts","../src/server/auth/helpers.ts"],"sourcesContent":["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 pattern += '/' + tmp;\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 } from '@mastra/core/auth';\nimport type { IRBACProvider, EEUser } from '@mastra/core/auth/ee';\nimport type { Mastra } from '@mastra/core/mastra';\nimport { CompositeAuth } 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_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 { 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 { MASTRA_USER_KEY, MASTRA_USER_PERMISSIONS_KEY, MASTRA_USER_ROLES_KEY } from '../constants';\n\n/**\n * Check if a route is a registered custom route that requires authentication.\n * Returns true only if the route is explicitly registered with requiresAuth: true.\n * Returns false if the route is not in the config or has requiresAuth: false.\n */\nexport const isProtectedCustomRoute = (\n path: string,\n method: string,\n customRouteAuthConfig?: Map<string, boolean>,\n): boolean => {\n if (!customRouteAuthConfig) {\n return false;\n }\n\n // Check exact match first (fast path for static routes)\n const exactRouteKey = `${method}:${path}`;\n if (customRouteAuthConfig.has(exactRouteKey)) {\n return customRouteAuthConfig.get(exactRouteKey) === true;\n }\n\n // Check exact match for ALL method\n const allRouteKey = `ALL:${path}`;\n if (customRouteAuthConfig.has(allRouteKey)) {\n return customRouteAuthConfig.get(allRouteKey) === true;\n }\n\n // Check pattern matches for dynamic routes (e.g., '/users/:id')\n for (const [routeKey, requiresAuth] of customRouteAuthConfig.entries()) {\n const colonIndex = routeKey.indexOf(':');\n if (colonIndex === -1) {\n continue; // Skip malformed keys\n }\n\n const routeMethod = routeKey.substring(0, colonIndex);\n const routePattern = routeKey.substring(colonIndex + 1);\n\n // Check if method matches (exact match or ALL)\n if (routeMethod !== method && routeMethod !== 'ALL') {\n continue;\n }\n\n // Check if path matches the pattern\n if (pathMatchesPattern(path, routePattern)) {\n return requiresAuth === true;\n }\n }\n\n return false; // Not in config = not a protected custom route\n};\n\n/**\n * Find a matching custom API route for the given path and method.\n * Returns the matched route and any extracted path parameters.\n */\nexport const findMatchingCustomRoute = (\n path: string,\n method: string,\n apiRoutes?: ApiRoute[],\n): { route: ApiRoute; params: Record<string, string> } | undefined => {\n if (!apiRoutes) return undefined;\n\n for (const route of apiRoutes) {\n if (route.method !== method && route.method !== 'ALL') continue;\n\n const { keys, pattern: regex } = parse(route.path);\n const match = regex.exec(path);\n if (!match) continue;\n\n const params: Record<string, string> = {};\n if (keys && keys.length > 0) {\n for (let i = 0; i < keys.length; i++) {\n if (match[i + 1] !== undefined) {\n params[keys[i]!] = match[i + 1]!;\n }\n }\n }\n\n return { route, params };\n }\n\n return undefined;\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\nexport const isCustomRoutePublic = (\n path: string,\n method: string,\n customRouteAuthConfig?: Map<string, boolean>,\n): boolean => {\n if (!customRouteAuthConfig) {\n return false;\n }\n\n // Check exact match first (fast path for static routes)\n const exactRouteKey = `${method}:${path}`;\n if (customRouteAuthConfig.has(exactRouteKey)) {\n return !customRouteAuthConfig.get(exactRouteKey); // True when route opts out of auth\n }\n\n // Check exact match for ALL method\n const allRouteKey = `ALL:${path}`;\n if (customRouteAuthConfig.has(allRouteKey)) {\n return !customRouteAuthConfig.get(allRouteKey);\n }\n\n // Check pattern matches for dynamic routes (e.g., '/users/:id').\n // Any matching pattern that requires auth wins over overlapping public patterns.\n let matchedPublic = false;\n for (const [routeKey, requiresAuth] of customRouteAuthConfig.entries()) {\n const colonIndex = routeKey.indexOf(':');\n if (colonIndex === -1) {\n continue; // Skip malformed keys\n }\n\n const routeMethod = routeKey.substring(0, colonIndex);\n const routePattern = routeKey.substring(colonIndex + 1);\n\n // Check if method matches (exact match or ALL)\n if (routeMethod !== method && routeMethod !== 'ALL') {\n continue;\n }\n\n if (pathMatchesPattern(path, routePattern)) {\n if (requiresAuth) {\n return false;\n }\n matchedPublic = true;\n }\n }\n\n return matchedPublic;\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 = (base: unknown, ctx: AuthMiddlewareContext): 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 * 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 {\n path,\n method,\n getHeader,\n mastra,\n authConfig,\n customRouteAuthConfig,\n requestContext,\n rawRequest,\n token,\n requiresAuth,\n } = ctx;\n\n // ── Skip checks (evaluated once) ──\n\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 pass;\n }\n\n if (!isProtectedPath(path, method, authConfig, customRouteAuthConfig)) {\n return pass;\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 if (\n !requiresAuth &&\n (canAccessPublicly(path, method, authConfig) || isCustomRoutePublic(path, method, customRouteAuthConfig))\n ) {\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 // 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 }\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 if ('authorizeUser' in authConfig && typeof authConfig.authorizeUser === 'function') {\n try {\n const isAuthorized = await authConfig.authorizeUser(user, authRequest);\n\n if (!isAuthorized) {\n return { action: 'error', status: 403, body: { error: 'Access denied' }, headers: refreshHeaders };\n }\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 { action: 'error', status: 500, body: { error: 'Authorization error' }, headers: refreshHeaders };\n }\n } else if ('authorize' in authConfig && typeof authConfig.authorize === 'function') {\n try {\n const authorizeCtx = withAuthorizeVariables(ctx.buildAuthorizeContext(), ctx);\n const isAuthorized = await authConfig.authorize(path, method, user, authorizeCtx as any);\n\n if (!isAuthorized) {\n return { action: 'error', status: 403, body: { error: 'Access denied' }, headers: refreshHeaders };\n }\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 { action: 'error', status: 500, body: { error: 'Authorization error' }, headers: refreshHeaders };\n }\n } else if ('rules' in authConfig && authConfig.rules && authConfig.rules.length > 0) {\n const isAuthorized = await checkRules(authConfig.rules, path, method, user);\n\n if (!isAuthorized) {\n return { action: 'error', status: 403, body: { error: 'Access denied' }, headers: refreshHeaders };\n }\n } else {\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 const isAuthorized = await checkRules(defaultAuthConfig.rules, path, method, user);\n\n if (!isAuthorized) {\n return { action: 'error', status: 403, body: { error: 'Access denied' }, headers: refreshHeaders };\n }\n } else {\n return { action: 'error', status: 403, body: { error: 'Access denied' }, headers: refreshHeaders };\n }\n }\n }\n\n return refreshHeaders ? { action: 'next', headers: refreshHeaders } : pass;\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, check conditions\n const condition = rule.condition;\n if (typeof condition === 'function') {\n const allowed = await Promise.resolve()\n .then(() => condition(user))\n .catch(() => false);\n\n if (allowed) {\n return true;\n }\n } else if (rule.allow) {\n return true;\n }\n }\n\n // No matching rules, deny by default\n return false;\n};\n"],"mappings":";;;;AAGA,MAAa,oBAAsC;CACjD,WAAW,CAAC,QAAQ;CACpB,QAAQ,CAAC,QAAQ,aAAa;CAE9B,OAAO,CAEL;EACE,YAA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AAgB;GAAG,SAAS;EAAe;CAErG;CAGF,OAAO,iBAAiB;EAAE,QAAQ;EAAQ,SAAS;CAAe,IAAI;AACxE;AAGA,MAAa,aAAa,OACxB,OACA,MACA,QACA,SACqB;CAErB,KAAK,MAAM,KAAK,SAAS,CAAC,GAAG;EAC3B,MAAM,OAAO,QAAQ;EAErB,IAAI,CAAC,gBAAgB,MAAM,KAAK,IAAI,GAClC;EAIF,IAAI,KAAK,WAAW,CAAC,kBAAkB,KAAK,SAAS,MAAM,GACzD;EAIF,MAAM,YAAY,KAAK;EACvB,IAAI,OAAO,cAAc,YAKnB;OAAA,MAJkB,QAAQ,QAAQ,CAAC,CACpC,WAAW,UAAU,IAAI,CAAC,CAAC,CAC3B,YAAY,KAAK,GAGlB,OAAO;EAAA,OAEJ,IAAI,KAAK,OACd,OAAO;CAEX;CAGA,OAAO;AACT"}
@@ -0,0 +1,431 @@
1
+ import { t as HTTPException } from "./http-exception-CzaWkxMl.js";
2
+ import { n as createRoute } from "./route-builder-BxPrwNog.js";
3
+ import { a as MASTRA_KNOWLEDGE_PRINCIPALS_KEY } from "./constants-CXAvBYcz.js";
4
+ import { handleError } from "./server/handlers/error.js";
5
+ import { _ as MastraFGAPermissions, o as getHandlerFGAProvider } from "./utils-B15w-1hm.js";
6
+ import { z } from "zod/v4";
7
+ import * as coreKnowledge from "@mastra/core/knowledge";
8
+ // src/server/schemas/knowledge.ts
9
+ const knowledgePathParams = z.object({ knowledgeKey: z.string().describe("Application key the Knowledge instance is registered under") });
10
+ const knowledgePagePathParams = knowledgePathParams.extend({ pageId: z.string().min(1).max(512).describe("Knowledge page id") });
11
+ const pageId = z.string().min(1).max(512);
12
+ const limit = z.coerce.number().int().min(1).max(100).optional();
13
+ const knowledgeTreeQuerySchema = z.object({
14
+ parentId: pageId.optional().describe("Page whose children to list; omit for the root scopes"),
15
+ cursor: z.string().optional(),
16
+ limit
17
+ });
18
+ const knowledgePageQuerySchema = z.object({
19
+ noteCursor: z.string().optional(),
20
+ noteLimit: limit
21
+ });
22
+ const knowledgeGraphQuerySchema = z.object({
23
+ rootId: pageId.optional().describe("Page to walk from; omit to walk every root scope"),
24
+ maxPages: z.coerce.number().int().min(1).max(500).optional()
25
+ });
26
+ const scopeIds = z.union([z.string(), z.array(z.string())]).transform((value) => Array.isArray(value) ? value : [value]).pipe(z.array(pageId).max(20));
27
+ const knowledgeSearchQuerySchema = z.object({
28
+ q: z.string().min(1).max(200).describe("Text to match in page names, synopses, bodies and notes"),
29
+ scopeId: scopeIds.optional().describe("Only pages within these scopes"),
30
+ limit
31
+ });
32
+ const knowledgeActivityQuerySchema = z.object({
33
+ scopeId: pageId.optional(),
34
+ pageId: pageId.optional(),
35
+ cursor: z.string().optional(),
36
+ limit
37
+ });
38
+ const payload = z.record(z.string(), z.unknown());
39
+ const listKnowledgeResponseSchema = z.object({ instances: z.array(z.object({
40
+ key: z.string(),
41
+ id: z.string()
42
+ })) });
43
+ const knowledgeTreeResponseSchema = payload;
44
+ const knowledgePageResponseSchema = payload;
45
+ const knowledgeGraphResponseSchema = payload;
46
+ const knowledgeSearchResponseSchema = z.object({ results: z.array(payload) });
47
+ const knowledgeActivityResponseSchema = payload;
48
+ const knowledgeEventsResponseSchema = z.object({
49
+ kind: z.enum([
50
+ "scope",
51
+ "page",
52
+ "note",
53
+ "pin"
54
+ ]),
55
+ op: z.string(),
56
+ pageId: z.string().optional(),
57
+ scopeId: z.string().optional(),
58
+ at: z.string()
59
+ });
60
+ // src/server/handlers/knowledge.ts
61
+ /**
62
+ * Read-only browsing of Knowledge instances registered on Mastra, for Studio. Nothing here writes.
63
+ *
64
+ * What a caller reads depends on whether the app has auth configured (`server.auth` or `studio.auth`):
65
+ * - No auth: probably a local or test project, so the routes read as the instance owner (`'all'`).
66
+ * - Auth: reads are narrowed to what the signed-in caller can read. The app maps the user to Knowledge
67
+ * principals by setting MASTRA_KNOWLEDGE_PRINCIPALS_KEY in `auth.authorize` (a `string[]`, or `'all'`
68
+ * for an admin); the instance turns them into a read scope with `readScopeFor`. A caller with no
69
+ * mapping is refused with 403.
70
+ *
71
+ * On top of that the path derives `knowledge:read` (`GET /knowledge/...`), and with FGA configured each
72
+ * instance is filtered and gated by `knowledge:read` on that instance. The routes are opt-in
73
+ * (KNOWLEDGE_ROUTES); hosts with their own scoping (Factory) do not mount them.
74
+ */
75
+ function hasAuth(mastra) {
76
+ return Boolean(mastra.getServer?.()?.auth || mastra.getStudio?.()?.auth);
77
+ }
78
+ async function callerReadScope(mastra, requestContext, instance) {
79
+ if (!hasAuth(mastra)) return "all";
80
+ const principals = requestContext?.get(MASTRA_KNOWLEDGE_PRINCIPALS_KEY);
81
+ if (principals === void 0 || principals === null) throw new HTTPException(403, { message: `Knowledge access is not mapped for this caller. Set request context key "${MASTRA_KNOWLEDGE_PRINCIPALS_KEY}" in auth.authorize.` });
82
+ if (principals === "all") return "all";
83
+ if (!Array.isArray(principals) || principals.some((principal) => typeof principal !== "string")) throw new HTTPException(500, { message: `Request context key "${MASTRA_KNOWLEDGE_PRINCIPALS_KEY}" must be a string array or 'all'.` });
84
+ try {
85
+ return await instance.readScopeFor(principals);
86
+ } catch (error) {
87
+ if (error instanceof Error && error.name === "KnowledgeDeclarationError") throw new HTTPException(500, {
88
+ message: error.message,
89
+ cause: error
90
+ });
91
+ throw error;
92
+ }
93
+ }
94
+ async function accessibleInstances(mastra, requestContext, entries) {
95
+ const fgaProvider = getHandlerFGAProvider(mastra, requestContext);
96
+ const user = requestContext?.get("user");
97
+ if (!fgaProvider || !user || typeof user !== "object" || entries.length === 0) return new Set(entries.map((entry) => entry.key));
98
+ const accessible = await fgaProvider.filterAccessible(user, entries.map((entry) => ({
99
+ ...entry,
100
+ id: entry.key
101
+ })), "knowledge", MastraFGAPermissions.KNOWLEDGE_READ);
102
+ return new Set(accessible.map((entry) => entry.key));
103
+ }
104
+ const pageReaders = coreKnowledge;
105
+ function requirePageReaders() {
106
+ const { listKnowledgeTreeChildren, readKnowledgePage, readKnowledgePageActivity, readKnowledgePageGraph, searchKnowledgeExplorerPages } = pageReaders;
107
+ if (!listKnowledgeTreeChildren || !readKnowledgePage || !readKnowledgePageActivity || !readKnowledgePageGraph || !searchKnowledgeExplorerPages) throw new HTTPException(501, { message: "Knowledge browsing needs @mastra/core 1.81.0 or later." });
108
+ return {
109
+ listKnowledgeTreeChildren,
110
+ readKnowledgePage,
111
+ readKnowledgePageActivity,
112
+ readKnowledgePageGraph,
113
+ searchKnowledgeExplorerPages
114
+ };
115
+ }
116
+ /**
117
+ * The declared grants between the graph's scopes, each with its principal's display label. Grants are
118
+ * newer than the page readers, so a core without them sends none and the graph still loads.
119
+ */
120
+ async function graphGrants(instance, store, pages, read) {
121
+ const readGrants = coreKnowledge.readKnowledgeScopeGrants;
122
+ const scopeGrants = instance.scopeGrants?.bind(instance);
123
+ if (!readGrants || !scopeGrants) return void 0;
124
+ return (await readGrants(store, {
125
+ pages,
126
+ read,
127
+ grantsFor: scopeGrants
128
+ })).map((grant) => {
129
+ const principalLabel = instance.scopeLabel?.(grant.principal);
130
+ return principalLabel ? {
131
+ ...grant,
132
+ principalLabel
133
+ } : grant;
134
+ });
135
+ }
136
+ async function resolveStore(mastra, requestContext, knowledgeKey) {
137
+ const instances = mastra.listKnowledge();
138
+ const instance = knowledgeKey && Object.hasOwn(instances, knowledgeKey) ? instances[knowledgeKey] : void 0;
139
+ if (!knowledgeKey || !instance) throw new HTTPException(404, { message: `Knowledge ${knowledgeKey ?? ""} not found` });
140
+ const fgaProvider = getHandlerFGAProvider(mastra, requestContext);
141
+ const user = requestContext?.get("user");
142
+ if (fgaProvider && user && typeof user === "object") {
143
+ if (!await fgaProvider.check(user, {
144
+ resource: {
145
+ type: "knowledge",
146
+ id: knowledgeKey
147
+ },
148
+ permission: MastraFGAPermissions.KNOWLEDGE_READ
149
+ })) throw new HTTPException(404, { message: `Knowledge ${knowledgeKey} not found` });
150
+ }
151
+ const readers = requirePageReaders();
152
+ const read = await callerReadScope(mastra, requestContext, instance);
153
+ return {
154
+ instance,
155
+ store: await instance.getStorage(),
156
+ read,
157
+ readers
158
+ };
159
+ }
160
+ /**
161
+ * Adds each scope page's declared `displayLabel` with its address's `$params` filled in (`'$orgId policy'`
162
+ * → `'acme policy'`), so the explorer can caption scopes. Scope declarations live in config, not
163
+ * storage, so the readers can't supply it. Older cores without `scopeLabel` send no label.
164
+ */
165
+ function withDisplayLabel(instance, page) {
166
+ if (!page.isScope || !page.address) return page;
167
+ const displayLabel = instance.scopeLabel?.(page.address);
168
+ return displayLabel ? {
169
+ ...page,
170
+ displayLabel
171
+ } : page;
172
+ }
173
+ const LIST_KNOWLEDGE_ROUTE = createRoute({
174
+ method: "GET",
175
+ path: "/knowledge",
176
+ responseType: "json",
177
+ responseSchema: listKnowledgeResponseSchema,
178
+ summary: "List Knowledge instances",
179
+ description: "Returns the Knowledge instances registered on this Mastra instance, by application key. Without app auth the other Knowledge routes read the whole instance; with auth they read only what the caller's Knowledge principals (MASTRA_KNOWLEDGE_PRINCIPALS_KEY, set in auth.authorize) can read, and refuse an unmapped caller with 403.",
180
+ tags: ["Knowledge"],
181
+ requiresAuth: true,
182
+ handler: async ({ mastra, requestContext }) => {
183
+ try {
184
+ const all = Object.entries(mastra.listKnowledge()).map(([key, instance]) => ({
185
+ key,
186
+ id: instance.id
187
+ }));
188
+ const allowed = await accessibleInstances(mastra, requestContext, all);
189
+ return { instances: all.filter((entry) => allowed.has(entry.key)) };
190
+ } catch (error) {
191
+ return handleError(error, "Error listing Knowledge instances");
192
+ }
193
+ }
194
+ });
195
+ const GET_KNOWLEDGE_TREE_ROUTE = createRoute({
196
+ method: "GET",
197
+ path: "/knowledge/:knowledgeKey/tree",
198
+ responseType: "json",
199
+ pathParamSchema: knowledgePathParams,
200
+ queryParamSchema: knowledgeTreeQuerySchema,
201
+ responseSchema: knowledgeTreeResponseSchema,
202
+ summary: "List one level of the Knowledge page tree",
203
+ description: "Without parentId, returns the root scopes. With parentId, returns its child scopes (first page only) then its child pages in order, paged with cursor.",
204
+ tags: ["Knowledge"],
205
+ requiresAuth: true,
206
+ handler: async ({ mastra, requestContext, knowledgeKey, parentId, cursor, limit }) => {
207
+ try {
208
+ const { instance, store, read, readers } = await resolveStore(mastra, requestContext, knowledgeKey);
209
+ const level = await readers.listKnowledgeTreeChildren(store, {
210
+ parentId: parentId ?? null,
211
+ read,
212
+ cursor: cursor || void 0,
213
+ limit
214
+ });
215
+ return {
216
+ ...level,
217
+ pages: level.pages.map((page) => withDisplayLabel(instance, page))
218
+ };
219
+ } catch (error) {
220
+ return handleError(error, "Error reading Knowledge tree");
221
+ }
222
+ }
223
+ });
224
+ const GET_KNOWLEDGE_PAGE_ROUTE = createRoute({
225
+ method: "GET",
226
+ path: "/knowledge/:knowledgeKey/pages/:pageId",
227
+ responseType: "json",
228
+ pathParamSchema: knowledgePagePathParams,
229
+ queryParamSchema: knowledgePageQuerySchema,
230
+ responseSchema: knowledgePageResponseSchema,
231
+ summary: "Get a Knowledge page",
232
+ description: "Returns one page with its ancestors, a page of its notes, its pin, the pages its notes reference and notes elsewhere that mention it; 404 when it does not exist",
233
+ tags: ["Knowledge"],
234
+ requiresAuth: true,
235
+ handler: async ({ mastra, requestContext, knowledgeKey, pageId, noteCursor, noteLimit }) => {
236
+ try {
237
+ const { instance, store, read, readers } = await resolveStore(mastra, requestContext, knowledgeKey);
238
+ const view = await readers.readKnowledgePage(store, {
239
+ pageId,
240
+ read,
241
+ noteCursor,
242
+ noteLimit
243
+ });
244
+ if (!view) throw new HTTPException(404, { message: "Knowledge page not found" });
245
+ const label = (page) => withDisplayLabel(instance, page);
246
+ return {
247
+ ...view,
248
+ page: label(view.page),
249
+ ancestors: view.ancestors.map(label),
250
+ related: view.related.map(label)
251
+ };
252
+ } catch (error) {
253
+ return handleError(error, "Error reading Knowledge page");
254
+ }
255
+ }
256
+ });
257
+ const GET_KNOWLEDGE_GRAPH_ROUTE = createRoute({
258
+ method: "GET",
259
+ path: "/knowledge/:knowledgeKey/graph",
260
+ responseType: "json",
261
+ pathParamSchema: knowledgePathParams,
262
+ queryParamSchema: knowledgeGraphQuerySchema,
263
+ responseSchema: knowledgeGraphResponseSchema,
264
+ summary: "Get a bounded Knowledge page graph",
265
+ description: "Returns pages under rootId (or every root scope) breadth-first with parent and mention edges, bounded; truncated is true when a limit stopped it. grants lists the declared access grants onto the scopes shown, from principal scopes the caller can read. 404 when rootId does not exist.",
266
+ tags: ["Knowledge"],
267
+ requiresAuth: true,
268
+ handler: async ({ mastra, requestContext, knowledgeKey, rootId, maxPages }) => {
269
+ try {
270
+ const { instance, store, read, readers } = await resolveStore(mastra, requestContext, knowledgeKey);
271
+ const graph = await readers.readKnowledgePageGraph(store, {
272
+ read,
273
+ rootId: rootId ?? null,
274
+ ...maxPages ? { limits: { maxPages } } : {}
275
+ });
276
+ if (!graph) throw new HTTPException(404, { message: "Knowledge page not found" });
277
+ const grants = await graphGrants(instance, store, graph.pages, read);
278
+ return {
279
+ ...graph,
280
+ pages: graph.pages.map((page) => withDisplayLabel(instance, page)),
281
+ ...grants ? { grants } : {}
282
+ };
283
+ } catch (error) {
284
+ return handleError(error, "Error reading Knowledge graph");
285
+ }
286
+ }
287
+ });
288
+ const SEARCH_KNOWLEDGE_ROUTE = createRoute({
289
+ method: "GET",
290
+ path: "/knowledge/:knowledgeKey/search",
291
+ responseType: "json",
292
+ pathParamSchema: knowledgePathParams,
293
+ queryParamSchema: knowledgeSearchQuerySchema,
294
+ responseSchema: knowledgeSearchResponseSchema,
295
+ summary: "Search Knowledge pages and notes",
296
+ description: "Returns pages whose name, synopsis or body, and notes whose text, match the query",
297
+ tags: ["Knowledge"],
298
+ requiresAuth: true,
299
+ handler: async ({ mastra, requestContext, knowledgeKey, q, scopeId, limit }) => {
300
+ try {
301
+ const { instance, store, read, readers } = await resolveStore(mastra, requestContext, knowledgeKey);
302
+ return { results: (await readers.searchKnowledgeExplorerPages(store, {
303
+ query: q,
304
+ read,
305
+ ...scopeId?.length ? { scopeIds: scopeId } : {},
306
+ limit
307
+ })).map((hit) => ({
308
+ ...hit,
309
+ page: withDisplayLabel(instance, hit.page)
310
+ })) };
311
+ } catch (error) {
312
+ return handleError(error, "Error searching Knowledge");
313
+ }
314
+ }
315
+ });
316
+ const GET_KNOWLEDGE_ACTIVITY_ROUTE = createRoute({
317
+ method: "GET",
318
+ path: "/knowledge/:knowledgeKey/activity",
319
+ responseType: "json",
320
+ pathParamSchema: knowledgePathParams,
321
+ queryParamSchema: knowledgeActivityQuerySchema,
322
+ responseSchema: knowledgeActivityResponseSchema,
323
+ summary: "List recent Knowledge activity",
324
+ description: "Returns a newest-first page of activity, optionally for one scope or one page",
325
+ tags: ["Knowledge"],
326
+ requiresAuth: true,
327
+ handler: async ({ mastra, requestContext, knowledgeKey, scopeId, pageId, cursor, limit }) => {
328
+ try {
329
+ const { store, read, readers } = await resolveStore(mastra, requestContext, knowledgeKey);
330
+ return { ...await readers.readKnowledgePageActivity(store, {
331
+ read,
332
+ scopeId,
333
+ pageId,
334
+ cursor,
335
+ limit
336
+ }) };
337
+ } catch (error) {
338
+ return handleError(error, "Error reading Knowledge activity");
339
+ }
340
+ }
341
+ });
342
+ const KEEPALIVE_MS = 25e3;
343
+ /**
344
+ * The read scope is resolved when the stream opens. Ending it after this long makes the client reconnect,
345
+ * which resolves the caller's read scope again, so a revoked grant stops receiving changes.
346
+ */
347
+ const STREAM_MAX_AGE_MS = 3e5;
348
+ /**
349
+ * What a viewer may learn about one change: the ids in it they can read, or nothing when they can read
350
+ * none. A page they can read now, or the scope it is (or was, before a move or merge) in, counts; a
351
+ * deleted page is matched by its scope.
352
+ */
353
+ async function visibleChange(store, read, event) {
354
+ const readable = async (id) => id !== void 0 && (read === "all" || await store.getPage({
355
+ id,
356
+ read
357
+ }) !== null);
358
+ const scopeId = "scopeId" in event ? event.scopeId : void 0;
359
+ const fromScopeId = "fromScopeId" in event ? event.fromScopeId : void 0;
360
+ const [page, scope, fromScope] = await Promise.all([
361
+ readable(event.pageId),
362
+ readable(scopeId),
363
+ readable(fromScopeId)
364
+ ]);
365
+ if (!page && !scope && !fromScope) return null;
366
+ return {
367
+ kind: event.kind,
368
+ op: event.op,
369
+ ...page ? { pageId: event.pageId } : {},
370
+ ...scope ? { scopeId } : {},
371
+ at: event.at.toISOString()
372
+ };
373
+ }
374
+ const STREAM_KNOWLEDGE_EVENTS_ROUTE = createRoute({
375
+ method: "GET",
376
+ path: "/knowledge/:knowledgeKey/events",
377
+ responseType: "stream",
378
+ streamFormat: "sse",
379
+ sseFlushOnConnect: true,
380
+ pathParamSchema: knowledgePathParams,
381
+ responseSchema: knowledgeEventsResponseSchema,
382
+ summary: "Stream Knowledge changes",
383
+ description: "Server-Sent Events, one per committed write the caller can read: { kind, op, pageId?, scopeId?, at }. Ids the caller cannot read are left out, and changes they cannot read at all are not sent. Re-read what changed with the other Knowledge routes.",
384
+ tags: ["Knowledge"],
385
+ requiresAuth: true,
386
+ handler: async ({ mastra, requestContext, knowledgeKey, abortSignal }) => {
387
+ try {
388
+ const { instance, store, read } = await resolveStore(mastra, requestContext, knowledgeKey);
389
+ if (typeof instance.onChange !== "function") throw new HTTPException(501, { message: "Knowledge change events need @mastra/core 1.81.0 or later." });
390
+ const logger = mastra.getLogger();
391
+ let stop = () => {};
392
+ return new ReadableStream({
393
+ start(controller) {
394
+ let open = true;
395
+ let queue = Promise.resolve();
396
+ const unsubscribe = instance.onChange((event) => {
397
+ queue = queue.then(async () => {
398
+ const change = await visibleChange(store, read, event).catch((error) => {
399
+ logger?.error("Error filtering a Knowledge change", { error });
400
+ return null;
401
+ });
402
+ if (open && change) controller.enqueue(change);
403
+ });
404
+ });
405
+ const keepalive = setInterval(() => open && controller.enqueue(": keepalive\n\n"), KEEPALIVE_MS);
406
+ const expire = setTimeout(() => stop(), STREAM_MAX_AGE_MS);
407
+ stop = () => {
408
+ if (!open) return;
409
+ open = false;
410
+ clearInterval(keepalive);
411
+ clearTimeout(expire);
412
+ unsubscribe();
413
+ try {
414
+ controller.close();
415
+ } catch {}
416
+ };
417
+ if (abortSignal?.aborted) stop();
418
+ else abortSignal?.addEventListener("abort", stop, { once: true });
419
+ },
420
+ cancel() {
421
+ stop();
422
+ }
423
+ });
424
+ } catch (error) {
425
+ return handleError(error, "Error streaming Knowledge changes");
426
+ }
427
+ }
428
+ });
429
+ export { LIST_KNOWLEDGE_ROUTE as a, GET_KNOWLEDGE_TREE_ROUTE as i, GET_KNOWLEDGE_GRAPH_ROUTE as n, SEARCH_KNOWLEDGE_ROUTE as o, GET_KNOWLEDGE_PAGE_ROUTE as r, STREAM_KNOWLEDGE_EVENTS_ROUTE as s, GET_KNOWLEDGE_ACTIVITY_ROUTE as t };
430
+
431
+ //# sourceMappingURL=knowledge-DykIi0wH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"knowledge-DykIi0wH.js","names":[],"sources":["../src/server/schemas/knowledge.ts","../src/server/handlers/knowledge.ts"],"sourcesContent":["import { z } from 'zod/v4';\n\nexport const knowledgePathParams = z.object({\n knowledgeKey: z.string().describe('Application key the Knowledge instance is registered under'),\n});\n\nexport const knowledgePagePathParams = knowledgePathParams.extend({\n pageId: z.string().min(1).max(512).describe('Knowledge page id'),\n});\n\nconst pageId = z.string().min(1).max(512);\nconst limit = z.coerce.number().int().min(1).max(100).optional();\n\nexport const knowledgeTreeQuerySchema = z.object({\n parentId: pageId.optional().describe('Page whose children to list; omit for the root scopes'),\n cursor: z.string().optional(),\n limit,\n});\n\nexport const knowledgePageQuerySchema = z.object({\n noteCursor: z.string().optional(),\n noteLimit: limit,\n});\n\nexport const knowledgeGraphQuerySchema = z.object({\n rootId: pageId.optional().describe('Page to walk from; omit to walk every root scope'),\n maxPages: z.coerce.number().int().min(1).max(500).optional(),\n});\n\n// A repeated param (`?scopeId=a&scopeId=b`) arrives as an array, a lone one as a string.\nconst scopeIds = z\n .union([z.string(), z.array(z.string())])\n .transform(value => (Array.isArray(value) ? value : [value]))\n .pipe(z.array(pageId).max(20));\n\nexport const knowledgeSearchQuerySchema = z.object({\n q: z.string().min(1).max(200).describe('Text to match in page names, synopses, bodies and notes'),\n scopeId: scopeIds.optional().describe('Only pages within these scopes'),\n limit,\n});\n\nexport const knowledgeActivityQuerySchema = z.object({\n scopeId: pageId.optional(),\n pageId: pageId.optional(),\n cursor: z.string().optional(),\n limit,\n});\n\n// Payloads come from the @mastra/core/knowledge page readers; the UI package owns their TypeScript shapes.\nconst payload = z.record(z.string(), z.unknown());\n\nexport const listKnowledgeResponseSchema = z.object({\n instances: z.array(z.object({ key: z.string(), id: z.string() })),\n});\nexport const knowledgeTreeResponseSchema = payload;\nexport const knowledgePageResponseSchema = payload;\nexport const knowledgeGraphResponseSchema = payload;\nexport const knowledgeSearchResponseSchema = z.object({ results: z.array(payload) });\nexport const knowledgeActivityResponseSchema = payload;\nexport const knowledgeEventsResponseSchema = z.object({\n kind: z.enum(['scope', 'page', 'note', 'pin']),\n op: z.string(),\n pageId: z.string().optional(),\n scopeId: z.string().optional(),\n at: z.string(),\n});\n","import * as coreKnowledge from '@mastra/core/knowledge';\nimport type { Knowledge, KnowledgeChangeEvent } from '@mastra/core/knowledge';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { KnowledgeReadScope, KnowledgeStorage } from '@mastra/core/storage';\nimport { MASTRA_KNOWLEDGE_PRINCIPALS_KEY } from '../constants';\nimport { MastraFGAPermissions } from '../fga-permissions';\nimport { HTTPException } from '../http-exception';\nimport {\n knowledgeActivityQuerySchema,\n knowledgeActivityResponseSchema,\n knowledgeEventsResponseSchema,\n knowledgeGraphQuerySchema,\n knowledgeGraphResponseSchema,\n knowledgePagePathParams,\n knowledgePageQuerySchema,\n knowledgePageResponseSchema,\n knowledgePathParams,\n knowledgeSearchQuerySchema,\n knowledgeSearchResponseSchema,\n knowledgeTreeQuerySchema,\n knowledgeTreeResponseSchema,\n listKnowledgeResponseSchema,\n} from '../schemas/knowledge';\nimport { createRoute } from '../server-adapter/routes/route-builder';\n\nimport { handleError } from './error';\nimport { getHandlerFGAProvider } from './utils';\n\n/**\n * Read-only browsing of Knowledge instances registered on Mastra, for Studio. Nothing here writes.\n *\n * What a caller reads depends on whether the app has auth configured (`server.auth` or `studio.auth`):\n * - No auth: probably a local or test project, so the routes read as the instance owner (`'all'`).\n * - Auth: reads are narrowed to what the signed-in caller can read. The app maps the user to Knowledge\n * principals by setting MASTRA_KNOWLEDGE_PRINCIPALS_KEY in `auth.authorize` (a `string[]`, or `'all'`\n * for an admin); the instance turns them into a read scope with `readScopeFor`. A caller with no\n * mapping is refused with 403.\n *\n * On top of that the path derives `knowledge:read` (`GET /knowledge/...`), and with FGA configured each\n * instance is filtered and gated by `knowledge:read` on that instance. The routes are opt-in\n * (KNOWLEDGE_ROUTES); hosts with their own scoping (Factory) do not mount them.\n */\n\nfunction hasAuth(mastra: Mastra): boolean {\n return Boolean(mastra.getServer?.()?.auth || (mastra as any).getStudio?.()?.auth);\n}\n\nasync function callerReadScope(\n mastra: Mastra,\n requestContext: RequestContext | undefined,\n instance: Knowledge,\n): Promise<KnowledgeReadScope> {\n if (!hasAuth(mastra)) return 'all';\n\n const principals = requestContext?.get(MASTRA_KNOWLEDGE_PRINCIPALS_KEY);\n if (principals === undefined || principals === null) {\n throw new HTTPException(403, {\n message: `Knowledge access is not mapped for this caller. Set request context key \"${MASTRA_KNOWLEDGE_PRINCIPALS_KEY}\" in auth.authorize.`,\n });\n }\n if (principals === 'all') return 'all';\n // The value comes from the app's own authorize code, so a bad one is a host misconfiguration, not a denial.\n if (!Array.isArray(principals) || principals.some(principal => typeof principal !== 'string')) {\n throw new HTTPException(500, {\n message: `Request context key \"${MASTRA_KNOWLEDGE_PRINCIPALS_KEY}\" must be a string array or 'all'.`,\n });\n }\n try {\n return await instance.readScopeFor(principals);\n } catch (error) {\n // A principal that matches no declared scope type: the app's mapping disagrees with its declarations.\n if (error instanceof Error && error.name === 'KnowledgeDeclarationError') {\n throw new HTTPException(500, { message: error.message, cause: error });\n }\n throw error;\n }\n}\n\nasync function accessibleInstances(\n mastra: Mastra,\n requestContext: RequestContext | undefined,\n entries: Array<{ id: string; key: string }>,\n): Promise<Set<string>> {\n const fgaProvider = getHandlerFGAProvider(mastra, requestContext);\n const user = requestContext?.get('user');\n if (!fgaProvider || !user || typeof user !== 'object' || entries.length === 0) {\n return new Set(entries.map(entry => entry.key));\n }\n // FGA names a Knowledge instance by its registered key, as the route metadata does (`:knowledgeKey`).\n const accessible: Array<{ id: string; key: string }> = await fgaProvider.filterAccessible(\n user,\n entries.map(entry => ({ ...entry, id: entry.key })),\n 'knowledge',\n MastraFGAPermissions.KNOWLEDGE_READ,\n );\n return new Set(accessible.map(entry => entry.key));\n}\n\ntype KnowledgePageReaders = Pick<\n typeof coreKnowledge,\n | 'listKnowledgeTreeChildren'\n | 'readKnowledgePage'\n | 'readKnowledgePageActivity'\n | 'readKnowledgePageGraph'\n | 'searchKnowledgeExplorerPages'\n>;\n\n// The page readers first ship in @mastra/core 1.81.0, above this package's peer floor. A named import\n// of an export an older core lacks fails at ESM link time and takes the whole server down, so they are\n// read off the namespace (as in schedules-workflows-shim.ts) and the routes answer 501 without them.\nconst pageReaders: Partial<KnowledgePageReaders> = coreKnowledge;\n\nfunction requirePageReaders(): KnowledgePageReaders {\n const {\n listKnowledgeTreeChildren,\n readKnowledgePage,\n readKnowledgePageActivity,\n readKnowledgePageGraph,\n searchKnowledgeExplorerPages,\n } = pageReaders;\n if (\n !listKnowledgeTreeChildren ||\n !readKnowledgePage ||\n !readKnowledgePageActivity ||\n !readKnowledgePageGraph ||\n !searchKnowledgeExplorerPages\n ) {\n throw new HTTPException(501, { message: 'Knowledge browsing needs @mastra/core 1.81.0 or later.' });\n }\n return {\n listKnowledgeTreeChildren,\n readKnowledgePage,\n readKnowledgePageActivity,\n readKnowledgePageGraph,\n searchKnowledgeExplorerPages,\n };\n}\n\n/**\n * The declared grants between the graph's scopes, each with its principal's display label. Grants are\n * newer than the page readers, so a core without them sends none and the graph still loads.\n */\nasync function graphGrants(\n instance: Knowledge,\n store: KnowledgeStorage,\n pages: readonly coreKnowledge.KnowledgePage[],\n read: KnowledgeReadScope,\n): Promise<Array<coreKnowledge.KnowledgeGraphScopeGrant & { principalLabel?: string }> | undefined> {\n const readGrants = (coreKnowledge as Partial<typeof coreKnowledge>).readKnowledgeScopeGrants;\n const scopeGrants = (instance as Partial<Knowledge>).scopeGrants?.bind(instance);\n if (!readGrants || !scopeGrants) return undefined;\n const grants = await readGrants(store, { pages, read, grantsFor: scopeGrants });\n return grants.map(grant => {\n const principalLabel = instance.scopeLabel?.(grant.principal);\n return principalLabel ? { ...grant, principalLabel } : grant;\n });\n}\n\nasync function resolveStore(\n mastra: Mastra,\n requestContext: RequestContext | undefined,\n knowledgeKey: string | undefined,\n): Promise<{ instance: Knowledge; store: KnowledgeStorage; read: KnowledgeReadScope; readers: KnowledgePageReaders }> {\n const instances = mastra.listKnowledge();\n // Own keys only: `constructor` or `__proto__` must not resolve to an Object.prototype member.\n const instance = knowledgeKey && Object.hasOwn(instances, knowledgeKey) ? instances[knowledgeKey] : undefined;\n if (!knowledgeKey || !instance)\n throw new HTTPException(404, { message: `Knowledge ${knowledgeKey ?? ''} not found` });\n\n // An instance the caller may not read looks the same as one that does not exist.\n const fgaProvider = getHandlerFGAProvider(mastra, requestContext);\n const user = requestContext?.get('user');\n if (fgaProvider && user && typeof user === 'object') {\n const allowed = await fgaProvider.check(user, {\n resource: { type: 'knowledge', id: knowledgeKey },\n permission: MastraFGAPermissions.KNOWLEDGE_READ,\n });\n if (!allowed) throw new HTTPException(404, { message: `Knowledge ${knowledgeKey} not found` });\n }\n const readers = requirePageReaders();\n const read = await callerReadScope(mastra, requestContext, instance);\n return { instance, store: await instance.getStorage(), read, readers };\n}\n\n/**\n * Adds each scope page's declared `displayLabel` with its address's `$params` filled in (`'$orgId policy'`\n * → `'acme policy'`), so the explorer can caption scopes. Scope declarations live in config, not\n * storage, so the readers can't supply it. Older cores without `scopeLabel` send no label.\n */\nfunction withDisplayLabel<T extends { isScope: boolean; address?: string }>(\n instance: Knowledge,\n page: T,\n): T & { displayLabel?: string } {\n if (!page.isScope || !page.address) return page;\n const displayLabel = instance.scopeLabel?.(page.address);\n return displayLabel ? { ...page, displayLabel } : page;\n}\n\nexport const LIST_KNOWLEDGE_ROUTE = createRoute({\n method: 'GET',\n path: '/knowledge',\n responseType: 'json',\n responseSchema: listKnowledgeResponseSchema,\n summary: 'List Knowledge instances',\n description:\n \"Returns the Knowledge instances registered on this Mastra instance, by application key. Without app auth the other Knowledge routes read the whole instance; with auth they read only what the caller's Knowledge principals (MASTRA_KNOWLEDGE_PRINCIPALS_KEY, set in auth.authorize) can read, and refuse an unmapped caller with 403.\",\n tags: ['Knowledge'],\n requiresAuth: true,\n handler: async ({ mastra, requestContext }) => {\n try {\n const all = Object.entries(mastra.listKnowledge()).map(([key, instance]) => ({ key, id: instance.id }));\n const allowed = await accessibleInstances(mastra, requestContext, all);\n return { instances: all.filter(entry => allowed.has(entry.key)) };\n } catch (error) {\n return handleError(error, 'Error listing Knowledge instances');\n }\n },\n});\n\nexport const GET_KNOWLEDGE_TREE_ROUTE = createRoute({\n method: 'GET',\n path: '/knowledge/:knowledgeKey/tree',\n responseType: 'json',\n pathParamSchema: knowledgePathParams,\n queryParamSchema: knowledgeTreeQuerySchema,\n responseSchema: knowledgeTreeResponseSchema,\n summary: 'List one level of the Knowledge page tree',\n description:\n 'Without parentId, returns the root scopes. With parentId, returns its child scopes (first page only) then its child pages in order, paged with cursor.',\n tags: ['Knowledge'],\n requiresAuth: true,\n handler: async ({ mastra, requestContext, knowledgeKey, parentId, cursor, limit }) => {\n try {\n const { instance, store, read, readers } = await resolveStore(mastra, requestContext, knowledgeKey);\n const level = await readers.listKnowledgeTreeChildren(store, {\n parentId: parentId ?? null,\n read,\n // An empty `?cursor=` means no cursor, so root scopes are still listed.\n cursor: cursor || undefined,\n limit,\n });\n return { ...level, pages: level.pages.map(page => withDisplayLabel(instance, page)) };\n } catch (error) {\n return handleError(error, 'Error reading Knowledge tree');\n }\n },\n});\n\nexport const GET_KNOWLEDGE_PAGE_ROUTE = createRoute({\n method: 'GET',\n path: '/knowledge/:knowledgeKey/pages/:pageId',\n responseType: 'json',\n pathParamSchema: knowledgePagePathParams,\n queryParamSchema: knowledgePageQuerySchema,\n responseSchema: knowledgePageResponseSchema,\n summary: 'Get a Knowledge page',\n description:\n 'Returns one page with its ancestors, a page of its notes, its pin, the pages its notes reference and notes elsewhere that mention it; 404 when it does not exist',\n tags: ['Knowledge'],\n requiresAuth: true,\n handler: async ({ mastra, requestContext, knowledgeKey, pageId, noteCursor, noteLimit }) => {\n try {\n const { instance, store, read, readers } = await resolveStore(mastra, requestContext, knowledgeKey);\n const view = await readers.readKnowledgePage(store, { pageId, read, noteCursor, noteLimit });\n if (!view) throw new HTTPException(404, { message: 'Knowledge page not found' });\n const label = <T extends { isScope: boolean; declaration?: string }>(page: T) => withDisplayLabel(instance, page);\n return {\n ...view,\n page: label(view.page),\n ancestors: view.ancestors.map(label),\n related: view.related.map(label),\n };\n } catch (error) {\n return handleError(error, 'Error reading Knowledge page');\n }\n },\n});\n\nexport const GET_KNOWLEDGE_GRAPH_ROUTE = createRoute({\n method: 'GET',\n path: '/knowledge/:knowledgeKey/graph',\n responseType: 'json',\n pathParamSchema: knowledgePathParams,\n queryParamSchema: knowledgeGraphQuerySchema,\n responseSchema: knowledgeGraphResponseSchema,\n summary: 'Get a bounded Knowledge page graph',\n description:\n 'Returns pages under rootId (or every root scope) breadth-first with parent and mention edges, bounded; truncated is true when a limit stopped it. grants lists the declared access grants onto the scopes shown, from principal scopes the caller can read. 404 when rootId does not exist.',\n tags: ['Knowledge'],\n requiresAuth: true,\n handler: async ({ mastra, requestContext, knowledgeKey, rootId, maxPages }) => {\n try {\n const { instance, store, read, readers } = await resolveStore(mastra, requestContext, knowledgeKey);\n const graph = await readers.readKnowledgePageGraph(store, {\n read,\n rootId: rootId ?? null,\n ...(maxPages ? { limits: { maxPages } } : {}),\n });\n if (!graph) throw new HTTPException(404, { message: 'Knowledge page not found' });\n const grants = await graphGrants(instance, store, graph.pages, read);\n return {\n ...graph,\n pages: graph.pages.map(page => withDisplayLabel(instance, page)),\n ...(grants ? { grants } : {}),\n };\n } catch (error) {\n return handleError(error, 'Error reading Knowledge graph');\n }\n },\n});\n\nexport const SEARCH_KNOWLEDGE_ROUTE = createRoute({\n method: 'GET',\n path: '/knowledge/:knowledgeKey/search',\n responseType: 'json',\n pathParamSchema: knowledgePathParams,\n queryParamSchema: knowledgeSearchQuerySchema,\n responseSchema: knowledgeSearchResponseSchema,\n summary: 'Search Knowledge pages and notes',\n description: 'Returns pages whose name, synopsis or body, and notes whose text, match the query',\n tags: ['Knowledge'],\n requiresAuth: true,\n handler: async ({ mastra, requestContext, knowledgeKey, q, scopeId, limit }) => {\n try {\n const { instance, store, read, readers } = await resolveStore(mastra, requestContext, knowledgeKey);\n const results = await readers.searchKnowledgeExplorerPages(store, {\n query: q,\n read,\n ...(scopeId?.length ? { scopeIds: scopeId } : {}),\n limit,\n });\n return { results: results.map(hit => ({ ...hit, page: withDisplayLabel(instance, hit.page) })) };\n } catch (error) {\n return handleError(error, 'Error searching Knowledge');\n }\n },\n});\n\nexport const GET_KNOWLEDGE_ACTIVITY_ROUTE = createRoute({\n method: 'GET',\n path: '/knowledge/:knowledgeKey/activity',\n responseType: 'json',\n pathParamSchema: knowledgePathParams,\n queryParamSchema: knowledgeActivityQuerySchema,\n responseSchema: knowledgeActivityResponseSchema,\n summary: 'List recent Knowledge activity',\n description: 'Returns a newest-first page of activity, optionally for one scope or one page',\n tags: ['Knowledge'],\n requiresAuth: true,\n handler: async ({ mastra, requestContext, knowledgeKey, scopeId, pageId, cursor, limit }) => {\n try {\n const { store, read, readers } = await resolveStore(mastra, requestContext, knowledgeKey);\n return { ...(await readers.readKnowledgePageActivity(store, { read, scopeId, pageId, cursor, limit })) };\n } catch (error) {\n return handleError(error, 'Error reading Knowledge activity');\n }\n },\n});\n\nconst KEEPALIVE_MS = 25_000;\n/**\n * The read scope is resolved when the stream opens. Ending it after this long makes the client reconnect,\n * which resolves the caller's read scope again, so a revoked grant stops receiving changes.\n */\nconst STREAM_MAX_AGE_MS = 5 * 60_000;\n\n/**\n * What a viewer may learn about one change: the ids in it they can read, or nothing when they can read\n * none. A page they can read now, or the scope it is (or was, before a move or merge) in, counts; a\n * deleted page is matched by its scope.\n */\nasync function visibleChange(store: KnowledgeStorage, read: KnowledgeReadScope, event: KnowledgeChangeEvent) {\n const readable = async (id: string | undefined) =>\n id !== undefined && (read === 'all' || (await store.getPage({ id, read })) !== null);\n const scopeId = 'scopeId' in event ? event.scopeId : undefined;\n const fromScopeId = 'fromScopeId' in event ? event.fromScopeId : undefined;\n const [page, scope, fromScope] = await Promise.all([\n readable(event.pageId),\n readable(scopeId),\n readable(fromScopeId),\n ]);\n if (!page && !scope && !fromScope) return null;\n return {\n kind: event.kind,\n op: event.op,\n ...(page ? { pageId: event.pageId } : {}),\n ...(scope ? { scopeId } : {}),\n at: event.at.toISOString(),\n };\n}\n\nexport const STREAM_KNOWLEDGE_EVENTS_ROUTE = createRoute({\n method: 'GET',\n path: '/knowledge/:knowledgeKey/events',\n responseType: 'stream',\n streamFormat: 'sse',\n sseFlushOnConnect: true,\n pathParamSchema: knowledgePathParams,\n responseSchema: knowledgeEventsResponseSchema,\n summary: 'Stream Knowledge changes',\n description:\n 'Server-Sent Events, one per committed write the caller can read: { kind, op, pageId?, scopeId?, at }. Ids the caller cannot read are left out, and changes they cannot read at all are not sent. Re-read what changed with the other Knowledge routes.',\n tags: ['Knowledge'],\n requiresAuth: true,\n handler: async ({ mastra, requestContext, knowledgeKey, abortSignal }) => {\n try {\n const { instance, store, read } = await resolveStore(mastra, requestContext, knowledgeKey);\n if (typeof instance.onChange !== 'function') {\n throw new HTTPException(501, { message: 'Knowledge change events need @mastra/core 1.81.0 or later.' });\n }\n const logger = mastra.getLogger();\n let stop = () => {};\n return new ReadableStream({\n start(controller) {\n let open = true;\n // Writes are filtered in order so a viewer never sees a later change before an earlier one.\n let queue = Promise.resolve();\n const unsubscribe = instance.onChange(event => {\n queue = queue.then(async () => {\n const change = await visibleChange(store, read, event).catch(error => {\n logger?.error('Error filtering a Knowledge change', { error });\n return null;\n });\n if (open && change) controller.enqueue(change);\n });\n });\n const keepalive = setInterval(() => open && controller.enqueue(': keepalive\\n\\n'), KEEPALIVE_MS);\n const expire = setTimeout(() => stop(), STREAM_MAX_AGE_MS);\n stop = () => {\n if (!open) return;\n open = false;\n clearInterval(keepalive);\n clearTimeout(expire);\n unsubscribe();\n try {\n controller.close();\n } catch {\n // Already closed\n }\n };\n if (abortSignal?.aborted) stop();\n else abortSignal?.addEventListener('abort', stop, { once: true });\n },\n cancel() {\n stop();\n },\n });\n } catch (error) {\n return handleError(error, 'Error streaming Knowledge changes');\n }\n },\n});\n"],"mappings":";;;;;;;;AAEA,MAAa,sBAAsB,EAAE,OAAO,EAC1C,cAAc,EAAE,OAAO,CAAC,CAAC,SAAS,4DAA4D,EAChG,CAAC;AAED,MAAa,0BAA0B,oBAAoB,OAAO,EAChE,QAAQ,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,SAAS,mBAAmB,EACjE,CAAC;AAED,MAAM,SAAS,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG;AACxC,MAAM,QAAQ,EAAE,OAAO,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,SAAS;AAE/D,MAAa,2BAA2B,EAAE,OAAO;CAC/C,UAAU,OAAO,SAAS,CAAC,CAAC,SAAS,uDAAuD;CAC5F,QAAQ,EAAE,OAAO,CAAC,CAAC,SAAS;CAC5B;AACF,CAAC;AAED,MAAa,2BAA2B,EAAE,OAAO;CAC/C,YAAY,EAAE,OAAO,CAAC,CAAC,SAAS;CAChC,WAAW;AAC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