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