@mastra/deployer 0.0.0-error-handler-fix-20251020202607 → 0.0.0-esbuild-bundle-worker-20260807182016

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 (319) hide show
  1. package/CHANGELOG.md +5691 -5
  2. package/LICENSE.md +15 -0
  3. package/dist/_types/@hono_node-server/dist/index.d.mts +101 -0
  4. package/dist/_types/@mastra_hono/dist/auth-middleware.d.ts +8 -0
  5. package/dist/_types/@mastra_hono/dist/browser-stream/index.d.ts +35 -0
  6. package/dist/_types/@mastra_hono/dist/index.d.ts +59 -0
  7. package/dist/analyze-7xxwhB5F.js +1405 -0
  8. package/dist/analyze-7xxwhB5F.js.map +1 -0
  9. package/dist/analyze-D100622N.cjs +1434 -0
  10. package/dist/analyze-D100622N.cjs.map +1 -0
  11. package/dist/arktype-aI7TBD0R-BWucI7hY.cjs +8 -0
  12. package/dist/arktype-aI7TBD0R-BWucI7hY.cjs.map +1 -0
  13. package/dist/arktype-aI7TBD0R-D06--n84.js +8 -0
  14. package/dist/arktype-aI7TBD0R-D06--n84.js.map +1 -0
  15. package/dist/build/analyze/analyzeEntry.d.ts +17 -11
  16. package/dist/build/analyze/analyzeEntry.d.ts.map +1 -1
  17. package/dist/build/analyze/bundleExternals.d.ts +8 -7
  18. package/dist/build/analyze/bundleExternals.d.ts.map +1 -1
  19. package/dist/build/analyze/constants.d.ts.map +1 -1
  20. package/dist/build/analyze.cjs +3 -12
  21. package/dist/build/analyze.d.ts +15 -7
  22. package/dist/build/analyze.d.ts.map +1 -1
  23. package/dist/build/analyze.js +2 -3
  24. package/dist/build/analyzeEntryProjectType.d.ts +12 -0
  25. package/dist/build/analyzeEntryProjectType.d.ts.map +1 -0
  26. package/dist/build/babel/check-config-export.d.ts +3 -2
  27. package/dist/build/babel/check-config-export.d.ts.map +1 -1
  28. package/dist/build/babel/detect-pino-transports.d.ts +13 -0
  29. package/dist/build/babel/detect-pino-transports.d.ts.map +1 -0
  30. package/dist/build/babel/remove-all-options-except.d.ts +3 -3
  31. package/dist/build/babel/remove-all-options-except.d.ts.map +1 -1
  32. package/dist/build/babel/remove-deployer.d.ts +6 -2
  33. package/dist/build/babel/remove-deployer.d.ts.map +1 -1
  34. package/dist/build/babel/remove-non-referenced-nodes.d.ts +2 -2
  35. package/dist/build/babel/remove-non-referenced-nodes.d.ts.map +1 -1
  36. package/dist/build/bundler.cjs +6 -16
  37. package/dist/build/bundler.d.ts +13 -3
  38. package/dist/build/bundler.d.ts.map +1 -1
  39. package/dist/build/bundler.js +2 -3
  40. package/dist/build/bundlerOptions.d.ts +1 -1
  41. package/dist/build/bundlerOptions.d.ts.map +1 -1
  42. package/dist/build/deployer.d.ts +1 -1
  43. package/dist/build/deployer.d.ts.map +1 -1
  44. package/dist/build/fs-routing/codegen.d.ts +42 -0
  45. package/dist/build/fs-routing/codegen.d.ts.map +1 -0
  46. package/dist/build/fs-routing/discover.d.ts +178 -0
  47. package/dist/build/fs-routing/discover.d.ts.map +1 -0
  48. package/dist/build/fs-routing/mirror.d.ts +16 -0
  49. package/dist/build/fs-routing/mirror.d.ts.map +1 -0
  50. package/dist/build/fs-routing/prepare.d.ts +67 -0
  51. package/dist/build/fs-routing/prepare.d.ts.map +1 -0
  52. package/dist/build/index.cjs +29 -52
  53. package/dist/build/index.d.ts +9 -1
  54. package/dist/build/index.d.ts.map +1 -1
  55. package/dist/build/index.js +7 -7
  56. package/dist/build/package-info.d.ts +14 -0
  57. package/dist/build/package-info.d.ts.map +1 -0
  58. package/dist/build/plugins/esm-shim.d.ts +14 -0
  59. package/dist/build/plugins/esm-shim.d.ts.map +1 -0
  60. package/dist/build/plugins/local-storage-detector.d.ts +50 -0
  61. package/dist/build/plugins/local-storage-detector.d.ts.map +1 -0
  62. package/dist/build/plugins/module-resolve-map.d.ts +3 -0
  63. package/dist/build/plugins/module-resolve-map.d.ts.map +1 -0
  64. package/dist/build/plugins/node-gyp-detector.d.ts +3 -0
  65. package/dist/build/plugins/node-gyp-detector.d.ts.map +1 -0
  66. package/dist/build/plugins/node-modules-extension-resolver.d.ts +7 -0
  67. package/dist/build/plugins/node-modules-extension-resolver.d.ts.map +1 -1
  68. package/dist/build/plugins/pino.d.ts.map +1 -1
  69. package/dist/build/plugins/protocol-external-resolver.d.ts +5 -0
  70. package/dist/build/plugins/protocol-external-resolver.d.ts.map +1 -0
  71. package/dist/build/plugins/remove-all-except.d.ts +10 -0
  72. package/dist/build/plugins/remove-all-except.d.ts.map +1 -0
  73. package/dist/build/plugins/remove-deployer.d.ts.map +1 -1
  74. package/dist/build/plugins/remove-unused-references.d.ts.map +1 -1
  75. package/dist/build/plugins/subpath-externals-resolver.d.ts +3 -0
  76. package/dist/build/plugins/subpath-externals-resolver.d.ts.map +1 -0
  77. package/dist/build/plugins/tsconfig-paths.d.ts +8 -0
  78. package/dist/build/plugins/tsconfig-paths.d.ts.map +1 -1
  79. package/dist/build/plugins/workspace-deps-watcher.d.ts +33 -0
  80. package/dist/build/plugins/workspace-deps-watcher.d.ts.map +1 -0
  81. package/dist/build/serverOptions.d.ts +1 -1
  82. package/dist/build/serverOptions.d.ts.map +1 -1
  83. package/dist/build/shared/extract-mastra-option.d.ts +5 -9
  84. package/dist/build/shared/extract-mastra-option.d.ts.map +1 -1
  85. package/dist/build/types.d.ts +35 -0
  86. package/dist/build/types.d.ts.map +1 -1
  87. package/dist/build/utils.d.ts +106 -2
  88. package/dist/build/utils.d.ts.map +1 -1
  89. package/dist/build/watcher.d.ts +5 -1
  90. package/dist/build/watcher.d.ts.map +1 -1
  91. package/dist/build-DEie1huB.js +1084 -0
  92. package/dist/build-DEie1huB.js.map +1 -0
  93. package/dist/build-YV8-9zZy.cjs +1158 -0
  94. package/dist/build-YV8-9zZy.cjs.map +1 -0
  95. package/dist/bundler/entries.d.ts +12 -0
  96. package/dist/bundler/entries.d.ts.map +1 -0
  97. package/dist/bundler/index.cjs +7 -12
  98. package/dist/bundler/index.d.ts +85 -12
  99. package/dist/bundler/index.d.ts.map +1 -1
  100. package/dist/bundler/index.js +2 -3
  101. package/dist/bundler/workspaceDependencies.d.ts +3 -5
  102. package/dist/bundler/workspaceDependencies.d.ts.map +1 -1
  103. package/dist/bundler-CD-PSWRS.cjs +591 -0
  104. package/dist/bundler-CD-PSWRS.cjs.map +1 -0
  105. package/dist/bundler-NdSt2FYG.js +558 -0
  106. package/dist/bundler-NdSt2FYG.js.map +1 -0
  107. package/dist/bundler-U9F2---r.js +704 -0
  108. package/dist/bundler-U9F2---r.js.map +1 -0
  109. package/dist/bundler-u9WOUtpl.cjs +791 -0
  110. package/dist/bundler-u9WOUtpl.cjs.map +1 -0
  111. package/dist/bundlerOptions-9DigsVhY.js +180 -0
  112. package/dist/bundlerOptions-9DigsVhY.js.map +1 -0
  113. package/dist/bundlerOptions-CYRir4LE.cjs +194 -0
  114. package/dist/bundlerOptions-CYRir4LE.cjs.map +1 -0
  115. package/dist/core-D0wEgdn3.cjs +790 -0
  116. package/dist/core-D0wEgdn3.cjs.map +1 -0
  117. package/dist/core-DF65PJXc.js +790 -0
  118. package/dist/core-DF65PJXc.js.map +1 -0
  119. package/dist/deploy/log.d.ts +2 -2
  120. package/dist/deploy/log.d.ts.map +1 -1
  121. package/dist/dist-BauTimif.js +532 -0
  122. package/dist/dist-BauTimif.js.map +1 -0
  123. package/dist/dist-Cv-mAEtr.cjs +532 -0
  124. package/dist/dist-Cv-mAEtr.cjs.map +1 -0
  125. package/dist/docs/SKILL.md +31 -0
  126. package/dist/docs/assets/SOURCE_MAP.json +6 -0
  127. package/dist/docs/references/docs-deployment-cloud-providers.md +23 -0
  128. package/dist/docs/references/docs-deployment-mastra-server.md +157 -0
  129. package/dist/docs/references/docs-deployment-monorepo.md +140 -0
  130. package/dist/docs/references/docs-deployment-overview.md +79 -0
  131. package/dist/docs/references/docs-deployment-web-framework.md +54 -0
  132. package/dist/docs/references/docs-deployment-workflow-runners.md +17 -0
  133. package/dist/docs/references/reference-deployer.md +102 -0
  134. package/dist/effect-QlVUlMFu-CWx-dnsz.cjs +14 -0
  135. package/dist/effect-QlVUlMFu-CWx-dnsz.cjs.map +1 -0
  136. package/dist/effect-QlVUlMFu-CovUzKO9.js +14 -0
  137. package/dist/effect-QlVUlMFu-CovUzKO9.js.map +1 -0
  138. package/dist/esm-B51vJPGv.js +4634 -0
  139. package/dist/esm-B51vJPGv.js.map +1 -0
  140. package/dist/esm-DZ1Siz1C.cjs +4634 -0
  141. package/dist/esm-DZ1Siz1C.cjs.map +1 -0
  142. package/dist/index-CLddUTqr-Btqs8t-3.js +140 -0
  143. package/dist/index-CLddUTqr-Btqs8t-3.js.map +1 -0
  144. package/dist/index-CLddUTqr-C8lMvBz9.cjs +145 -0
  145. package/dist/index-CLddUTqr-C8lMvBz9.cjs.map +1 -0
  146. package/dist/index.cjs +35 -59
  147. package/dist/index.cjs.map +1 -1
  148. package/dist/index.js +29 -41
  149. package/dist/index.js.map +1 -1
  150. package/dist/rolldown-runtime-emK7D4bc.cjs +35 -0
  151. package/dist/server/handlers/a2a.d.ts +28 -3
  152. package/dist/server/handlers/a2a.d.ts.map +1 -1
  153. package/dist/server/handlers/agent-learning.d.ts +3 -0
  154. package/dist/server/handlers/agent-learning.d.ts.map +1 -0
  155. package/dist/server/handlers/health.d.ts +5 -0
  156. package/dist/server/handlers/health.d.ts.map +1 -0
  157. package/dist/server/handlers/restart-active-runs.d.ts +3 -0
  158. package/dist/server/handlers/restart-active-runs.d.ts.map +1 -0
  159. package/dist/server/handlers/utils/query-parsers.d.ts +15 -0
  160. package/dist/server/handlers/utils/query-parsers.d.ts.map +1 -1
  161. package/dist/server/handlers/utils.d.ts +0 -7
  162. package/dist/server/handlers/utils.d.ts.map +1 -1
  163. package/dist/server/index.cjs +4375 -11856
  164. package/dist/server/index.cjs.map +1 -1
  165. package/dist/server/index.d.ts +4 -13
  166. package/dist/server/index.d.ts.map +1 -1
  167. package/dist/server/index.js +4370 -11830
  168. package/dist/server/index.js.map +1 -1
  169. package/dist/server/types.d.ts +2 -1
  170. package/dist/server/types.d.ts.map +1 -1
  171. package/dist/server/welcome.d.ts +1 -1
  172. package/dist/server/welcome.d.ts.map +1 -1
  173. package/dist/services/deps.d.ts +9 -1
  174. package/dist/services/deps.d.ts.map +1 -1
  175. package/dist/services/env.d.ts.map +1 -1
  176. package/dist/services/index.cjs +5 -20
  177. package/dist/services/index.js +2 -3
  178. package/dist/services-BRF1RRXB.js +430 -0
  179. package/dist/services-BRF1RRXB.js.map +1 -0
  180. package/dist/services-_ksvysL5.cjs +469 -0
  181. package/dist/services-_ksvysL5.cjs.map +1 -0
  182. package/dist/sury-CWZTCd75-Bbjr0vWq.cjs +14 -0
  183. package/dist/sury-CWZTCd75-Bbjr0vWq.cjs.map +1 -0
  184. package/dist/sury-CWZTCd75-C3LyvnOp.js +14 -0
  185. package/dist/sury-CWZTCd75-C3LyvnOp.js.map +1 -0
  186. package/dist/typebox-Dei93FPO-EcvSqxpn.js +8 -0
  187. package/dist/typebox-Dei93FPO-EcvSqxpn.js.map +1 -0
  188. package/dist/typebox-Dei93FPO-n37w7tHC.cjs +8 -0
  189. package/dist/typebox-Dei93FPO-n37w7tHC.cjs.map +1 -0
  190. package/dist/utils-FVOUvj-I.js +190 -0
  191. package/dist/utils-FVOUvj-I.js.map +1 -0
  192. package/dist/utils-O98BGdnP.cjs +267 -0
  193. package/dist/utils-O98BGdnP.cjs.map +1 -0
  194. package/dist/valibot--1zFm7rT-BN2-Xy7Y.cjs +14 -0
  195. package/dist/valibot--1zFm7rT-BN2-Xy7Y.cjs.map +1 -0
  196. package/dist/valibot--1zFm7rT-DLXBDt2x.js +14 -0
  197. package/dist/valibot--1zFm7rT-DLXBDt2x.js.map +1 -0
  198. package/dist/validator/custom-resolver.cjs +77 -45
  199. package/dist/validator/custom-resolver.cjs.map +1 -1
  200. package/dist/validator/custom-resolver.d.ts +15 -1
  201. package/dist/validator/custom-resolver.d.ts.map +1 -1
  202. package/dist/validator/custom-resolver.js +74 -42
  203. package/dist/validator/custom-resolver.js.map +1 -1
  204. package/dist/validator/loader.cjs +6 -7
  205. package/dist/validator/loader.cjs.map +1 -1
  206. package/dist/validator/loader.js +8 -4
  207. package/dist/validator/loader.js.map +1 -1
  208. package/dist/validator/validate.d.ts +16 -1
  209. package/dist/validator/validate.d.ts.map +1 -1
  210. package/dist/zod-Bwrt9trS-Cbwhu5Zl.cjs +23 -0
  211. package/dist/zod-Bwrt9trS-Cbwhu5Zl.cjs.map +1 -0
  212. package/dist/zod-Bwrt9trS-Si3ZkB_H.js +23 -0
  213. package/dist/zod-Bwrt9trS-Si3ZkB_H.js.map +1 -0
  214. package/package.json +50 -45
  215. package/dist/build/analyze.cjs.map +0 -1
  216. package/dist/build/analyze.js.map +0 -1
  217. package/dist/build/babel/get-deployer.d.ts +0 -3
  218. package/dist/build/babel/get-deployer.d.ts.map +0 -1
  219. package/dist/build/babel/remove-all-options-bundler.d.ts +0 -5
  220. package/dist/build/babel/remove-all-options-bundler.d.ts.map +0 -1
  221. package/dist/build/babel/remove-all-options-deployer.d.ts +0 -5
  222. package/dist/build/babel/remove-all-options-deployer.d.ts.map +0 -1
  223. package/dist/build/babel/remove-all-options-server.d.ts +0 -5
  224. package/dist/build/babel/remove-all-options-server.d.ts.map +0 -1
  225. package/dist/build/babel/remove-all-options-telemetry.d.ts +0 -5
  226. package/dist/build/babel/remove-all-options-telemetry.d.ts.map +0 -1
  227. package/dist/build/bundler.cjs.map +0 -1
  228. package/dist/build/bundler.js.map +0 -1
  229. package/dist/build/customInstrumentation.d.ts +0 -10
  230. package/dist/build/customInstrumentation.d.ts.map +0 -1
  231. package/dist/build/index.cjs.map +0 -1
  232. package/dist/build/index.js.map +0 -1
  233. package/dist/build/telemetry.d.ts +0 -8
  234. package/dist/build/telemetry.d.ts.map +0 -1
  235. package/dist/bundler/index.cjs.map +0 -1
  236. package/dist/bundler/index.js.map +0 -1
  237. package/dist/chunk-3JYRSECU.cjs +0 -430
  238. package/dist/chunk-3JYRSECU.cjs.map +0 -1
  239. package/dist/chunk-465ZVXAK.js +0 -409
  240. package/dist/chunk-465ZVXAK.js.map +0 -1
  241. package/dist/chunk-5QFG6SCM.js +0 -398
  242. package/dist/chunk-5QFG6SCM.js.map +0 -1
  243. package/dist/chunk-CEXVMFUD.js +0 -1265
  244. package/dist/chunk-CEXVMFUD.js.map +0 -1
  245. package/dist/chunk-CKUCDCGI.js +0 -168
  246. package/dist/chunk-CKUCDCGI.js.map +0 -1
  247. package/dist/chunk-HMMDNIEQ.cjs +0 -167
  248. package/dist/chunk-HMMDNIEQ.cjs.map +0 -1
  249. package/dist/chunk-LGC3GUMR.cjs +0 -437
  250. package/dist/chunk-LGC3GUMR.cjs.map +0 -1
  251. package/dist/chunk-MCDDO4WY.cjs +0 -1309
  252. package/dist/chunk-MCDDO4WY.cjs.map +0 -1
  253. package/dist/chunk-OYO2MJED.cjs +0 -195
  254. package/dist/chunk-OYO2MJED.cjs.map +0 -1
  255. package/dist/chunk-SBTEIZ3B.js +0 -26
  256. package/dist/chunk-SBTEIZ3B.js.map +0 -1
  257. package/dist/chunk-WAWEQ3DP.js +0 -156
  258. package/dist/chunk-WAWEQ3DP.js.map +0 -1
  259. package/dist/chunk-WIQEFIRX.cjs +0 -28
  260. package/dist/chunk-WIQEFIRX.cjs.map +0 -1
  261. package/dist/server/handlers/auth/defaults.d.ts +0 -3
  262. package/dist/server/handlers/auth/defaults.d.ts.map +0 -1
  263. package/dist/server/handlers/auth/helpers.d.ts +0 -11
  264. package/dist/server/handlers/auth/helpers.d.ts.map +0 -1
  265. package/dist/server/handlers/auth/index.d.ts +0 -11
  266. package/dist/server/handlers/auth/index.d.ts.map +0 -1
  267. package/dist/server/handlers/prompt.d.ts +0 -3
  268. package/dist/server/handlers/prompt.d.ts.map +0 -1
  269. package/dist/server/handlers/routes/agent-builder/handlers.d.ts +0 -17
  270. package/dist/server/handlers/routes/agent-builder/handlers.d.ts.map +0 -1
  271. package/dist/server/handlers/routes/agent-builder/router.d.ts +0 -4
  272. package/dist/server/handlers/routes/agent-builder/router.d.ts.map +0 -1
  273. package/dist/server/handlers/routes/agents/handlers.d.ts +0 -363
  274. package/dist/server/handlers/routes/agents/handlers.d.ts.map +0 -1
  275. package/dist/server/handlers/routes/agents/router.d.ts +0 -5
  276. package/dist/server/handlers/routes/agents/router.d.ts.map +0 -1
  277. package/dist/server/handlers/routes/agents/voice.d.ts +0 -18
  278. package/dist/server/handlers/routes/agents/voice.d.ts.map +0 -1
  279. package/dist/server/handlers/routes/logs/handlers.d.ts +0 -5
  280. package/dist/server/handlers/routes/logs/handlers.d.ts.map +0 -1
  281. package/dist/server/handlers/routes/logs/router.d.ts +0 -3
  282. package/dist/server/handlers/routes/logs/router.d.ts.map +0 -1
  283. package/dist/server/handlers/routes/mcp/handlers.d.ts +0 -139
  284. package/dist/server/handlers/routes/mcp/handlers.d.ts.map +0 -1
  285. package/dist/server/handlers/routes/mcp/router.d.ts +0 -4
  286. package/dist/server/handlers/routes/mcp/router.d.ts.map +0 -1
  287. package/dist/server/handlers/routes/memory/handlers.d.ts +0 -17
  288. package/dist/server/handlers/routes/memory/handlers.d.ts.map +0 -1
  289. package/dist/server/handlers/routes/memory/router.d.ts +0 -4
  290. package/dist/server/handlers/routes/memory/router.d.ts.map +0 -1
  291. package/dist/server/handlers/routes/observability/handlers.d.ts +0 -6
  292. package/dist/server/handlers/routes/observability/handlers.d.ts.map +0 -1
  293. package/dist/server/handlers/routes/observability/router.d.ts +0 -3
  294. package/dist/server/handlers/routes/observability/router.d.ts.map +0 -1
  295. package/dist/server/handlers/routes/scores/handlers.d.ts +0 -300
  296. package/dist/server/handlers/routes/scores/handlers.d.ts.map +0 -1
  297. package/dist/server/handlers/routes/scores/router.d.ts +0 -4
  298. package/dist/server/handlers/routes/scores/router.d.ts.map +0 -1
  299. package/dist/server/handlers/routes/telemetry/handlers.d.ts +0 -4
  300. package/dist/server/handlers/routes/telemetry/handlers.d.ts.map +0 -1
  301. package/dist/server/handlers/routes/telemetry/router.d.ts +0 -3
  302. package/dist/server/handlers/routes/telemetry/router.d.ts.map +0 -1
  303. package/dist/server/handlers/routes/tools/handlers.d.ts +0 -7
  304. package/dist/server/handlers/routes/tools/handlers.d.ts.map +0 -1
  305. package/dist/server/handlers/routes/tools/router.d.ts +0 -4
  306. package/dist/server/handlers/routes/tools/router.d.ts.map +0 -1
  307. package/dist/server/handlers/routes/vector/handlers.d.ts +0 -10
  308. package/dist/server/handlers/routes/vector/handlers.d.ts.map +0 -1
  309. package/dist/server/handlers/routes/vector/router.d.ts +0 -4
  310. package/dist/server/handlers/routes/vector/router.d.ts.map +0 -1
  311. package/dist/server/handlers/routes/workflows/handlers.d.ts +0 -20
  312. package/dist/server/handlers/routes/workflows/handlers.d.ts.map +0 -1
  313. package/dist/server/handlers/routes/workflows/legacyWorkflows.d.ts +0 -11
  314. package/dist/server/handlers/routes/workflows/legacyWorkflows.d.ts.map +0 -1
  315. package/dist/server/handlers/routes/workflows/router.d.ts +0 -4
  316. package/dist/server/handlers/routes/workflows/router.d.ts.map +0 -1
  317. package/dist/services/index.cjs.map +0 -1
  318. package/dist/services/index.js.map +0 -1
  319. package/dist/templates/instrumentation-template.js +0 -172
@@ -0,0 +1,1158 @@
1
+ const require_rolldown_runtime = require("./rolldown-runtime-emK7D4bc.cjs");
2
+ const require_analyze = require("./analyze-D100622N.cjs");
3
+ const require_utils = require("./utils-O98BGdnP.cjs");
4
+ require("./services-_ksvysL5.cjs");
5
+ const require_bundler = require("./bundler-u9WOUtpl.cjs");
6
+ const require_bundlerOptions = require("./bundlerOptions-CYRir4LE.cjs");
7
+ let fs = require("fs");
8
+ let fs_promises = require("fs/promises");
9
+ let path = require("path");
10
+ let empathic_package = require("empathic/package");
11
+ empathic_package = require_rolldown_runtime.__toESM(empathic_package, 1);
12
+ let tinyglobby = require("tinyglobby");
13
+ let _babel_core = require("@babel/core");
14
+ let rollup = require("rollup");
15
+ let _mastra_core_logger = require("@mastra/core/logger");
16
+ let _mastra_core_agent = require("@mastra/core/agent");
17
+ let gray_matter = require("gray-matter");
18
+ gray_matter = require_rolldown_runtime.__toESM(gray_matter, 1);
19
+ //#region src/build/plugins/workspace-deps-watcher.ts
20
+ const SOURCE_GLOBS = ["**/*.{ts,tsx,js,jsx,mjs,cjs,json}"];
21
+ const SOURCE_IGNORE = ["**/node_modules/**", "**/.cache/**"];
22
+ /**
23
+ * During `mastra dev`, workspace packages are pre-transpiled into
24
+ * `<pkg>/node_modules/.cache/*.mjs` and marked external in the main Rollup
25
+ * watch graph. This plugin:
26
+ * 1. Watches the original workspace package sources so edits trigger rebuilds.
27
+ * 2. Regenerates the optimized `.cache` outputs when those sources change (or
28
+ * when cache files are missing) before the rebuild finishes — so a later
29
+ * server restart loads fresh package code.
30
+ */
31
+ function workspaceDepsWatcher(options) {
32
+ const { depsToOptimize, optimizedDependencyFiles, workspaceMap, workspaceRoot, outputDir, platform, bundlerOptions } = options;
33
+ let isFirstBuild = true;
34
+ const usedPackageRoots = collectUsedPackageRoots(depsToOptimize, workspaceMap);
35
+ const cachePaths = collectAbsoluteCachePaths(optimizedDependencyFiles, workspaceRoot);
36
+ return {
37
+ name: "workspace-deps-watcher",
38
+ async buildStart() {
39
+ const sourceFiles = await discoverWorkspaceSourceFiles(usedPackageRoots);
40
+ for (const file of sourceFiles) this.addWatchFile((0, path.resolve)(file));
41
+ if (isFirstBuild) {
42
+ isFirstBuild = false;
43
+ return;
44
+ }
45
+ if (!await isWorkspaceOutputStale(sourceFiles, cachePaths)) return;
46
+ await require_analyze.bundleExternals(cloneDepsToOptimize(depsToOptimize), outputDir, {
47
+ bundlerOptions: {
48
+ ...bundlerOptions,
49
+ externals: bundlerOptions?.externals ?? true,
50
+ isDev: true
51
+ },
52
+ projectRoot: workspaceRoot,
53
+ workspaceRoot,
54
+ workspaceMap,
55
+ platform
56
+ });
57
+ }
58
+ };
59
+ }
60
+ function collectUsedPackageRoots(depsToOptimize, workspaceMap) {
61
+ const roots = /* @__PURE__ */ new Set();
62
+ for (const [dep, metadata] of depsToOptimize.entries()) {
63
+ if (!metadata.isWorkspace) continue;
64
+ if (metadata.rootPath) {
65
+ roots.add(require_utils.slash(metadata.rootPath));
66
+ continue;
67
+ }
68
+ const pkgName = require_utils.getPackageName(dep);
69
+ const location = pkgName ? workspaceMap.get(pkgName)?.location : void 0;
70
+ if (location) roots.add(require_utils.slash(location));
71
+ }
72
+ return Array.from(roots);
73
+ }
74
+ function collectAbsoluteCachePaths(optimizedDependencyFiles, workspaceRoot) {
75
+ return Array.from(optimizedDependencyFiles.values()).map((relativePath) => (0, path.resolve)(workspaceRoot, relativePath));
76
+ }
77
+ async function discoverWorkspaceSourceFiles(packageRoots) {
78
+ if (packageRoots.length === 0) return [];
79
+ return (await Promise.all(packageRoots.map((root) => (0, tinyglobby.glob)(SOURCE_GLOBS, {
80
+ cwd: root,
81
+ absolute: true,
82
+ ignore: SOURCE_IGNORE,
83
+ onlyFiles: true
84
+ })))).flat();
85
+ }
86
+ async function isCacheMissing(cachePaths) {
87
+ for (const cachePath of cachePaths) if (!(0, fs.existsSync)(cachePath)) return true;
88
+ return false;
89
+ }
90
+ async function isWorkspaceOutputStale(sourceFiles, cachePaths) {
91
+ if (await isCacheMissing(cachePaths)) return true;
92
+ let cacheBaselineMs = 0;
93
+ for (const cachePath of cachePaths) try {
94
+ const { mtimeMs } = await (0, fs_promises.stat)(cachePath);
95
+ cacheBaselineMs = Math.max(cacheBaselineMs, mtimeMs);
96
+ } catch {
97
+ return true;
98
+ }
99
+ for (const file of sourceFiles) try {
100
+ const { mtimeMs } = await (0, fs_promises.stat)(file);
101
+ if (mtimeMs > cacheBaselineMs) return true;
102
+ } catch {
103
+ return true;
104
+ }
105
+ return false;
106
+ }
107
+ function cloneDepsToOptimize(deps) {
108
+ const copy = /* @__PURE__ */ new Map();
109
+ for (const [dep, metadata] of deps.entries()) copy.set(dep, {
110
+ ...metadata,
111
+ exports: [...metadata.exports]
112
+ });
113
+ return copy;
114
+ }
115
+ //#endregion
116
+ //#region src/build/watcher.ts
117
+ async function getInputOptions(entryFile, platform, env, { sourcemap = false, bundlerOptions = {
118
+ enableSourcemap: false,
119
+ enableEsmShim: true,
120
+ externals: true
121
+ }, analysisEntries = [entryFile] } = {}) {
122
+ const closestPkgJson = empathic_package.up({ cwd: (0, path.dirname)(entryFile) });
123
+ const projectRoot = closestPkgJson ? (0, path.dirname)(require_utils.slash(closestPkgJson)) : require_utils.slash(process.cwd());
124
+ const { workspaceMap, workspaceRoot } = await require_analyze.getWorkspaceInformation({ mastraEntryFile: entryFile });
125
+ const outputDir = path.posix.join(process.cwd(), ".mastra", ".build");
126
+ const analyzeEntryResult = await require_analyze.analyzeBundle(analysisEntries, entryFile, {
127
+ outputDir,
128
+ projectRoot: workspaceRoot || process.cwd(),
129
+ platform,
130
+ isDev: true,
131
+ bundlerOptions
132
+ }, _mastra_core_logger.noopLogger);
133
+ const deps = /* @__PURE__ */ new Map();
134
+ for (const [dep, metadata] of analyzeEntryResult.dependencies.entries()) {
135
+ const pkgName = require_utils.getPackageName(dep);
136
+ if (pkgName && workspaceMap.has(pkgName)) deps.set(dep, metadata);
137
+ }
138
+ const inputOptions = await require_bundler.getInputOptions(entryFile, {
139
+ dependencies: deps,
140
+ externalDependencies: /* @__PURE__ */ new Map(),
141
+ workspaceMap
142
+ }, platform, env, {
143
+ sourcemap,
144
+ isDev: true,
145
+ workspaceRoot,
146
+ projectRoot,
147
+ externalsPreset: bundlerOptions?.externals === true
148
+ });
149
+ if (Array.isArray(inputOptions.plugins)) {
150
+ const plugins = [];
151
+ inputOptions.plugins.forEach((plugin) => {
152
+ if (plugin?.name === "node-resolve") return;
153
+ if (plugin?.name === "tsconfig-paths") {
154
+ plugins.push(require_bundler.tsConfigPaths({ localResolve: true }));
155
+ return;
156
+ }
157
+ plugins.push(plugin);
158
+ });
159
+ inputOptions.plugins = plugins;
160
+ inputOptions.plugins.push(require_analyze.aliasHono());
161
+ inputOptions.plugins.push(require_bundler.nodeModulesExtensionResolver());
162
+ const depsToOptimize = analyzeEntryResult.depsToOptimize;
163
+ const resolvedWorkspaceRoot = analyzeEntryResult.workspaceRoot || workspaceRoot;
164
+ if (depsToOptimize?.size && resolvedWorkspaceRoot) inputOptions.plugins.push(workspaceDepsWatcher({
165
+ depsToOptimize,
166
+ optimizedDependencyFiles: deps,
167
+ workspaceMap,
168
+ workspaceRoot: resolvedWorkspaceRoot,
169
+ outputDir: analyzeEntryResult.outputDir || outputDir,
170
+ platform,
171
+ bundlerOptions
172
+ }));
173
+ }
174
+ return inputOptions;
175
+ }
176
+ async function createWatcher(inputOptions, outputOptions) {
177
+ return await (0, rollup.watch)({
178
+ ...inputOptions,
179
+ output: {
180
+ ...outputOptions,
181
+ format: "esm",
182
+ entryFileNames: "[name].mjs",
183
+ chunkFileNames: "[name].mjs"
184
+ }
185
+ });
186
+ }
187
+ //#endregion
188
+ //#region src/build/analyzeEntryProjectType.ts
189
+ /**
190
+ * Lightweight entry analysis that returns the detected project type by running
191
+ * only the Babel check-config-export plugin on the Mastra entry file. This is
192
+ * intentionally cheaper than `analyzeBundle` and is used by the CLI before
193
+ * `prepare()` clears `.mastra` to decide whether Factory-specific assets
194
+ * should be copied.
195
+ *
196
+ * Returns `'factory'` when the entry imports `MastraFactory` and
197
+ * constructs it, or `undefined` for ordinary Mastra projects.
198
+ */
199
+ async function analyzeEntryProjectType(mastraEntry) {
200
+ const code = await (0, fs_promises.readFile)(mastraEntry, "utf-8");
201
+ const result = { hasValidConfig: false };
202
+ await (0, _babel_core.transformAsync)(code, {
203
+ filename: mastraEntry,
204
+ presets: [{}.resolve("@babel/preset-typescript")],
205
+ plugins: [() => require_analyze.checkConfigExport(result)]
206
+ });
207
+ return result.projectType;
208
+ }
209
+ //#endregion
210
+ //#region src/build/serverOptions.ts
211
+ async function getServerOptions(entryFile, outputDir, logger) {
212
+ const result = await require_bundlerOptions.extractMastraOption("server", entryFile, outputDir, logger);
213
+ if (!result) return null;
214
+ return result.getConfig();
215
+ }
216
+ //#endregion
217
+ //#region src/build/fs-routing/discover.ts
218
+ /**
219
+ * Frontmatter keys a markdown schedule may set, in the order they are copied
220
+ * onto the definition. Anything outside this list fails the build rather than
221
+ * being silently dropped — a schedule that quietly ignores half its config is
222
+ * worse than one that refuses to build.
223
+ *
224
+ * The `satisfies` binds this list to core's definition type, so renaming or
225
+ * removing a field there breaks the build here instead of silently rejecting
226
+ * frontmatter that used to be valid. (`prompt` is excluded because the document
227
+ * body supplies it, `handler` because markdown can't carry a function.)
228
+ */
229
+ const MARKDOWN_SCHEDULE_KEYS = [
230
+ "cron",
231
+ "timezone",
232
+ "name",
233
+ "threadId",
234
+ "resourceId",
235
+ "signalType",
236
+ "tagName",
237
+ "attributes",
238
+ "providerOptions",
239
+ "ifActive",
240
+ "ifIdle",
241
+ "status",
242
+ "metadata"
243
+ ];
244
+ const CONFIG_BASENAMES = ["config.ts", "config.js"];
245
+ const WORKSPACE_BASENAMES = ["workspace.ts", "workspace.js"];
246
+ const MEMORY_BASENAMES = ["memory.ts", "memory.js"];
247
+ const INSTRUCTIONS_BASENAME = "instructions.md";
248
+ const INSTRUCTIONS_MODULE_BASENAMES = ["instructions.ts", "instructions.js"];
249
+ const TOOL_EXTENSIONS = [".ts", ".js"];
250
+ const SCHEDULE_MODULE_EXTENSIONS = [".ts", ".js"];
251
+ const SKILL_MODULE_EXTENSIONS = [".ts", ".js"];
252
+ const SKILL_MD_BASENAME = "SKILL.md";
253
+ /**
254
+ * Presence check that does NOT follow symlinks. Returns `false` for symlinks
255
+ * (and broken links) so a symlinked `config.ts`/`instructions.md`/
256
+ * `instructions.ts`/`workspace.ts`/`memory.ts` is never inlined or imported
257
+ * into the generated bundle.
258
+ */
259
+ async function exists(path$1) {
260
+ try {
261
+ return !(await (0, fs_promises.lstat)(path$1)).isSymbolicLink();
262
+ } catch {
263
+ return false;
264
+ }
265
+ }
266
+ /**
267
+ * Returns the slash-normalized path when `path` is a real directory (not a
268
+ * symlink). Symlinked directories are rejected to prevent the build from
269
+ * following links out of the project tree during discovery.
270
+ */
271
+ async function realDirectory(path$2) {
272
+ try {
273
+ const info = await (0, fs_promises.lstat)(path$2);
274
+ if (info.isDirectory() && !info.isSymbolicLink()) return require_utils.slash(path$2);
275
+ } catch {}
276
+ }
277
+ async function directoryExists(path$3) {
278
+ return realDirectory(path$3);
279
+ }
280
+ async function firstExisting(dir, basenames) {
281
+ for (const basename of basenames) {
282
+ const candidate = (0, path.join)(dir, basename);
283
+ if (await exists(candidate)) return require_utils.slash(candidate);
284
+ }
285
+ }
286
+ function isTestFile(basename) {
287
+ return /\.(test|spec)\.(ts|js)$/.test(basename);
288
+ }
289
+ function toolKey(basename) {
290
+ return basename.replace(/\.(ts|js)$/, "");
291
+ }
292
+ /**
293
+ * Discover default-exporting `.ts`/`.js` modules directly under `dir`, returning
294
+ * `{ key, path }` entries in stable (sorted) order. Test files, symlinks, and
295
+ * subdirectories are skipped: a symlinked module could point anywhere on the
296
+ * build machine and be embedded into generated import code. Shared by the
297
+ * `tools/` and `scorers/` scanners.
298
+ */
299
+ async function discoverModuleDir(dir) {
300
+ if (!await exists(dir)) return [];
301
+ let entries;
302
+ try {
303
+ entries = await (0, fs_promises.readdir)(dir);
304
+ } catch {
305
+ return [];
306
+ }
307
+ const modules = [];
308
+ for (const basename of entries.sort()) {
309
+ if (isTestFile(basename)) continue;
310
+ if (!TOOL_EXTENSIONS.some((ext) => basename.endsWith(ext))) continue;
311
+ const path$4 = (0, path.join)(dir, basename);
312
+ const stats = await (0, fs_promises.lstat)(path$4);
313
+ if (stats.isSymbolicLink() || stats.isDirectory()) continue;
314
+ modules.push({
315
+ key: toolKey(basename),
316
+ path: require_utils.slash(path$4)
317
+ });
318
+ }
319
+ return modules;
320
+ }
321
+ async function discoverTools(toolsDir) {
322
+ return discoverModuleDir(toolsDir);
323
+ }
324
+ async function discoverProcessors(processorsDir) {
325
+ const result = {
326
+ input: [],
327
+ output: []
328
+ };
329
+ for (const type of ["input", "output"]) {
330
+ const typeDir = (0, path.join)(processorsDir, type);
331
+ if (!await exists(typeDir)) continue;
332
+ let entries;
333
+ try {
334
+ entries = await (0, fs_promises.readdir)(typeDir);
335
+ } catch {
336
+ continue;
337
+ }
338
+ for (const basename of entries.sort()) {
339
+ if (isTestFile(basename)) continue;
340
+ if (!TOOL_EXTENSIONS.some((ext) => basename.endsWith(ext))) continue;
341
+ const path$5 = (0, path.join)(typeDir, basename);
342
+ const stats = await (0, fs_promises.lstat)(path$5);
343
+ if (stats.isSymbolicLink() || stats.isDirectory()) continue;
344
+ result[type].push({
345
+ key: toolKey(basename),
346
+ path: require_utils.slash(path$5)
347
+ });
348
+ }
349
+ }
350
+ return result;
351
+ }
352
+ async function readReferences(referencesDir) {
353
+ if (!await exists(referencesDir)) return {};
354
+ const references = {};
355
+ let entries;
356
+ try {
357
+ entries = await (0, fs_promises.readdir)(referencesDir);
358
+ } catch {
359
+ return {};
360
+ }
361
+ for (const basename of entries.sort()) {
362
+ const path$6 = (0, path.join)(referencesDir, basename);
363
+ const stats = await (0, fs_promises.lstat)(path$6);
364
+ if (stats.isSymbolicLink() || stats.isDirectory()) continue;
365
+ references[basename] = await (0, fs_promises.readFile)(path$6, "utf-8");
366
+ }
367
+ return references;
368
+ }
369
+ async function parsePackagedSkill(skillMdPath, fallbackName, references = {}) {
370
+ const parsed = (0, gray_matter.default)(await (0, fs_promises.readFile)(skillMdPath, "utf-8"));
371
+ const frontmatter = parsed.data;
372
+ const name = frontmatter.name ?? fallbackName;
373
+ const description = frontmatter.description;
374
+ if (!description) throw new Error(`Skill "${name}" in ${skillMdPath} is missing a required "description". Add a YAML frontmatter block with a "description:" field. See https://agentskills.io/specification for the SKILL.md format.`);
375
+ return {
376
+ kind: "packaged",
377
+ name,
378
+ description,
379
+ instructions: parsed.content.trim(),
380
+ references
381
+ };
382
+ }
383
+ function skillModuleName(basename) {
384
+ return basename.replace(/\.(ts|js)$/, "");
385
+ }
386
+ async function discoverSkills(skillsDir) {
387
+ if (!await exists(skillsDir)) return [];
388
+ let entries;
389
+ try {
390
+ entries = await (0, fs_promises.readdir)(skillsDir);
391
+ } catch {
392
+ return [];
393
+ }
394
+ const skills = [];
395
+ for (const basename of entries.sort()) {
396
+ if (isTestFile(basename)) continue;
397
+ const path$7 = (0, path.join)(skillsDir, basename);
398
+ const stats = await (0, fs_promises.lstat)(path$7);
399
+ if (stats.isSymbolicLink()) continue;
400
+ if (stats.isDirectory()) {
401
+ const skillMd = (0, path.join)(path$7, SKILL_MD_BASENAME);
402
+ if (await exists(skillMd)) {
403
+ const references = await readReferences((0, path.join)(path$7, "references"));
404
+ skills.push(await parsePackagedSkill(skillMd, skillModuleName(basename), references));
405
+ }
406
+ continue;
407
+ }
408
+ if (SKILL_MODULE_EXTENSIONS.some((ext) => basename.endsWith(ext))) {
409
+ skills.push({
410
+ kind: "module",
411
+ path: require_utils.slash(path$7)
412
+ });
413
+ continue;
414
+ }
415
+ if (basename.endsWith(".md")) {
416
+ const skill = await parsePackagedSkill(path$7, basename.replace(/\.md$/, ""));
417
+ skills.push(skill);
418
+ }
419
+ }
420
+ return skills;
421
+ }
422
+ /**
423
+ * Parse a markdown schedule: YAML frontmatter for the cron (and other JSON-safe
424
+ * options), document body for the prompt.
425
+ *
426
+ * Throws a build error naming the file when `cron` is missing or the body is
427
+ * empty — a schedule that can't fire is never what the author meant.
428
+ */
429
+ async function parseMarkdownSchedule(path$8, key) {
430
+ const raw = await (0, fs_promises.readFile)(path$8, "utf-8");
431
+ let parsed;
432
+ try {
433
+ parsed = (0, gray_matter.default)(raw);
434
+ } catch (error) {
435
+ const detail = error instanceof Error ? error.message.split("\n")[0] : String(error);
436
+ throw new Error(`Schedule "${key}" in ${path$8} has invalid YAML frontmatter: ${detail}. Cron expressions must be quoted (cron: "*/5 * * * *"), because a leading "*" is a YAML alias.`);
437
+ }
438
+ const frontmatter = parsed.data ?? {};
439
+ const prompt = parsed.content.trim();
440
+ const unknown = Object.keys(frontmatter).filter((field) => !MARKDOWN_SCHEDULE_KEYS.includes(field));
441
+ if (unknown.length > 0) {
442
+ const hint = unknown.includes("prompt") ? ` The document body is used as the prompt, so "prompt" cannot be set in frontmatter.` : ` Supported fields: ${MARKDOWN_SCHEDULE_KEYS.join(", ")}. Handler mode requires a .ts or .js schedule.`;
443
+ throw new Error(`Schedule "${key}" in ${path$8} has unknown frontmatter field(s): ${unknown.join(", ")}.${hint}`);
444
+ }
445
+ if (!frontmatter.cron || typeof frontmatter.cron !== "string") throw new Error(`Schedule "${key}" in ${path$8} is missing a required "cron". Add a YAML frontmatter block with a "cron:" field (e.g. cron: "0 9 * * *").`);
446
+ if (!prompt) throw new Error(`Schedule "${key}" in ${path$8} has an empty body. The document body is used as the prompt, so it cannot be blank.`);
447
+ const definition = {
448
+ cron: frontmatter.cron,
449
+ prompt
450
+ };
451
+ for (const field of MARKDOWN_SCHEDULE_KEYS) {
452
+ if (field === "cron") continue;
453
+ if (frontmatter[field] !== void 0) definition[field] = frontmatter[field];
454
+ }
455
+ return definition;
456
+ }
457
+ /**
458
+ * Discover schedules under `agents/<name>/schedules/`, recursing into
459
+ * subdirectories so a schedule's identity is its path relative to `schedules/`
460
+ * with the extension stripped (`billing/sweep.ts` → `billing/sweep`).
461
+ *
462
+ * Test files and symlinks (files and directories alike) are skipped for the
463
+ * same reason as the other scanners: a symlink could point anywhere on the
464
+ * build machine and be embedded into generated import code.
465
+ */
466
+ async function discoverSchedules(schedulesDir, prefix = "") {
467
+ if (!await exists(schedulesDir)) return [];
468
+ let entries;
469
+ try {
470
+ entries = await (0, fs_promises.readdir)(schedulesDir);
471
+ } catch {
472
+ return [];
473
+ }
474
+ const schedules = [];
475
+ for (const basename of entries.sort()) {
476
+ const path$9 = (0, path.join)(schedulesDir, basename);
477
+ let stats;
478
+ try {
479
+ stats = await (0, fs_promises.lstat)(path$9);
480
+ } catch {
481
+ continue;
482
+ }
483
+ if (stats.isSymbolicLink()) continue;
484
+ if (stats.isDirectory()) {
485
+ schedules.push(...await discoverSchedules(path$9, `${prefix}${basename}/`));
486
+ continue;
487
+ }
488
+ if (isTestFile(basename)) continue;
489
+ if (SCHEDULE_MODULE_EXTENSIONS.some((ext) => basename.endsWith(ext))) {
490
+ schedules.push({
491
+ kind: "module",
492
+ key: `${prefix}${basename.replace(/\.(ts|js)$/, "")}`,
493
+ path: require_utils.slash(path$9)
494
+ });
495
+ continue;
496
+ }
497
+ if (basename.endsWith(".md")) {
498
+ const key = `${prefix}${basename.replace(/\.md$/, "")}`;
499
+ schedules.push({
500
+ kind: "markdown",
501
+ key,
502
+ path: require_utils.slash(path$9),
503
+ definition: await parseMarkdownSchedule(path$9, key)
504
+ });
505
+ }
506
+ }
507
+ return schedules.sort((left, right) => left.key < right.key ? -1 : left.key > right.key ? 1 : 0);
508
+ }
509
+ /**
510
+ * Discover a single agent directory: its `config`/`instructions`/`workspace`
511
+ * files plus `tools/`, `skills/`, and declared `subagents/`. Returns
512
+ * `undefined` when `dir` is not an agent directory (no `config.(ts|js)`, no
513
+ * `instructions.md`, and no `instructions.(ts|js)`).
514
+ *
515
+ * `depth` is the subagent nesting level (`0` for top-level agents). Discovery
516
+ * recurses into `subagents/` until `MAX_FS_SUBAGENT_DEPTH`; deeper directories
517
+ * are ignored with a warning.
518
+ */
519
+ async function discoverAgentDir(dir, name, depth, onWarn) {
520
+ const configPath = await firstExisting(dir, CONFIG_BASENAMES);
521
+ const instructionsPath = await exists((0, path.join)(dir, INSTRUCTIONS_BASENAME)) ? require_utils.slash((0, path.join)(dir, INSTRUCTIONS_BASENAME)) : void 0;
522
+ const instructionsModulePath = await firstExisting(dir, INSTRUCTIONS_MODULE_BASENAMES);
523
+ if (!configPath && !instructionsPath && !instructionsModulePath) return;
524
+ const workspacePath = await firstExisting(dir, WORKSPACE_BASENAMES);
525
+ const memoryPath = await firstExisting(dir, MEMORY_BASENAMES);
526
+ const workspaceSeedDir = await directoryExists((0, path.join)(dir, "workspace"));
527
+ const tools = await discoverTools((0, path.join)(dir, "tools"));
528
+ const processors = await discoverProcessors((0, path.join)(dir, "processors"));
529
+ const scorers = await discoverModuleDir((0, path.join)(dir, "scorers"));
530
+ const skills = await discoverSkills((0, path.join)(dir, "skills"));
531
+ const schedules = await discoverSchedules((0, path.join)(dir, "schedules"));
532
+ const subagents = await discoverSubagents(dir, depth, onWarn);
533
+ return {
534
+ name,
535
+ dir: require_utils.slash(dir),
536
+ configPath,
537
+ instructionsPath,
538
+ instructionsModulePath,
539
+ workspacePath,
540
+ memoryPath,
541
+ workspaceSeedDir,
542
+ tools,
543
+ inputProcessors: processors.input,
544
+ outputProcessors: processors.output,
545
+ scorers,
546
+ skills,
547
+ schedules,
548
+ subagents
549
+ };
550
+ }
551
+ /**
552
+ * Discover declared subagents under `<dir>/subagents/*`. `parentDepth` is the
553
+ * parent agent's nesting level (`0` for top-level agents). Discovery recurses
554
+ * until `MAX_FS_SUBAGENT_DEPTH` levels of subagents; a `subagents/` directory
555
+ * that would exceed the cap is skipped with a warning.
556
+ */
557
+ async function discoverSubagents(parentDir, parentDepth, onWarn) {
558
+ const subagentsDir = (0, path.join)(parentDir, "subagents");
559
+ if (!await exists(subagentsDir)) return [];
560
+ if (parentDepth >= _mastra_core_agent.MAX_FS_SUBAGENT_DEPTH) {
561
+ onWarn?.(`Ignoring subagents in "${require_utils.slash(subagentsDir)}": subagents may only nest ${_mastra_core_agent.MAX_FS_SUBAGENT_DEPTH} levels below a top-level agent.`);
562
+ return [];
563
+ }
564
+ let entries;
565
+ try {
566
+ entries = await (0, fs_promises.readdir)(subagentsDir);
567
+ } catch {
568
+ return [];
569
+ }
570
+ const subagents = [];
571
+ for (const name of entries.sort()) {
572
+ const dir = (0, path.join)(subagentsDir, name);
573
+ if (!await realDirectory(dir)) continue;
574
+ const child = await discoverAgentDir(dir, name, parentDepth + 1, onWarn);
575
+ if (child) subagents.push(child);
576
+ }
577
+ return subagents;
578
+ }
579
+ /**
580
+ * Scan `<mastraDir>/agents/*` for file-system routed agents. A directory is
581
+ * treated as an agent only when it contains a `config.(ts|js)`, an
582
+ * `instructions.md`, or an `instructions.(ts|js)`; other directories are
583
+ * ignored. Each agent may declare `subagents/` up to `MAX_FS_SUBAGENT_DEPTH`
584
+ * levels deep. Returns descriptors with absolute, slash-normalized paths ready
585
+ * for codegen. Performs no module evaluation — only filesystem inspection.
586
+ */
587
+ async function discoverFsAgents(mastraDir, onWarn) {
588
+ const agentsDir = (0, path.join)(mastraDir, "agents");
589
+ if (!await exists(agentsDir)) return [];
590
+ let entries;
591
+ try {
592
+ entries = await (0, fs_promises.readdir)(agentsDir);
593
+ } catch {
594
+ return [];
595
+ }
596
+ const discovered = [];
597
+ for (const name of entries.sort()) {
598
+ const dir = (0, path.join)(agentsDir, name);
599
+ if (!await realDirectory(dir)) continue;
600
+ const agent = await discoverAgentDir(dir, name, 0, onWarn);
601
+ if (agent) discovered.push(agent);
602
+ }
603
+ return discovered;
604
+ }
605
+ /**
606
+ * Scan `<mastraDir>/workflows/` for file-system routed workflow modules. Only
607
+ * files whose source contains an `export default` are treated as fs-routed
608
+ * workflows — this convention distinguishes them from workflow files that are
609
+ * manually imported and registered programmatically. Returns descriptors with
610
+ * absolute, slash-normalized paths ready for codegen. Performs no module
611
+ * evaluation — only filesystem and source-text inspection.
612
+ */
613
+ async function discoverFsWorkflows(mastraDir) {
614
+ const workflowsDir = (0, path.join)(mastraDir, "workflows");
615
+ if (!await exists(workflowsDir)) return [];
616
+ let entries;
617
+ try {
618
+ entries = await (0, fs_promises.readdir)(workflowsDir);
619
+ } catch {
620
+ return [];
621
+ }
622
+ const discovered = [];
623
+ for (const basename of entries.sort()) {
624
+ if (isTestFile(basename)) continue;
625
+ if (!TOOL_EXTENSIONS.some((ext) => basename.endsWith(ext))) continue;
626
+ const path$10 = (0, path.join)(workflowsDir, basename);
627
+ const stats = await (0, fs_promises.lstat)(path$10);
628
+ if (stats.isSymbolicLink() || stats.isDirectory()) continue;
629
+ const source = await (0, fs_promises.readFile)(path$10, "utf-8");
630
+ if (!/\bexport\s+default\b/.test(source)) continue;
631
+ discovered.push({
632
+ key: toolKey(basename),
633
+ path: require_utils.slash(path$10)
634
+ });
635
+ }
636
+ return discovered;
637
+ }
638
+ const SINGLETON_EXTENSIONS = [
639
+ ".ts",
640
+ ".js",
641
+ ".mts",
642
+ ".mjs"
643
+ ];
644
+ /** Safe singleton identifier: no path separators, `..`, or other traversal. */
645
+ const SINGLETON_NAME_PATTERN = /^[a-zA-Z0-9_-]+$/;
646
+ /**
647
+ * Check for a singleton config file (e.g. `storage.ts`, `storage.js`) directly
648
+ * under `<mastraDir>`. Returns the first matching file path or `undefined`.
649
+ * Symlinks are rejected for security.
650
+ *
651
+ * Convention: only files with `export default` are fs-routed singletons. Files
652
+ * using named exports are assumed to be manually imported into the user's
653
+ * `index.ts`, so they are ignored to remain backward-compatible with existing
654
+ * project structures.
655
+ *
656
+ * `name` must be a bare identifier — path separators and traversal sequences are
657
+ * rejected so the lookup can never escape `<mastraDir>`.
658
+ */
659
+ async function discoverFsSingleton(mastraDir, name) {
660
+ if (!SINGLETON_NAME_PATTERN.test(name)) throw new Error(`Invalid fs-singleton name ${JSON.stringify(name)}: expected a bare identifier.`);
661
+ for (const ext of SINGLETON_EXTENSIONS) {
662
+ const candidate = (0, path.join)(mastraDir, `${name}${ext}`);
663
+ try {
664
+ const stats = await (0, fs_promises.lstat)(candidate);
665
+ if (!stats.isFile() || stats.isSymbolicLink()) continue;
666
+ const source = await (0, fs_promises.readFile)(candidate, "utf-8");
667
+ if (!/\bexport\s+default\b/.test(source)) continue;
668
+ return { path: require_utils.slash(candidate) };
669
+ } catch {}
670
+ }
671
+ }
672
+ //#endregion
673
+ //#region src/build/fs-routing/codegen.ts
674
+ function sanitizeIdentifier(name, prefix, index) {
675
+ return `${prefix}_${index}_${name.replace(/[^a-zA-Z0-9_$]/g, "_")}`;
676
+ }
677
+ /**
678
+ * Emit the imports for a single discovered agent into `lines` and return the
679
+ * source of its `assembleAgentFromFsEntry` entry object (the `{ name, config,
680
+ * ... }` argument). `idPath` is a dot-free, unique path index (e.g. `0` for the
681
+ * first top-level agent, `0_1` for its second subagent) used to keep generated
682
+ * identifiers unique across the parent/child tree. `workspaceName` is the
683
+ * slash-joined workspace key (`<parent>/<child>` for subagents) so seed files
684
+ * don't collide. Discovered subagents are emitted recursively as a nested
685
+ * `subagents: [...]` field (discovery already enforces the depth cap).
686
+ */
687
+ async function emitAgentEntry(agent, idPath, workspaceName, lines) {
688
+ const configIdent = sanitizeIdentifier(agent.name, "config", idPath);
689
+ const toolIdents = [];
690
+ if (agent.configPath) lines.push(`import ${configIdent} from ${JSON.stringify(agent.configPath)};`);
691
+ let workspaceIdent;
692
+ if (agent.workspacePath) {
693
+ workspaceIdent = sanitizeIdentifier(`${agent.name}_workspace`, "workspace", idPath);
694
+ lines.push(`import ${workspaceIdent} from ${JSON.stringify(agent.workspacePath)};`);
695
+ }
696
+ let memoryIdent;
697
+ if (agent.memoryPath) {
698
+ memoryIdent = sanitizeIdentifier(`${agent.name}_memory`, "memory", idPath);
699
+ lines.push(`import ${memoryIdent} from ${JSON.stringify(agent.memoryPath)};`);
700
+ }
701
+ let instructionsIdent;
702
+ if (agent.instructionsModulePath) {
703
+ instructionsIdent = sanitizeIdentifier(`${agent.name}_instructions`, "instructions", idPath);
704
+ lines.push(`import ${instructionsIdent} from ${JSON.stringify(agent.instructionsModulePath)};`);
705
+ }
706
+ for (let t = 0; t < agent.tools.length; t++) {
707
+ const tool = agent.tools[t];
708
+ const ident = sanitizeIdentifier(`${agent.name}_${tool.key}`, "tool", `${idPath}_${t}`);
709
+ lines.push(`import ${ident} from ${JSON.stringify(tool.path)};`);
710
+ toolIdents.push({
711
+ key: tool.key,
712
+ ident
713
+ });
714
+ }
715
+ const inputProcessorIdents = [];
716
+ for (let p = 0; p < agent.inputProcessors.length; p++) {
717
+ const proc = agent.inputProcessors[p];
718
+ const ident = sanitizeIdentifier(`${agent.name}_inputProc_${proc.key}`, "proc", `${idPath}_ip${p}`);
719
+ lines.push(`import ${ident} from ${JSON.stringify(proc.path)};`);
720
+ inputProcessorIdents.push(ident);
721
+ }
722
+ const outputProcessorIdents = [];
723
+ for (let p = 0; p < agent.outputProcessors.length; p++) {
724
+ const proc = agent.outputProcessors[p];
725
+ const ident = sanitizeIdentifier(`${agent.name}_outputProc_${proc.key}`, "proc", `${idPath}_op${p}`);
726
+ lines.push(`import ${ident} from ${JSON.stringify(proc.path)};`);
727
+ outputProcessorIdents.push(ident);
728
+ }
729
+ const scorerIdents = [];
730
+ for (let s = 0; s < agent.scorers.length; s++) {
731
+ const scorer = agent.scorers[s];
732
+ const ident = sanitizeIdentifier(`${agent.name}_scorer_${scorer.key}`, "scorer", `${idPath}_${s}`);
733
+ lines.push(`import ${ident} from ${JSON.stringify(scorer.path)};`);
734
+ scorerIdents.push({
735
+ key: scorer.key,
736
+ ident
737
+ });
738
+ }
739
+ const skillExprs = [];
740
+ const agentSkills = agent.skills ?? [];
741
+ for (let s = 0; s < agentSkills.length; s++) {
742
+ const skill = agentSkills[s];
743
+ if (skill.kind === "module") {
744
+ const ident = sanitizeIdentifier(`${agent.name}_skill`, "skill", `${idPath}_${s}`);
745
+ lines.push(`import ${ident} from ${JSON.stringify(skill.path)};`);
746
+ skillExprs.push(ident);
747
+ } else {
748
+ const referenceFields = Object.entries(skill.references).map(([key, value]) => `${JSON.stringify(key)}: ${JSON.stringify(value)}`);
749
+ const skillFields = [
750
+ `name: ${JSON.stringify(skill.name)}`,
751
+ `description: ${JSON.stringify(skill.description)}`,
752
+ `instructions: ${JSON.stringify(skill.instructions)}`
753
+ ];
754
+ if (referenceFields.length > 0) skillFields.push(`references: { ${referenceFields.join(", ")} }`);
755
+ skillExprs.push(`__createSkill({ ${skillFields.join(", ")} })`);
756
+ }
757
+ }
758
+ const scheduleExprs = [];
759
+ const agentSchedules = agent.schedules ?? [];
760
+ for (let s = 0; s < agentSchedules.length; s++) {
761
+ const schedule = agentSchedules[s];
762
+ const keyField = `key: ${JSON.stringify(schedule.key)}`;
763
+ if (schedule.kind === "module") {
764
+ const ident = sanitizeIdentifier(`${agent.name}_schedule`, "schedule", `${idPath}_${s}`);
765
+ lines.push(`import ${ident} from ${JSON.stringify(schedule.path)};`);
766
+ scheduleExprs.push(`{ ${keyField}, schedule: ${ident} }`);
767
+ } else scheduleExprs.push(`{ ${keyField}, schedule: ${JSON.stringify(schedule.definition)} }`);
768
+ }
769
+ let instructionsMd;
770
+ if (agent.instructionsPath) instructionsMd = await (0, fs_promises.readFile)(agent.instructionsPath, "utf-8");
771
+ const subagentExprs = [];
772
+ for (let c = 0; c < agent.subagents.length; c++) {
773
+ const child = agent.subagents[c];
774
+ const childExpr = await emitAgentEntry(child, `${idPath}_${c}`, `${workspaceName}/${child.name}`, lines);
775
+ subagentExprs.push(childExpr);
776
+ }
777
+ const entryFields = [`name: ${JSON.stringify(agent.name)}`];
778
+ if (agent.configPath) entryFields.push(`config: ${configIdent}`);
779
+ if (instructionsIdent) entryFields.push(`instructions: ${instructionsIdent}`);
780
+ if (instructionsMd !== void 0) entryFields.push(`instructionsMd: ${JSON.stringify(instructionsMd)}`);
781
+ if (toolIdents.length > 0) {
782
+ const toolEntries = toolIdents.map(({ key, ident }) => `{ key: ${JSON.stringify(key)}, tool: ${ident} }`);
783
+ entryFields.push(`tools: [${toolEntries.join(", ")}]`);
784
+ }
785
+ if (skillExprs.length > 0) entryFields.push(`skills: [${skillExprs.join(", ")}]`);
786
+ if (inputProcessorIdents.length > 0) entryFields.push(`inputProcessors: [${inputProcessorIdents.join(", ")}]`);
787
+ if (outputProcessorIdents.length > 0) entryFields.push(`outputProcessors: [${outputProcessorIdents.join(", ")}]`);
788
+ if (scorerIdents.length > 0) {
789
+ const scorerEntries = scorerIdents.map(({ key, ident }) => `{ key: ${JSON.stringify(key)}, scorer: ${ident} }`);
790
+ entryFields.push(`scorers: [${scorerEntries.join(", ")}]`);
791
+ }
792
+ if (scheduleExprs.length > 0) entryFields.push(`schedules: [${scheduleExprs.join(", ")}]`);
793
+ if (subagentExprs.length > 0) entryFields.push(`subagents: [${subagentExprs.join(", ")}]`);
794
+ if (workspaceIdent) entryFields.push(`workspace: ${workspaceIdent}`);
795
+ if (memoryIdent) entryFields.push(`memory: ${memoryIdent}`);
796
+ entryFields.push(`defaultWorkspaceBasePath: __workspaceBasePath(${JSON.stringify(workspaceName)})`);
797
+ return `{ ${entryFields.join(", ")} }`;
798
+ }
799
+ /**
800
+ * Generate the source of a wrapper module that:
801
+ * 1. imports the user's real Mastra entry,
802
+ * 2. imports each discovered `config.ts`, `instructions.ts`, `tools/*.ts`,
803
+ * `skills/*.ts` (`createSkill(...)` modules), `workspace.ts`, and
804
+ * `memory.ts`, inlining packaged `SKILL.md` skills,
805
+ * 3. assembles `Agent` instances via `assembleAgentFromFsEntry`, wiring any
806
+ * declared `subagents/` into the parent (nested up to `MAX_FS_SUBAGENT_DEPTH`),
807
+ * 4. registers them onto the user's `mastra` instance (code-registered agents
808
+ * win on name collisions), and
809
+ * 5. re-exports everything from the user's entry so this module is a drop-in
810
+ * replacement for the original `#mastra` target.
811
+ *
812
+ * `instructions.md` is read into the generated wrapper. In dev, the CLI watcher
813
+ * regenerates that wrapper when the markdown file changes. `instructions.ts` is
814
+ * imported instead, so the bundler already tracks it through the module graph.
815
+ *
816
+ * @param userEntry slash-normalized absolute path to the user's mastra entry.
817
+ * @param agents discovered fs-routed agents (absolute, slash-normalized paths).
818
+ */
819
+ async function generateFsAgentsModule(userEntry, agents, options) {
820
+ const workflows = options?.workflows ?? [];
821
+ const storage = options?.storage;
822
+ const observability = options?.observability;
823
+ const logger = options?.logger;
824
+ const server = options?.server;
825
+ const studio = options?.studio;
826
+ const standalone = userEntry === void 0;
827
+ const lines = [];
828
+ const hasInlineSkills = (function check(list) {
829
+ return list.some((a) => (a.skills ?? []).some((s) => s.kind === "packaged") || check(a.subagents ?? []));
830
+ })(agents);
831
+ lines.push(`import { assembleAgentFromFsEntry } from '@mastra/core/agent';`);
832
+ if (hasInlineSkills) lines.push(`import { createSkill as __createSkill } from '@mastra/core/skills';`);
833
+ if (standalone) lines.push(`import { Mastra } from '@mastra/core';`);
834
+ lines.push(`import { fileURLToPath as __fileURLToPath } from 'node:url';`);
835
+ lines.push(`import { dirname as __dirname, join as __join } from 'node:path';`);
836
+ if (userEntry) {
837
+ lines.push(`import * as __userEntry from ${JSON.stringify(userEntry)};`);
838
+ lines.push(`export * from ${JSON.stringify(userEntry)};`);
839
+ }
840
+ lines.push(``);
841
+ lines.push(`const __bundleDir = __dirname(__fileURLToPath(import.meta.url));`);
842
+ lines.push(`const __workspaceBasePath = name => __join(__bundleDir, 'workspace', ...name.split('/'));`);
843
+ lines.push(``);
844
+ const singletonImports = [];
845
+ if (storage) singletonImports.push(`import __fsStorage from ${JSON.stringify(storage.path)};`);
846
+ if (observability) singletonImports.push(`import __fsObservability from ${JSON.stringify(observability.path)};`);
847
+ if (logger) singletonImports.push(`import __fsLogger from ${JSON.stringify(logger.path)};`);
848
+ if (server) singletonImports.push(`import __fsServer from ${JSON.stringify(server.path)};`);
849
+ if (studio) singletonImports.push(`import __fsStudio from ${JSON.stringify(studio.path)};`);
850
+ if (singletonImports.length > 0) {
851
+ lines.push(...singletonImports);
852
+ lines.push(``);
853
+ }
854
+ const wfCodegen = workflows.length > 0 ? generateFsWorkflowsCodegen(workflows) : void 0;
855
+ if (wfCodegen) {
856
+ for (const line of wfCodegen.importLines) lines.push(line);
857
+ lines.push(``);
858
+ }
859
+ const entryExprs = [];
860
+ for (let i = 0; i < agents.length; i++) {
861
+ const agent = agents[i];
862
+ const expr = await emitAgentEntry(agent, `${i}`, agent.name, lines);
863
+ entryExprs.push(expr);
864
+ }
865
+ if (standalone) {
866
+ lines.push(``);
867
+ lines.push(`const __mastra = new Mastra({});`);
868
+ } else {
869
+ lines.push(``);
870
+ lines.push(`const __mastra = __userEntry.mastra;`);
871
+ }
872
+ lines.push(``);
873
+ lines.push(`const __fsAgentEntries = [`);
874
+ for (const expr of entryExprs) lines.push(` ${expr},`);
875
+ lines.push(`];`);
876
+ lines.push(``);
877
+ if (logger) {
878
+ lines.push(`if (__mastra && typeof __mastra.__registerFsLogger === 'function') {`);
879
+ lines.push(` __mastra.__registerFsLogger(__fsLogger);`);
880
+ lines.push(`}`);
881
+ lines.push(``);
882
+ }
883
+ if (storage) {
884
+ lines.push(`if (__mastra && typeof __mastra.__registerFsStorage === 'function') {`);
885
+ lines.push(` __mastra.__registerFsStorage(__fsStorage);`);
886
+ lines.push(`}`);
887
+ lines.push(``);
888
+ }
889
+ if (observability) {
890
+ lines.push(`if (__mastra && typeof __mastra.__registerFsObservability === 'function') {`);
891
+ lines.push(` __mastra.__registerFsObservability(__fsObservability);`);
892
+ lines.push(`}`);
893
+ lines.push(``);
894
+ }
895
+ if (server) {
896
+ lines.push(`if (__mastra && typeof __mastra.__registerFsServer === 'function') {`);
897
+ lines.push(` __mastra.__registerFsServer(__fsServer);`);
898
+ lines.push(`}`);
899
+ lines.push(``);
900
+ }
901
+ if (studio) {
902
+ lines.push(`if (__mastra && typeof __mastra.__registerFsStudio === 'function') {`);
903
+ lines.push(` __mastra.__registerFsStudio(__fsStudio);`);
904
+ lines.push(`}`);
905
+ lines.push(``);
906
+ }
907
+ lines.push(`const __fsAgents = Object.create(null);`);
908
+ lines.push(`for (const __entry of __fsAgentEntries) {`);
909
+ lines.push(` __fsAgents[__entry.name] = assembleAgentFromFsEntry(__entry, {`);
910
+ lines.push(` onWarn: msg => __mastra?.getLogger?.()?.warn?.(msg) ?? console.warn(msg),`);
911
+ lines.push(` });`);
912
+ lines.push(`}`);
913
+ lines.push(``);
914
+ lines.push(`if (__mastra && typeof __mastra.__registerFsAgents === 'function') {`);
915
+ lines.push(` __mastra.__registerFsAgents(__fsAgents);`);
916
+ lines.push(`}`);
917
+ if (wfCodegen) {
918
+ lines.push(``);
919
+ for (const line of wfCodegen.registrationLines) lines.push(line);
920
+ }
921
+ lines.push(``);
922
+ lines.push(`export const mastra = __mastra;`);
923
+ return lines.join("\n");
924
+ }
925
+ /**
926
+ * Generate the workflow-registration lines to splice into the generated wrapper
927
+ * module. Emits import statements for each discovered workflow module and a
928
+ * registration block that calls `__registerFsWorkflows` on the user's mastra.
929
+ *
930
+ * Returns `{ importLines, registrationLines }` so the caller can place them at
931
+ * the correct positions in the wrapper source.
932
+ */
933
+ function generateFsWorkflowsCodegen(workflows) {
934
+ const importLines = [];
935
+ const registrationLines = [];
936
+ for (let i = 0; i < workflows.length; i++) {
937
+ const wf = workflows[i];
938
+ const ident = sanitizeIdentifier(wf.key, "workflow", `${i}`);
939
+ importLines.push(`import ${ident} from ${JSON.stringify(wf.path)};`);
940
+ }
941
+ registrationLines.push(`const __fsWorkflows = Object.create(null);`);
942
+ for (let i = 0; i < workflows.length; i++) {
943
+ const wf = workflows[i];
944
+ const ident = sanitizeIdentifier(wf.key, "workflow", `${i}`);
945
+ registrationLines.push(`__fsWorkflows[${JSON.stringify(wf.key)}] = ${ident};`);
946
+ }
947
+ registrationLines.push(``);
948
+ registrationLines.push(`if (__mastra && typeof __mastra.__registerFsWorkflows === 'function') {`);
949
+ registrationLines.push(` __mastra.__registerFsWorkflows(__fsWorkflows);`);
950
+ registrationLines.push(`}`);
951
+ return {
952
+ importLines,
953
+ registrationLines
954
+ };
955
+ }
956
+ //#endregion
957
+ //#region src/build/fs-routing/prepare.ts
958
+ /**
959
+ * Discover fs-routed agents under `<mastraDir>/agents/*`, workflows under
960
+ * `<mastraDir>/workflows/`, and singleton config files (e.g. `storage.ts`,
961
+ * `observability.ts`, `logger.ts`, `server.ts`, `studio.ts`).
962
+ * When any are found, generate a wrapper entry module that registers them onto
963
+ * the user's mastra instance. Returns the entry the bundler should use plus
964
+ * extra tool glob paths so `agents/*\/tools` are bundled.
965
+ *
966
+ * This does NOT write the wrapper to disk; call {@link writeFsAgentsEntry} with
967
+ * the result after `bundler.prepare()` so the generated file is not wiped when
968
+ * the output directory is emptied.
969
+ *
970
+ * When `entryFile` is `undefined` (no `index.ts`/`index.js`) and fs-routed
971
+ * primitives are found, a standalone Mastra instance is auto-constructed from
972
+ * them — no user code required.
973
+ *
974
+ * When no fs-routed primitives are present the original entry is returned
975
+ * unchanged, so existing code-only projects are completely unaffected.
976
+ */
977
+ async function prepareFsAgentsEntry(mastraDir, entryFile, outputDirectory) {
978
+ const [agents, workflows, storage, observability, logger, server, studio] = await Promise.all([
979
+ discoverFsAgents(mastraDir),
980
+ discoverFsWorkflows(mastraDir),
981
+ discoverFsSingleton(mastraDir, "storage"),
982
+ discoverFsSingleton(mastraDir, "observability"),
983
+ discoverFsSingleton(mastraDir, "logger"),
984
+ discoverFsSingleton(mastraDir, "server"),
985
+ discoverFsSingleton(mastraDir, "studio")
986
+ ]);
987
+ const standalone = entryFile === void 0;
988
+ const hasFsPrimitives = agents.length > 0 || workflows.length > 0 || !!storage || !!observability || !!logger || !!server || !!studio;
989
+ if (!hasFsPrimitives && entryFile !== void 0) return {
990
+ entryFile,
991
+ standalone: false,
992
+ toolPaths: [],
993
+ agentCount: 0,
994
+ workflowCount: 0,
995
+ hasStorage: false,
996
+ hasObservability: false,
997
+ hasLogger: false,
998
+ hasServer: false,
999
+ hasStudio: false
1000
+ };
1001
+ if (!hasFsPrimitives && standalone) throw new Error("No index.ts and no file-based primitives found. Create src/mastra/index.ts with a Mastra instance, or add file-based agents/workflows/storage.");
1002
+ const moduleSource = await generateFsAgentsModule(entryFile ? require_utils.slash(entryFile) : void 0, agents, {
1003
+ workflows,
1004
+ storage,
1005
+ observability,
1006
+ logger,
1007
+ server,
1008
+ studio
1009
+ });
1010
+ const generatedEntry = (0, path.join)(outputDirectory, ".mastra-fs-agents-entry.mjs");
1011
+ const normalizedMastraDir = require_utils.slash(mastraDir);
1012
+ return {
1013
+ entryFile: generatedEntry,
1014
+ standalone,
1015
+ toolPaths: agents.length > 0 ? [
1016
+ path.posix.join(normalizedMastraDir, "agents/*/tools/**/*.{js,ts}"),
1017
+ `!${path.posix.join(normalizedMastraDir, "agents/*/tools/**/*.{test,spec}.{js,ts}")}`,
1018
+ `!${path.posix.join(normalizedMastraDir, "agents/*/tools/**/__tests__/**")}`
1019
+ ] : [],
1020
+ agentCount: agents.length,
1021
+ workflowCount: workflows.length,
1022
+ hasStorage: !!storage,
1023
+ hasObservability: !!observability,
1024
+ hasLogger: !!logger,
1025
+ hasServer: !!server,
1026
+ hasStudio: !!studio,
1027
+ moduleSource
1028
+ };
1029
+ }
1030
+ /**
1031
+ * Write the generated fs-agents wrapper produced by {@link prepareFsAgentsEntry}
1032
+ * to its `entryFile`. No-op when there are no fs-routed agents. Call this AFTER
1033
+ * `bundler.prepare()` (which empties the output directory) so the wrapper
1034
+ * survives for the bundler/watcher to read.
1035
+ */
1036
+ async function writeFsAgentsEntry(result) {
1037
+ if (!result.moduleSource) return;
1038
+ await (0, fs_promises.mkdir)((0, path.dirname)(result.entryFile), { recursive: true });
1039
+ await (0, fs_promises.writeFile)(result.entryFile, result.moduleSource, "utf-8");
1040
+ }
1041
+ //#endregion
1042
+ //#region src/build/fs-routing/mirror.ts
1043
+ /**
1044
+ * Skip symlinks when copying workspace seeds. A symlink under
1045
+ * `agents/<name>/workspace/` could point outside the workspace and be preserved
1046
+ * in the bundle, letting the agent read arbitrary files at runtime. We copy only
1047
+ * regular files and directories.
1048
+ */
1049
+ async function rejectSymlinks(source) {
1050
+ return !(await (0, fs_promises.lstat)(source)).isSymbolicLink();
1051
+ }
1052
+ async function mirrorAgentSeeds(agent, workspaceName, bundleDir, mirrored) {
1053
+ if (agent.workspaceSeedDir) {
1054
+ const destination = (0, path.join)(bundleDir, "workspace", ...workspaceName.split("/"));
1055
+ await (0, fs_promises.mkdir)(destination, { recursive: true });
1056
+ await (0, fs_promises.cp)(agent.workspaceSeedDir, destination, {
1057
+ recursive: true,
1058
+ filter: rejectSymlinks
1059
+ });
1060
+ mirrored.push(workspaceName);
1061
+ }
1062
+ for (const child of agent.subagents ?? []) await mirrorAgentSeeds(child, `${workspaceName}/${child.name}`, bundleDir, mirrored);
1063
+ }
1064
+ /**
1065
+ * Mirror authored `agents/<name>/workspace/**` seed files into the bundled
1066
+ * output so each fs-routed agent starts with them on disk (Eve parity). Files
1067
+ * are copied to `<bundleDir>/workspace/<name>`, which is exactly where the
1068
+ * generated entry roots each agent's default workspace at runtime (resolved
1069
+ * relative to the bundled module via `import.meta.url`). Declared subagents
1070
+ * mirror to the nested `<bundleDir>/workspace/<parent>/<child>` path.
1071
+ *
1072
+ * Must run AFTER the bundle step, since bundling recreates the output dir.
1073
+ *
1074
+ * @param mastraDir The user's `src/mastra` directory (source of seeds).
1075
+ * @param bundleDir The final bundle directory (e.g. `<outputDirectory>/output`).
1076
+ * @returns the workspace names whose seeds were mirrored (`<parent>/<child>` for subagents).
1077
+ */
1078
+ async function mirrorFsAgentWorkspaces(mastraDir, bundleDir) {
1079
+ const agents = await discoverFsAgents(mastraDir);
1080
+ const mirrored = [];
1081
+ for (const agent of agents) await mirrorAgentSeeds(agent, agent.name, bundleDir, mirrored);
1082
+ return mirrored;
1083
+ }
1084
+ //#endregion
1085
+ Object.defineProperty(exports, "analyzeEntryProjectType", {
1086
+ enumerable: true,
1087
+ get: function() {
1088
+ return analyzeEntryProjectType;
1089
+ }
1090
+ });
1091
+ Object.defineProperty(exports, "createWatcher", {
1092
+ enumerable: true,
1093
+ get: function() {
1094
+ return createWatcher;
1095
+ }
1096
+ });
1097
+ Object.defineProperty(exports, "discoverFsAgents", {
1098
+ enumerable: true,
1099
+ get: function() {
1100
+ return discoverFsAgents;
1101
+ }
1102
+ });
1103
+ Object.defineProperty(exports, "discoverFsSingleton", {
1104
+ enumerable: true,
1105
+ get: function() {
1106
+ return discoverFsSingleton;
1107
+ }
1108
+ });
1109
+ Object.defineProperty(exports, "discoverFsWorkflows", {
1110
+ enumerable: true,
1111
+ get: function() {
1112
+ return discoverFsWorkflows;
1113
+ }
1114
+ });
1115
+ Object.defineProperty(exports, "generateFsAgentsModule", {
1116
+ enumerable: true,
1117
+ get: function() {
1118
+ return generateFsAgentsModule;
1119
+ }
1120
+ });
1121
+ Object.defineProperty(exports, "generateFsWorkflowsCodegen", {
1122
+ enumerable: true,
1123
+ get: function() {
1124
+ return generateFsWorkflowsCodegen;
1125
+ }
1126
+ });
1127
+ Object.defineProperty(exports, "getInputOptions", {
1128
+ enumerable: true,
1129
+ get: function() {
1130
+ return getInputOptions;
1131
+ }
1132
+ });
1133
+ Object.defineProperty(exports, "getServerOptions", {
1134
+ enumerable: true,
1135
+ get: function() {
1136
+ return getServerOptions;
1137
+ }
1138
+ });
1139
+ Object.defineProperty(exports, "mirrorFsAgentWorkspaces", {
1140
+ enumerable: true,
1141
+ get: function() {
1142
+ return mirrorFsAgentWorkspaces;
1143
+ }
1144
+ });
1145
+ Object.defineProperty(exports, "prepareFsAgentsEntry", {
1146
+ enumerable: true,
1147
+ get: function() {
1148
+ return prepareFsAgentsEntry;
1149
+ }
1150
+ });
1151
+ Object.defineProperty(exports, "writeFsAgentsEntry", {
1152
+ enumerable: true,
1153
+ get: function() {
1154
+ return writeFsAgentsEntry;
1155
+ }
1156
+ });
1157
+
1158
+ //# sourceMappingURL=build-YV8-9zZy.cjs.map