@mastra/deployer 1.54.0-alpha.0 → 1.54.0-alpha.2

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 (211) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/analyze-C2q7jxbN.js +1308 -0
  3. package/dist/analyze-C2q7jxbN.js.map +1 -0
  4. package/dist/analyze-DhDZW9TS.cjs +1318 -0
  5. package/dist/analyze-DhDZW9TS.cjs.map +1 -0
  6. package/dist/arktype-aI7TBD0R-BsgjPZ4a.cjs +8 -0
  7. package/dist/arktype-aI7TBD0R-BsgjPZ4a.cjs.map +1 -0
  8. package/dist/arktype-aI7TBD0R-_UZl-wsH.js +8 -0
  9. package/dist/arktype-aI7TBD0R-_UZl-wsH.js.map +1 -0
  10. package/dist/build/analyze/constants.d.ts.map +1 -1
  11. package/dist/build/analyze.cjs +3 -12
  12. package/dist/build/analyze.js +2 -3
  13. package/dist/build/bundler.cjs +6 -24
  14. package/dist/build/bundler.js +2 -3
  15. package/dist/build/index.cjs +29 -101
  16. package/dist/build/index.js +7 -8
  17. package/dist/build-De4AZhfJ.cjs +908 -0
  18. package/dist/build-De4AZhfJ.cjs.map +1 -0
  19. package/dist/build-KCOeHd4N.js +834 -0
  20. package/dist/build-KCOeHd4N.js.map +1 -0
  21. package/dist/bundler/index.cjs +318 -13
  22. package/dist/bundler/index.cjs.map +1 -1
  23. package/dist/bundler/index.js +314 -2
  24. package/dist/bundler/index.js.map +1 -1
  25. package/dist/bundler-BqrDXofn.cjs +792 -0
  26. package/dist/bundler-BqrDXofn.cjs.map +1 -0
  27. package/dist/bundler-D86rFu2J.js +705 -0
  28. package/dist/bundler-D86rFu2J.js.map +1 -0
  29. package/dist/bundlerOptions-aFsEi86t.js +180 -0
  30. package/dist/bundlerOptions-aFsEi86t.js.map +1 -0
  31. package/dist/bundlerOptions-rBmtSyGe.cjs +194 -0
  32. package/dist/bundlerOptions-rBmtSyGe.cjs.map +1 -0
  33. package/dist/core-D0wEgdn3.cjs +790 -0
  34. package/dist/core-D0wEgdn3.cjs.map +1 -0
  35. package/dist/core-DF65PJXc.js +790 -0
  36. package/dist/core-DF65PJXc.js.map +1 -0
  37. package/dist/dist-BauTimif.js +532 -0
  38. package/dist/dist-BauTimif.js.map +1 -0
  39. package/dist/dist-Cv-mAEtr.cjs +532 -0
  40. package/dist/dist-Cv-mAEtr.cjs.map +1 -0
  41. package/dist/docs/SKILL.md +1 -1
  42. package/dist/docs/assets/SOURCE_MAP.json +2 -23
  43. package/dist/docs/references/docs-deployment-cloud-providers.md +1 -0
  44. package/dist/docs/references/docs-deployment-overview.md +1 -0
  45. package/dist/effect-QlVUlMFu-CwFnyS-g.cjs +14 -0
  46. package/dist/effect-QlVUlMFu-CwFnyS-g.cjs.map +1 -0
  47. package/dist/effect-QlVUlMFu-gyLQRCtQ.js +14 -0
  48. package/dist/effect-QlVUlMFu-gyLQRCtQ.js.map +1 -0
  49. package/dist/esm-BX-weMyC.js +4634 -0
  50. package/dist/esm-BX-weMyC.js.map +1 -0
  51. package/dist/esm-D81PZ_wJ.cjs +4634 -0
  52. package/dist/esm-D81PZ_wJ.cjs.map +1 -0
  53. package/dist/index-CLddUTqr-B5mOP6DC.cjs +145 -0
  54. package/dist/index-CLddUTqr-B5mOP6DC.cjs.map +1 -0
  55. package/dist/index-CLddUTqr-CkS6Y_hA.js +140 -0
  56. package/dist/index-CLddUTqr-CkS6Y_hA.js.map +1 -0
  57. package/dist/index.cjs +35 -48
  58. package/dist/index.cjs.map +1 -1
  59. package/dist/index.js +29 -30
  60. package/dist/index.js.map +1 -1
  61. package/dist/rolldown-runtime-emK7D4bc.cjs +35 -0
  62. package/dist/server/index.cjs +3141 -3874
  63. package/dist/server/index.cjs.map +1 -1
  64. package/dist/server/index.d.ts.map +1 -1
  65. package/dist/server/index.js +3131 -3842
  66. package/dist/server/index.js.map +1 -1
  67. package/dist/server/types.d.ts +1 -0
  68. package/dist/server/types.d.ts.map +1 -1
  69. package/dist/services/index.cjs +5 -20
  70. package/dist/services/index.js +2 -3
  71. package/dist/services-BxYMLS9-.cjs +430 -0
  72. package/dist/services-BxYMLS9-.cjs.map +1 -0
  73. package/dist/services-CLi56qqe.js +391 -0
  74. package/dist/services-CLi56qqe.js.map +1 -0
  75. package/dist/sury-CWZTCd75-B85M6878.js +14 -0
  76. package/dist/sury-CWZTCd75-B85M6878.js.map +1 -0
  77. package/dist/sury-CWZTCd75-DTj5HlK_.cjs +14 -0
  78. package/dist/sury-CWZTCd75-DTj5HlK_.cjs.map +1 -0
  79. package/dist/typebox-Dei93FPO-BeuT13_G.cjs +8 -0
  80. package/dist/typebox-Dei93FPO-BeuT13_G.cjs.map +1 -0
  81. package/dist/typebox-Dei93FPO-DovwMlVl.js +8 -0
  82. package/dist/typebox-Dei93FPO-DovwMlVl.js.map +1 -0
  83. package/dist/utils-FVOUvj-I.js +190 -0
  84. package/dist/utils-FVOUvj-I.js.map +1 -0
  85. package/dist/utils-O98BGdnP.cjs +267 -0
  86. package/dist/utils-O98BGdnP.cjs.map +1 -0
  87. package/dist/valibot--1zFm7rT-BqJHja5B.cjs +14 -0
  88. package/dist/valibot--1zFm7rT-BqJHja5B.cjs.map +1 -0
  89. package/dist/valibot--1zFm7rT-Y4Fhea0w.js +14 -0
  90. package/dist/valibot--1zFm7rT-Y4Fhea0w.js.map +1 -0
  91. package/dist/validator/custom-resolver.cjs +71 -73
  92. package/dist/validator/custom-resolver.cjs.map +1 -1
  93. package/dist/validator/custom-resolver.js +70 -71
  94. package/dist/validator/custom-resolver.js.map +1 -1
  95. package/dist/validator/loader.cjs +6 -7
  96. package/dist/validator/loader.cjs.map +1 -1
  97. package/dist/validator/loader.js +8 -4
  98. package/dist/validator/loader.js.map +1 -1
  99. package/dist/zod-Bwrt9trS-2JL6_UI_.cjs +23 -0
  100. package/dist/zod-Bwrt9trS-2JL6_UI_.cjs.map +1 -0
  101. package/dist/zod-Bwrt9trS-rVHICsmp.js +23 -0
  102. package/dist/zod-Bwrt9trS-rVHICsmp.js.map +1 -0
  103. package/package.json +7 -7
  104. package/dist/arktype-aI7TBD0R-K3QZAVE2.js +0 -8
  105. package/dist/arktype-aI7TBD0R-K3QZAVE2.js.map +0 -1
  106. package/dist/arktype-aI7TBD0R-WK5AZZMC.cjs +0 -10
  107. package/dist/arktype-aI7TBD0R-WK5AZZMC.cjs.map +0 -1
  108. package/dist/build/analyze.cjs.map +0 -1
  109. package/dist/build/analyze.js.map +0 -1
  110. package/dist/build/bundler.cjs.map +0 -1
  111. package/dist/build/bundler.js.map +0 -1
  112. package/dist/build/index.cjs.map +0 -1
  113. package/dist/build/index.js.map +0 -1
  114. package/dist/chunk-36AWZH7Z.cjs +0 -252
  115. package/dist/chunk-36AWZH7Z.cjs.map +0 -1
  116. package/dist/chunk-3XIMK24X.cjs +0 -765
  117. package/dist/chunk-3XIMK24X.cjs.map +0 -1
  118. package/dist/chunk-46M65MQG.cjs +0 -95
  119. package/dist/chunk-46M65MQG.cjs.map +0 -1
  120. package/dist/chunk-4ZNTNJ6T.js +0 -6
  121. package/dist/chunk-4ZNTNJ6T.js.map +0 -1
  122. package/dist/chunk-5PORNUPF.js +0 -739
  123. package/dist/chunk-5PORNUPF.js.map +0 -1
  124. package/dist/chunk-743HRNWT.cjs +0 -1546
  125. package/dist/chunk-743HRNWT.cjs.map +0 -1
  126. package/dist/chunk-AEQ7JHDB.cjs +0 -412
  127. package/dist/chunk-AEQ7JHDB.cjs.map +0 -1
  128. package/dist/chunk-E5SBYHQK.js +0 -244
  129. package/dist/chunk-E5SBYHQK.js.map +0 -1
  130. package/dist/chunk-FKKJQUGR.cjs +0 -497
  131. package/dist/chunk-FKKJQUGR.cjs.map +0 -1
  132. package/dist/chunk-FQHUOYYL.js +0 -1514
  133. package/dist/chunk-FQHUOYYL.js.map +0 -1
  134. package/dist/chunk-G7MIMGMX.js +0 -14
  135. package/dist/chunk-G7MIMGMX.js.map +0 -1
  136. package/dist/chunk-HZC3PTK2.cjs +0 -16
  137. package/dist/chunk-HZC3PTK2.cjs.map +0 -1
  138. package/dist/chunk-JZRFRUGM.cjs +0 -158
  139. package/dist/chunk-JZRFRUGM.cjs.map +0 -1
  140. package/dist/chunk-L45X3DJX.js +0 -385
  141. package/dist/chunk-L45X3DJX.js.map +0 -1
  142. package/dist/chunk-PC25XSK7.cjs +0 -8
  143. package/dist/chunk-PC25XSK7.cjs.map +0 -1
  144. package/dist/chunk-PZ5AY32C.js +0 -9
  145. package/dist/chunk-PZ5AY32C.js.map +0 -1
  146. package/dist/chunk-Q7SFCCGT.cjs +0 -11
  147. package/dist/chunk-Q7SFCCGT.cjs.map +0 -1
  148. package/dist/chunk-T4UT2QX7.js +0 -3
  149. package/dist/chunk-T4UT2QX7.js.map +0 -1
  150. package/dist/chunk-UBIDJOJA.js +0 -93
  151. package/dist/chunk-UBIDJOJA.js.map +0 -1
  152. package/dist/chunk-V3EKV6QB.cjs +0 -162
  153. package/dist/chunk-V3EKV6QB.cjs.map +0 -1
  154. package/dist/chunk-WHD2QQ3N.js +0 -783
  155. package/dist/chunk-WHD2QQ3N.js.map +0 -1
  156. package/dist/chunk-WP65JQAT.js +0 -144
  157. package/dist/chunk-WP65JQAT.js.map +0 -1
  158. package/dist/chunk-YO5OFXPN.cjs +0 -819
  159. package/dist/chunk-YO5OFXPN.cjs.map +0 -1
  160. package/dist/chunk-YUBKHO52.js +0 -465
  161. package/dist/chunk-YUBKHO52.js.map +0 -1
  162. package/dist/chunk-YWMYXUHX.cjs +0 -4
  163. package/dist/chunk-YWMYXUHX.cjs.map +0 -1
  164. package/dist/chunk-ZKZOVNT4.js +0 -159
  165. package/dist/chunk-ZKZOVNT4.js.map +0 -1
  166. package/dist/core-XIDAXLRB.js +0 -11866
  167. package/dist/core-XIDAXLRB.js.map +0 -1
  168. package/dist/core-XJNQ4AY6.cjs +0 -12141
  169. package/dist/core-XJNQ4AY6.cjs.map +0 -1
  170. package/dist/default-u_dwuiYb-HGUAHA6N.cjs +0 -9
  171. package/dist/default-u_dwuiYb-HGUAHA6N.cjs.map +0 -1
  172. package/dist/default-u_dwuiYb-MVPTVDCE.js +0 -3
  173. package/dist/default-u_dwuiYb-MVPTVDCE.js.map +0 -1
  174. package/dist/dist-UEE5OLII.cjs +0 -521
  175. package/dist/dist-UEE5OLII.cjs.map +0 -1
  176. package/dist/dist-X75F2Q36.js +0 -515
  177. package/dist/dist-X75F2Q36.js.map +0 -1
  178. package/dist/effect-QlVUlMFu-QNLZLGWO.js +0 -15
  179. package/dist/effect-QlVUlMFu-QNLZLGWO.js.map +0 -1
  180. package/dist/effect-QlVUlMFu-XUD6EH23.cjs +0 -17
  181. package/dist/effect-QlVUlMFu-XUD6EH23.cjs.map +0 -1
  182. package/dist/esm-DFCHSIJZ.cjs +0 -1589
  183. package/dist/esm-DFCHSIJZ.cjs.map +0 -1
  184. package/dist/esm-PXGQ5WB4.js +0 -1542
  185. package/dist/esm-PXGQ5WB4.js.map +0 -1
  186. package/dist/services/index.cjs.map +0 -1
  187. package/dist/services/index.js.map +0 -1
  188. package/dist/sury-CWZTCd75-3KQQJ22C.cjs +0 -17
  189. package/dist/sury-CWZTCd75-3KQQJ22C.cjs.map +0 -1
  190. package/dist/sury-CWZTCd75-DZQHKAZF.js +0 -15
  191. package/dist/sury-CWZTCd75-DZQHKAZF.js.map +0 -1
  192. package/dist/typebox-Dei93FPO-GOYJ5OUT.js +0 -8
  193. package/dist/typebox-Dei93FPO-GOYJ5OUT.js.map +0 -1
  194. package/dist/typebox-Dei93FPO-M7J7E57W.cjs +0 -10
  195. package/dist/typebox-Dei93FPO-M7J7E57W.cjs.map +0 -1
  196. package/dist/valibot--1zFm7rT-NVM3G3TI.cjs +0 -17
  197. package/dist/valibot--1zFm7rT-NVM3G3TI.cjs.map +0 -1
  198. package/dist/valibot--1zFm7rT-ZVGQI7WV.js +0 -15
  199. package/dist/valibot--1zFm7rT-ZVGQI7WV.js.map +0 -1
  200. package/dist/valibot-D_HTw1Gn-UCPEGDL7.cjs +0 -45
  201. package/dist/valibot-D_HTw1Gn-UCPEGDL7.cjs.map +0 -1
  202. package/dist/valibot-D_HTw1Gn-XPR4F6VS.js +0 -43
  203. package/dist/valibot-D_HTw1Gn-XPR4F6VS.js.map +0 -1
  204. package/dist/zod-Bwrt9trS-GN7ZXBMN.js +0 -29
  205. package/dist/zod-Bwrt9trS-GN7ZXBMN.js.map +0 -1
  206. package/dist/zod-Bwrt9trS-OVKARV6W.cjs +0 -31
  207. package/dist/zod-Bwrt9trS-OVKARV6W.cjs.map +0 -1
  208. package/dist/zod-DSgpEGAE-E7YZZ7VC.js +0 -37
  209. package/dist/zod-DSgpEGAE-E7YZZ7VC.js.map +0 -1
  210. package/dist/zod-DSgpEGAE-UNQNGL2W.cjs +0 -39
  211. package/dist/zod-DSgpEGAE-UNQNGL2W.cjs.map +0 -1
@@ -0,0 +1,908 @@
1
+ const require_rolldown_runtime = require("./rolldown-runtime-emK7D4bc.cjs");
2
+ const require_analyze = require("./analyze-DhDZW9TS.cjs");
3
+ const require_utils = require("./utils-O98BGdnP.cjs");
4
+ require("./services-BxYMLS9-.cjs");
5
+ const require_bundler = require("./bundler-BqrDXofn.cjs");
6
+ const require_bundlerOptions = require("./bundlerOptions-rBmtSyGe.cjs");
7
+ let fs_promises = require("fs/promises");
8
+ let path = require("path");
9
+ let empathic_package = require("empathic/package");
10
+ empathic_package = require_rolldown_runtime.__toESM(empathic_package, 1);
11
+ let _babel_core = require("@babel/core");
12
+ let rollup = require("rollup");
13
+ let _mastra_core_logger = require("@mastra/core/logger");
14
+ let _mastra_core_agent = require("@mastra/core/agent");
15
+ let gray_matter = require("gray-matter");
16
+ gray_matter = require_rolldown_runtime.__toESM(gray_matter, 1);
17
+ //#region src/build/watcher.ts
18
+ async function getInputOptions(entryFile, platform, env, { sourcemap = false, bundlerOptions = {
19
+ enableSourcemap: false,
20
+ enableEsmShim: true,
21
+ externals: true
22
+ }, analysisEntries = [entryFile] } = {}) {
23
+ const closestPkgJson = empathic_package.up({ cwd: (0, path.dirname)(entryFile) });
24
+ const projectRoot = closestPkgJson ? (0, path.dirname)(require_utils.slash(closestPkgJson)) : require_utils.slash(process.cwd());
25
+ const { workspaceMap, workspaceRoot } = await require_analyze.getWorkspaceInformation({ mastraEntryFile: entryFile });
26
+ const analyzeEntryResult = await require_analyze.analyzeBundle(analysisEntries, entryFile, {
27
+ outputDir: path.posix.join(process.cwd(), ".mastra", ".build"),
28
+ projectRoot: workspaceRoot || process.cwd(),
29
+ platform,
30
+ isDev: true,
31
+ bundlerOptions
32
+ }, _mastra_core_logger.noopLogger);
33
+ const deps = /* @__PURE__ */ new Map();
34
+ for (const [dep, metadata] of analyzeEntryResult.dependencies.entries()) {
35
+ const pkgName = require_utils.getPackageName(dep);
36
+ if (pkgName && workspaceMap.has(pkgName)) deps.set(dep, metadata);
37
+ }
38
+ const inputOptions = await require_bundler.getInputOptions(entryFile, {
39
+ dependencies: deps,
40
+ externalDependencies: /* @__PURE__ */ new Map(),
41
+ workspaceMap
42
+ }, platform, env, {
43
+ sourcemap,
44
+ isDev: true,
45
+ workspaceRoot,
46
+ projectRoot,
47
+ externalsPreset: bundlerOptions?.externals === true
48
+ });
49
+ if (Array.isArray(inputOptions.plugins)) {
50
+ const plugins = [];
51
+ inputOptions.plugins.forEach((plugin) => {
52
+ if (plugin?.name === "node-resolve") return;
53
+ if (plugin?.name === "tsconfig-paths") {
54
+ plugins.push(require_bundler.tsConfigPaths({ localResolve: true }));
55
+ return;
56
+ }
57
+ plugins.push(plugin);
58
+ });
59
+ inputOptions.plugins = plugins;
60
+ inputOptions.plugins.push(require_analyze.aliasHono());
61
+ inputOptions.plugins.push(require_bundler.nodeModulesExtensionResolver());
62
+ }
63
+ return inputOptions;
64
+ }
65
+ async function createWatcher(inputOptions, outputOptions) {
66
+ return await (0, rollup.watch)({
67
+ ...inputOptions,
68
+ output: {
69
+ ...outputOptions,
70
+ format: "esm",
71
+ entryFileNames: "[name].mjs",
72
+ chunkFileNames: "[name].mjs"
73
+ }
74
+ });
75
+ }
76
+ //#endregion
77
+ //#region src/build/analyzeEntryProjectType.ts
78
+ /**
79
+ * Lightweight entry analysis that returns the detected project type by running
80
+ * only the Babel check-config-export plugin on the Mastra entry file. This is
81
+ * intentionally cheaper than `analyzeBundle` and is used by the CLI before
82
+ * `prepare()` clears `.mastra` to decide whether Factory-specific assets
83
+ * should be copied.
84
+ *
85
+ * Returns `'factory'` when the entry imports `MastraFactory` and
86
+ * constructs it, or `undefined` for ordinary Mastra projects.
87
+ */
88
+ async function analyzeEntryProjectType(mastraEntry) {
89
+ const code = await (0, fs_promises.readFile)(mastraEntry, "utf-8");
90
+ const result = { hasValidConfig: false };
91
+ await (0, _babel_core.transformAsync)(code, {
92
+ filename: mastraEntry,
93
+ presets: [{}.resolve("@babel/preset-typescript")],
94
+ plugins: [() => require_analyze.checkConfigExport(result)]
95
+ });
96
+ return result.projectType;
97
+ }
98
+ //#endregion
99
+ //#region src/build/serverOptions.ts
100
+ async function getServerOptions(entryFile, outputDir, logger) {
101
+ const result = await require_bundlerOptions.extractMastraOption("server", entryFile, outputDir, logger);
102
+ if (!result) return null;
103
+ return result.getConfig();
104
+ }
105
+ //#endregion
106
+ //#region src/build/fs-routing/discover.ts
107
+ const CONFIG_BASENAMES = ["config.ts", "config.js"];
108
+ const WORKSPACE_BASENAMES = ["workspace.ts", "workspace.js"];
109
+ const MEMORY_BASENAMES = ["memory.ts", "memory.js"];
110
+ const INSTRUCTIONS_BASENAME = "instructions.md";
111
+ const TOOL_EXTENSIONS = [".ts", ".js"];
112
+ const SKILL_MODULE_EXTENSIONS = [".ts", ".js"];
113
+ const SKILL_MD_BASENAME = "SKILL.md";
114
+ /**
115
+ * Presence check that does NOT follow symlinks. Returns `false` for symlinks
116
+ * (and broken links) so a symlinked `config.ts`/`instructions.md`/`workspace.ts`/
117
+ * `memory.ts` is never inlined or imported into the generated bundle.
118
+ */
119
+ async function exists(path$1) {
120
+ try {
121
+ return !(await (0, fs_promises.lstat)(path$1)).isSymbolicLink();
122
+ } catch {
123
+ return false;
124
+ }
125
+ }
126
+ /**
127
+ * Returns the slash-normalized path when `path` is a real directory (not a
128
+ * symlink). Symlinked directories are rejected to prevent the build from
129
+ * following links out of the project tree during discovery.
130
+ */
131
+ async function realDirectory(path$2) {
132
+ try {
133
+ const info = await (0, fs_promises.lstat)(path$2);
134
+ if (info.isDirectory() && !info.isSymbolicLink()) return require_utils.slash(path$2);
135
+ } catch {}
136
+ }
137
+ async function directoryExists(path$3) {
138
+ return realDirectory(path$3);
139
+ }
140
+ async function firstExisting(dir, basenames) {
141
+ for (const basename of basenames) {
142
+ const candidate = (0, path.join)(dir, basename);
143
+ if (await exists(candidate)) return require_utils.slash(candidate);
144
+ }
145
+ }
146
+ function isTestFile(basename) {
147
+ return /\.(test|spec)\.(ts|js)$/.test(basename);
148
+ }
149
+ function toolKey(basename) {
150
+ return basename.replace(/\.(ts|js)$/, "");
151
+ }
152
+ /**
153
+ * Discover default-exporting `.ts`/`.js` modules directly under `dir`, returning
154
+ * `{ key, path }` entries in stable (sorted) order. Test files, symlinks, and
155
+ * subdirectories are skipped: a symlinked module could point anywhere on the
156
+ * build machine and be embedded into generated import code. Shared by the
157
+ * `tools/` and `scorers/` scanners.
158
+ */
159
+ async function discoverModuleDir(dir) {
160
+ if (!await exists(dir)) return [];
161
+ let entries;
162
+ try {
163
+ entries = await (0, fs_promises.readdir)(dir);
164
+ } catch {
165
+ return [];
166
+ }
167
+ const modules = [];
168
+ for (const basename of entries.sort()) {
169
+ if (isTestFile(basename)) continue;
170
+ if (!TOOL_EXTENSIONS.some((ext) => basename.endsWith(ext))) continue;
171
+ const path$4 = (0, path.join)(dir, basename);
172
+ const stats = await (0, fs_promises.lstat)(path$4);
173
+ if (stats.isSymbolicLink() || stats.isDirectory()) continue;
174
+ modules.push({
175
+ key: toolKey(basename),
176
+ path: require_utils.slash(path$4)
177
+ });
178
+ }
179
+ return modules;
180
+ }
181
+ async function discoverTools(toolsDir) {
182
+ return discoverModuleDir(toolsDir);
183
+ }
184
+ async function discoverProcessors(processorsDir) {
185
+ const result = {
186
+ input: [],
187
+ output: []
188
+ };
189
+ for (const type of ["input", "output"]) {
190
+ const typeDir = (0, path.join)(processorsDir, type);
191
+ if (!await exists(typeDir)) continue;
192
+ let entries;
193
+ try {
194
+ entries = await (0, fs_promises.readdir)(typeDir);
195
+ } catch {
196
+ continue;
197
+ }
198
+ for (const basename of entries.sort()) {
199
+ if (isTestFile(basename)) continue;
200
+ if (!TOOL_EXTENSIONS.some((ext) => basename.endsWith(ext))) continue;
201
+ const path$5 = (0, path.join)(typeDir, basename);
202
+ const stats = await (0, fs_promises.lstat)(path$5);
203
+ if (stats.isSymbolicLink() || stats.isDirectory()) continue;
204
+ result[type].push({
205
+ key: toolKey(basename),
206
+ path: require_utils.slash(path$5)
207
+ });
208
+ }
209
+ }
210
+ return result;
211
+ }
212
+ async function readReferences(referencesDir) {
213
+ if (!await exists(referencesDir)) return {};
214
+ const references = {};
215
+ let entries;
216
+ try {
217
+ entries = await (0, fs_promises.readdir)(referencesDir);
218
+ } catch {
219
+ return {};
220
+ }
221
+ for (const basename of entries.sort()) {
222
+ const path$6 = (0, path.join)(referencesDir, basename);
223
+ const stats = await (0, fs_promises.lstat)(path$6);
224
+ if (stats.isSymbolicLink() || stats.isDirectory()) continue;
225
+ references[basename] = await (0, fs_promises.readFile)(path$6, "utf-8");
226
+ }
227
+ return references;
228
+ }
229
+ async function parsePackagedSkill(skillMdPath, fallbackName, references = {}) {
230
+ const parsed = (0, gray_matter.default)(await (0, fs_promises.readFile)(skillMdPath, "utf-8"));
231
+ const frontmatter = parsed.data;
232
+ const name = frontmatter.name ?? fallbackName;
233
+ const description = frontmatter.description;
234
+ 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.`);
235
+ return {
236
+ kind: "packaged",
237
+ name,
238
+ description,
239
+ instructions: parsed.content.trim(),
240
+ references
241
+ };
242
+ }
243
+ function skillModuleName(basename) {
244
+ return basename.replace(/\.(ts|js)$/, "");
245
+ }
246
+ async function discoverSkills(skillsDir) {
247
+ if (!await exists(skillsDir)) return [];
248
+ let entries;
249
+ try {
250
+ entries = await (0, fs_promises.readdir)(skillsDir);
251
+ } catch {
252
+ return [];
253
+ }
254
+ const skills = [];
255
+ for (const basename of entries.sort()) {
256
+ if (isTestFile(basename)) continue;
257
+ const path$7 = (0, path.join)(skillsDir, basename);
258
+ const stats = await (0, fs_promises.lstat)(path$7);
259
+ if (stats.isSymbolicLink()) continue;
260
+ if (stats.isDirectory()) {
261
+ const skillMd = (0, path.join)(path$7, SKILL_MD_BASENAME);
262
+ if (await exists(skillMd)) {
263
+ const references = await readReferences((0, path.join)(path$7, "references"));
264
+ skills.push(await parsePackagedSkill(skillMd, skillModuleName(basename), references));
265
+ }
266
+ continue;
267
+ }
268
+ if (SKILL_MODULE_EXTENSIONS.some((ext) => basename.endsWith(ext))) {
269
+ skills.push({
270
+ kind: "module",
271
+ path: require_utils.slash(path$7)
272
+ });
273
+ continue;
274
+ }
275
+ if (basename.endsWith(".md")) {
276
+ const skill = await parsePackagedSkill(path$7, basename.replace(/\.md$/, ""));
277
+ skills.push(skill);
278
+ }
279
+ }
280
+ return skills;
281
+ }
282
+ /**
283
+ * Discover a single agent directory: its `config`/`instructions`/`workspace`
284
+ * files plus `tools/`, `skills/`, and declared `subagents/`. Returns
285
+ * `undefined` when `dir` is not an agent directory (no `config.(ts|js)` and no
286
+ * `instructions.md`).
287
+ *
288
+ * `depth` is the subagent nesting level (`0` for top-level agents). Discovery
289
+ * recurses into `subagents/` until `MAX_FS_SUBAGENT_DEPTH`; deeper directories
290
+ * are ignored with a warning.
291
+ */
292
+ async function discoverAgentDir(dir, name, depth, onWarn) {
293
+ const configPath = await firstExisting(dir, CONFIG_BASENAMES);
294
+ const instructionsPath = await exists((0, path.join)(dir, INSTRUCTIONS_BASENAME)) ? require_utils.slash((0, path.join)(dir, INSTRUCTIONS_BASENAME)) : void 0;
295
+ if (!configPath && !instructionsPath) return;
296
+ const workspacePath = await firstExisting(dir, WORKSPACE_BASENAMES);
297
+ const memoryPath = await firstExisting(dir, MEMORY_BASENAMES);
298
+ const workspaceSeedDir = await directoryExists((0, path.join)(dir, "workspace"));
299
+ const tools = await discoverTools((0, path.join)(dir, "tools"));
300
+ const processors = await discoverProcessors((0, path.join)(dir, "processors"));
301
+ const scorers = await discoverModuleDir((0, path.join)(dir, "scorers"));
302
+ const skills = await discoverSkills((0, path.join)(dir, "skills"));
303
+ const subagents = await discoverSubagents(dir, depth, onWarn);
304
+ return {
305
+ name,
306
+ dir: require_utils.slash(dir),
307
+ configPath,
308
+ instructionsPath,
309
+ workspacePath,
310
+ memoryPath,
311
+ workspaceSeedDir,
312
+ tools,
313
+ inputProcessors: processors.input,
314
+ outputProcessors: processors.output,
315
+ scorers,
316
+ skills,
317
+ subagents
318
+ };
319
+ }
320
+ /**
321
+ * Discover declared subagents under `<dir>/subagents/*`. `parentDepth` is the
322
+ * parent agent's nesting level (`0` for top-level agents). Discovery recurses
323
+ * until `MAX_FS_SUBAGENT_DEPTH` levels of subagents; a `subagents/` directory
324
+ * that would exceed the cap is skipped with a warning.
325
+ */
326
+ async function discoverSubagents(parentDir, parentDepth, onWarn) {
327
+ const subagentsDir = (0, path.join)(parentDir, "subagents");
328
+ if (!await exists(subagentsDir)) return [];
329
+ if (parentDepth >= _mastra_core_agent.MAX_FS_SUBAGENT_DEPTH) {
330
+ 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.`);
331
+ return [];
332
+ }
333
+ let entries;
334
+ try {
335
+ entries = await (0, fs_promises.readdir)(subagentsDir);
336
+ } catch {
337
+ return [];
338
+ }
339
+ const subagents = [];
340
+ for (const name of entries.sort()) {
341
+ const dir = (0, path.join)(subagentsDir, name);
342
+ if (!await realDirectory(dir)) continue;
343
+ const child = await discoverAgentDir(dir, name, parentDepth + 1, onWarn);
344
+ if (child) subagents.push(child);
345
+ }
346
+ return subagents;
347
+ }
348
+ /**
349
+ * Scan `<mastraDir>/agents/*` for file-system routed agents. A directory is
350
+ * treated as an agent only when it contains a `config.(ts|js)` or an
351
+ * `instructions.md`; other directories are ignored. Each agent may declare
352
+ * `subagents/` up to `MAX_FS_SUBAGENT_DEPTH` levels deep. Returns descriptors
353
+ * with absolute, slash-normalized paths ready for codegen. Performs no module
354
+ * evaluation — only filesystem inspection.
355
+ */
356
+ async function discoverFsAgents(mastraDir, onWarn) {
357
+ const agentsDir = (0, path.join)(mastraDir, "agents");
358
+ if (!await exists(agentsDir)) return [];
359
+ let entries;
360
+ try {
361
+ entries = await (0, fs_promises.readdir)(agentsDir);
362
+ } catch {
363
+ return [];
364
+ }
365
+ const discovered = [];
366
+ for (const name of entries.sort()) {
367
+ const dir = (0, path.join)(agentsDir, name);
368
+ if (!await realDirectory(dir)) continue;
369
+ const agent = await discoverAgentDir(dir, name, 0, onWarn);
370
+ if (agent) discovered.push(agent);
371
+ }
372
+ return discovered;
373
+ }
374
+ /**
375
+ * Scan `<mastraDir>/workflows/` for file-system routed workflow modules. Only
376
+ * files whose source contains an `export default` are treated as fs-routed
377
+ * workflows — this convention distinguishes them from workflow files that are
378
+ * manually imported and registered programmatically. Returns descriptors with
379
+ * absolute, slash-normalized paths ready for codegen. Performs no module
380
+ * evaluation — only filesystem and source-text inspection.
381
+ */
382
+ async function discoverFsWorkflows(mastraDir) {
383
+ const workflowsDir = (0, path.join)(mastraDir, "workflows");
384
+ if (!await exists(workflowsDir)) return [];
385
+ let entries;
386
+ try {
387
+ entries = await (0, fs_promises.readdir)(workflowsDir);
388
+ } catch {
389
+ return [];
390
+ }
391
+ const discovered = [];
392
+ for (const basename of entries.sort()) {
393
+ if (isTestFile(basename)) continue;
394
+ if (!TOOL_EXTENSIONS.some((ext) => basename.endsWith(ext))) continue;
395
+ const path$8 = (0, path.join)(workflowsDir, basename);
396
+ const stats = await (0, fs_promises.lstat)(path$8);
397
+ if (stats.isSymbolicLink() || stats.isDirectory()) continue;
398
+ const source = await (0, fs_promises.readFile)(path$8, "utf-8");
399
+ if (!/\bexport\s+default\b/.test(source)) continue;
400
+ discovered.push({
401
+ key: toolKey(basename),
402
+ path: require_utils.slash(path$8)
403
+ });
404
+ }
405
+ return discovered;
406
+ }
407
+ const SINGLETON_EXTENSIONS = [
408
+ ".ts",
409
+ ".js",
410
+ ".mts",
411
+ ".mjs"
412
+ ];
413
+ /** Safe singleton identifier: no path separators, `..`, or other traversal. */
414
+ const SINGLETON_NAME_PATTERN = /^[a-zA-Z0-9_-]+$/;
415
+ /**
416
+ * Check for a singleton config file (e.g. `storage.ts`, `storage.js`) directly
417
+ * under `<mastraDir>`. Returns the first matching file path or `undefined`.
418
+ * Symlinks are rejected for security.
419
+ *
420
+ * Convention: only files with `export default` are fs-routed singletons. Files
421
+ * using named exports are assumed to be manually imported into the user's
422
+ * `index.ts`, so they are ignored to remain backward-compatible with existing
423
+ * project structures.
424
+ *
425
+ * `name` must be a bare identifier — path separators and traversal sequences are
426
+ * rejected so the lookup can never escape `<mastraDir>`.
427
+ */
428
+ async function discoverFsSingleton(mastraDir, name) {
429
+ if (!SINGLETON_NAME_PATTERN.test(name)) throw new Error(`Invalid fs-singleton name ${JSON.stringify(name)}: expected a bare identifier.`);
430
+ for (const ext of SINGLETON_EXTENSIONS) {
431
+ const candidate = (0, path.join)(mastraDir, `${name}${ext}`);
432
+ try {
433
+ const stats = await (0, fs_promises.lstat)(candidate);
434
+ if (!stats.isFile() || stats.isSymbolicLink()) continue;
435
+ const source = await (0, fs_promises.readFile)(candidate, "utf-8");
436
+ if (!/\bexport\s+default\b/.test(source)) continue;
437
+ return { path: require_utils.slash(candidate) };
438
+ } catch {}
439
+ }
440
+ }
441
+ //#endregion
442
+ //#region src/build/fs-routing/codegen.ts
443
+ function sanitizeIdentifier(name, prefix, index) {
444
+ return `${prefix}_${index}_${name.replace(/[^a-zA-Z0-9_$]/g, "_")}`;
445
+ }
446
+ /**
447
+ * Emit the imports for a single discovered agent into `lines` and return the
448
+ * source of its `assembleAgentFromFsEntry` entry object (the `{ name, config,
449
+ * ... }` argument). `idPath` is a dot-free, unique path index (e.g. `0` for the
450
+ * first top-level agent, `0_1` for its second subagent) used to keep generated
451
+ * identifiers unique across the parent/child tree. `workspaceName` is the
452
+ * slash-joined workspace key (`<parent>/<child>` for subagents) so seed files
453
+ * don't collide. Discovered subagents are emitted recursively as a nested
454
+ * `subagents: [...]` field (discovery already enforces the depth cap).
455
+ */
456
+ async function emitAgentEntry(agent, idPath, workspaceName, lines) {
457
+ const configIdent = sanitizeIdentifier(agent.name, "config", idPath);
458
+ const toolIdents = [];
459
+ if (agent.configPath) lines.push(`import ${configIdent} from ${JSON.stringify(agent.configPath)};`);
460
+ let workspaceIdent;
461
+ if (agent.workspacePath) {
462
+ workspaceIdent = sanitizeIdentifier(`${agent.name}_workspace`, "workspace", idPath);
463
+ lines.push(`import ${workspaceIdent} from ${JSON.stringify(agent.workspacePath)};`);
464
+ }
465
+ let memoryIdent;
466
+ if (agent.memoryPath) {
467
+ memoryIdent = sanitizeIdentifier(`${agent.name}_memory`, "memory", idPath);
468
+ lines.push(`import ${memoryIdent} from ${JSON.stringify(agent.memoryPath)};`);
469
+ }
470
+ for (let t = 0; t < agent.tools.length; t++) {
471
+ const tool = agent.tools[t];
472
+ const ident = sanitizeIdentifier(`${agent.name}_${tool.key}`, "tool", `${idPath}_${t}`);
473
+ lines.push(`import ${ident} from ${JSON.stringify(tool.path)};`);
474
+ toolIdents.push({
475
+ key: tool.key,
476
+ ident
477
+ });
478
+ }
479
+ const inputProcessorIdents = [];
480
+ for (let p = 0; p < agent.inputProcessors.length; p++) {
481
+ const proc = agent.inputProcessors[p];
482
+ const ident = sanitizeIdentifier(`${agent.name}_inputProc_${proc.key}`, "proc", `${idPath}_ip${p}`);
483
+ lines.push(`import ${ident} from ${JSON.stringify(proc.path)};`);
484
+ inputProcessorIdents.push(ident);
485
+ }
486
+ const outputProcessorIdents = [];
487
+ for (let p = 0; p < agent.outputProcessors.length; p++) {
488
+ const proc = agent.outputProcessors[p];
489
+ const ident = sanitizeIdentifier(`${agent.name}_outputProc_${proc.key}`, "proc", `${idPath}_op${p}`);
490
+ lines.push(`import ${ident} from ${JSON.stringify(proc.path)};`);
491
+ outputProcessorIdents.push(ident);
492
+ }
493
+ const scorerIdents = [];
494
+ for (let s = 0; s < agent.scorers.length; s++) {
495
+ const scorer = agent.scorers[s];
496
+ const ident = sanitizeIdentifier(`${agent.name}_scorer_${scorer.key}`, "scorer", `${idPath}_${s}`);
497
+ lines.push(`import ${ident} from ${JSON.stringify(scorer.path)};`);
498
+ scorerIdents.push({
499
+ key: scorer.key,
500
+ ident
501
+ });
502
+ }
503
+ const skillExprs = [];
504
+ const agentSkills = agent.skills ?? [];
505
+ for (let s = 0; s < agentSkills.length; s++) {
506
+ const skill = agentSkills[s];
507
+ if (skill.kind === "module") {
508
+ const ident = sanitizeIdentifier(`${agent.name}_skill`, "skill", `${idPath}_${s}`);
509
+ lines.push(`import ${ident} from ${JSON.stringify(skill.path)};`);
510
+ skillExprs.push(ident);
511
+ } else {
512
+ const referenceFields = Object.entries(skill.references).map(([key, value]) => `${JSON.stringify(key)}: ${JSON.stringify(value)}`);
513
+ const skillFields = [
514
+ `name: ${JSON.stringify(skill.name)}`,
515
+ `description: ${JSON.stringify(skill.description)}`,
516
+ `instructions: ${JSON.stringify(skill.instructions)}`
517
+ ];
518
+ if (referenceFields.length > 0) skillFields.push(`references: { ${referenceFields.join(", ")} }`);
519
+ skillExprs.push(`__createSkill({ ${skillFields.join(", ")} })`);
520
+ }
521
+ }
522
+ let instructionsMd;
523
+ if (agent.instructionsPath) instructionsMd = await (0, fs_promises.readFile)(agent.instructionsPath, "utf-8");
524
+ const subagentExprs = [];
525
+ for (let c = 0; c < agent.subagents.length; c++) {
526
+ const child = agent.subagents[c];
527
+ const childExpr = await emitAgentEntry(child, `${idPath}_${c}`, `${workspaceName}/${child.name}`, lines);
528
+ subagentExprs.push(childExpr);
529
+ }
530
+ const entryFields = [`name: ${JSON.stringify(agent.name)}`];
531
+ if (agent.configPath) entryFields.push(`config: ${configIdent}`);
532
+ if (instructionsMd !== void 0) entryFields.push(`instructionsMd: ${JSON.stringify(instructionsMd)}`);
533
+ if (toolIdents.length > 0) {
534
+ const toolEntries = toolIdents.map(({ key, ident }) => `{ key: ${JSON.stringify(key)}, tool: ${ident} }`);
535
+ entryFields.push(`tools: [${toolEntries.join(", ")}]`);
536
+ }
537
+ if (skillExprs.length > 0) entryFields.push(`skills: [${skillExprs.join(", ")}]`);
538
+ if (inputProcessorIdents.length > 0) entryFields.push(`inputProcessors: [${inputProcessorIdents.join(", ")}]`);
539
+ if (outputProcessorIdents.length > 0) entryFields.push(`outputProcessors: [${outputProcessorIdents.join(", ")}]`);
540
+ if (scorerIdents.length > 0) {
541
+ const scorerEntries = scorerIdents.map(({ key, ident }) => `{ key: ${JSON.stringify(key)}, scorer: ${ident} }`);
542
+ entryFields.push(`scorers: [${scorerEntries.join(", ")}]`);
543
+ }
544
+ if (subagentExprs.length > 0) entryFields.push(`subagents: [${subagentExprs.join(", ")}]`);
545
+ if (workspaceIdent) entryFields.push(`workspace: ${workspaceIdent}`);
546
+ if (memoryIdent) entryFields.push(`memory: ${memoryIdent}`);
547
+ entryFields.push(`defaultWorkspaceBasePath: __workspaceBasePath(${JSON.stringify(workspaceName)})`);
548
+ return `{ ${entryFields.join(", ")} }`;
549
+ }
550
+ /**
551
+ * Generate the source of a wrapper module that:
552
+ * 1. imports the user's real Mastra entry,
553
+ * 2. imports each discovered `config.ts`, `tools/*.ts`, `skills/*.ts`
554
+ * (`createSkill(...)` modules), `workspace.ts`, and `memory.ts`, inlining
555
+ * packaged `SKILL.md` skills,
556
+ * 3. assembles `Agent` instances via `assembleAgentFromFsEntry`, wiring any
557
+ * declared `subagents/` into the parent (nested up to `MAX_FS_SUBAGENT_DEPTH`),
558
+ * 4. registers them onto the user's `mastra` instance (code-registered agents
559
+ * win on name collisions), and
560
+ * 5. re-exports everything from the user's entry so this module is a drop-in
561
+ * replacement for the original `#mastra` target.
562
+ *
563
+ * `instructions.md` is read into the generated wrapper. In dev, the CLI watcher
564
+ * regenerates that wrapper when the markdown file changes.
565
+ *
566
+ * @param userEntry slash-normalized absolute path to the user's mastra entry.
567
+ * @param agents discovered fs-routed agents (absolute, slash-normalized paths).
568
+ */
569
+ async function generateFsAgentsModule(userEntry, agents, options) {
570
+ const workflows = options?.workflows ?? [];
571
+ const storage = options?.storage;
572
+ const observability = options?.observability;
573
+ const logger = options?.logger;
574
+ const server = options?.server;
575
+ const studio = options?.studio;
576
+ const standalone = userEntry === void 0;
577
+ const lines = [];
578
+ const hasInlineSkills = (function check(list) {
579
+ return list.some((a) => (a.skills ?? []).some((s) => s.kind === "packaged") || check(a.subagents ?? []));
580
+ })(agents);
581
+ lines.push(`import { assembleAgentFromFsEntry } from '@mastra/core/agent';`);
582
+ if (hasInlineSkills) lines.push(`import { createSkill as __createSkill } from '@mastra/core/skills';`);
583
+ if (standalone) lines.push(`import { Mastra } from '@mastra/core';`);
584
+ lines.push(`import { fileURLToPath as __fileURLToPath } from 'node:url';`);
585
+ lines.push(`import { dirname as __dirname, join as __join } from 'node:path';`);
586
+ if (userEntry) {
587
+ lines.push(`import * as __userEntry from ${JSON.stringify(userEntry)};`);
588
+ lines.push(`export * from ${JSON.stringify(userEntry)};`);
589
+ }
590
+ lines.push(``);
591
+ lines.push(`const __bundleDir = __dirname(__fileURLToPath(import.meta.url));`);
592
+ lines.push(`const __workspaceBasePath = name => __join(__bundleDir, 'workspace', ...name.split('/'));`);
593
+ lines.push(``);
594
+ const singletonImports = [];
595
+ if (storage) singletonImports.push(`import __fsStorage from ${JSON.stringify(storage.path)};`);
596
+ if (observability) singletonImports.push(`import __fsObservability from ${JSON.stringify(observability.path)};`);
597
+ if (logger) singletonImports.push(`import __fsLogger from ${JSON.stringify(logger.path)};`);
598
+ if (server) singletonImports.push(`import __fsServer from ${JSON.stringify(server.path)};`);
599
+ if (studio) singletonImports.push(`import __fsStudio from ${JSON.stringify(studio.path)};`);
600
+ if (singletonImports.length > 0) {
601
+ lines.push(...singletonImports);
602
+ lines.push(``);
603
+ }
604
+ const wfCodegen = workflows.length > 0 ? generateFsWorkflowsCodegen(workflows) : void 0;
605
+ if (wfCodegen) {
606
+ for (const line of wfCodegen.importLines) lines.push(line);
607
+ lines.push(``);
608
+ }
609
+ const entryExprs = [];
610
+ for (let i = 0; i < agents.length; i++) {
611
+ const agent = agents[i];
612
+ const expr = await emitAgentEntry(agent, `${i}`, agent.name, lines);
613
+ entryExprs.push(expr);
614
+ }
615
+ if (standalone) {
616
+ lines.push(``);
617
+ lines.push(`const __mastra = new Mastra({});`);
618
+ } else {
619
+ lines.push(``);
620
+ lines.push(`const __mastra = __userEntry.mastra;`);
621
+ }
622
+ lines.push(``);
623
+ lines.push(`const __fsAgentEntries = [`);
624
+ for (const expr of entryExprs) lines.push(` ${expr},`);
625
+ lines.push(`];`);
626
+ lines.push(``);
627
+ lines.push(`const __fsAgents = Object.create(null);`);
628
+ lines.push(`for (const __entry of __fsAgentEntries) {`);
629
+ lines.push(` __fsAgents[__entry.name] = assembleAgentFromFsEntry(__entry, {`);
630
+ lines.push(` onWarn: msg => __mastra?.getLogger?.()?.warn?.(msg) ?? console.warn(msg),`);
631
+ lines.push(` });`);
632
+ lines.push(`}`);
633
+ lines.push(``);
634
+ if (logger) {
635
+ lines.push(`if (__mastra && typeof __mastra.__registerFsLogger === 'function') {`);
636
+ lines.push(` __mastra.__registerFsLogger(__fsLogger);`);
637
+ lines.push(`}`);
638
+ lines.push(``);
639
+ }
640
+ if (storage) {
641
+ lines.push(`if (__mastra && typeof __mastra.__registerFsStorage === 'function') {`);
642
+ lines.push(` __mastra.__registerFsStorage(__fsStorage);`);
643
+ lines.push(`}`);
644
+ lines.push(``);
645
+ }
646
+ if (observability) {
647
+ lines.push(`if (__mastra && typeof __mastra.__registerFsObservability === 'function') {`);
648
+ lines.push(` __mastra.__registerFsObservability(__fsObservability);`);
649
+ lines.push(`}`);
650
+ lines.push(``);
651
+ }
652
+ if (server) {
653
+ lines.push(`if (__mastra && typeof __mastra.__registerFsServer === 'function') {`);
654
+ lines.push(` __mastra.__registerFsServer(__fsServer);`);
655
+ lines.push(`}`);
656
+ lines.push(``);
657
+ }
658
+ if (studio) {
659
+ lines.push(`if (__mastra && typeof __mastra.__registerFsStudio === 'function') {`);
660
+ lines.push(` __mastra.__registerFsStudio(__fsStudio);`);
661
+ lines.push(`}`);
662
+ lines.push(``);
663
+ }
664
+ lines.push(`if (__mastra && typeof __mastra.__registerFsAgents === 'function') {`);
665
+ lines.push(` __mastra.__registerFsAgents(__fsAgents);`);
666
+ lines.push(`}`);
667
+ if (wfCodegen) {
668
+ lines.push(``);
669
+ for (const line of wfCodegen.registrationLines) lines.push(line);
670
+ }
671
+ lines.push(``);
672
+ lines.push(`export const mastra = __mastra;`);
673
+ return lines.join("\n");
674
+ }
675
+ /**
676
+ * Generate the workflow-registration lines to splice into the generated wrapper
677
+ * module. Emits import statements for each discovered workflow module and a
678
+ * registration block that calls `__registerFsWorkflows` on the user's mastra.
679
+ *
680
+ * Returns `{ importLines, registrationLines }` so the caller can place them at
681
+ * the correct positions in the wrapper source.
682
+ */
683
+ function generateFsWorkflowsCodegen(workflows) {
684
+ const importLines = [];
685
+ const registrationLines = [];
686
+ for (let i = 0; i < workflows.length; i++) {
687
+ const wf = workflows[i];
688
+ const ident = sanitizeIdentifier(wf.key, "workflow", `${i}`);
689
+ importLines.push(`import ${ident} from ${JSON.stringify(wf.path)};`);
690
+ }
691
+ registrationLines.push(`const __fsWorkflows = Object.create(null);`);
692
+ for (let i = 0; i < workflows.length; i++) {
693
+ const wf = workflows[i];
694
+ const ident = sanitizeIdentifier(wf.key, "workflow", `${i}`);
695
+ registrationLines.push(`__fsWorkflows[${JSON.stringify(wf.key)}] = ${ident};`);
696
+ }
697
+ registrationLines.push(``);
698
+ registrationLines.push(`if (__mastra && typeof __mastra.__registerFsWorkflows === 'function') {`);
699
+ registrationLines.push(` __mastra.__registerFsWorkflows(__fsWorkflows);`);
700
+ registrationLines.push(`}`);
701
+ return {
702
+ importLines,
703
+ registrationLines
704
+ };
705
+ }
706
+ //#endregion
707
+ //#region src/build/fs-routing/prepare.ts
708
+ /**
709
+ * Discover fs-routed agents under `<mastraDir>/agents/*`, workflows under
710
+ * `<mastraDir>/workflows/`, and singleton config files (e.g. `storage.ts`,
711
+ * `observability.ts`, `logger.ts`, `server.ts`, `studio.ts`).
712
+ * When any are found, generate a wrapper entry module that registers them onto
713
+ * the user's mastra instance. Returns the entry the bundler should use plus
714
+ * extra tool glob paths so `agents/*\/tools` are bundled.
715
+ *
716
+ * This does NOT write the wrapper to disk; call {@link writeFsAgentsEntry} with
717
+ * the result after `bundler.prepare()` so the generated file is not wiped when
718
+ * the output directory is emptied.
719
+ *
720
+ * When `entryFile` is `undefined` (no `index.ts`/`index.js`) and fs-routed
721
+ * primitives are found, a standalone Mastra instance is auto-constructed from
722
+ * them — no user code required.
723
+ *
724
+ * When no fs-routed primitives are present the original entry is returned
725
+ * unchanged, so existing code-only projects are completely unaffected.
726
+ */
727
+ async function prepareFsAgentsEntry(mastraDir, entryFile, outputDirectory) {
728
+ const [agents, workflows, storage, observability, logger, server, studio] = await Promise.all([
729
+ discoverFsAgents(mastraDir),
730
+ discoverFsWorkflows(mastraDir),
731
+ discoverFsSingleton(mastraDir, "storage"),
732
+ discoverFsSingleton(mastraDir, "observability"),
733
+ discoverFsSingleton(mastraDir, "logger"),
734
+ discoverFsSingleton(mastraDir, "server"),
735
+ discoverFsSingleton(mastraDir, "studio")
736
+ ]);
737
+ const standalone = entryFile === void 0;
738
+ const hasFsPrimitives = agents.length > 0 || workflows.length > 0 || !!storage || !!observability || !!logger || !!server || !!studio;
739
+ if (!hasFsPrimitives && entryFile !== void 0) return {
740
+ entryFile,
741
+ standalone: false,
742
+ toolPaths: [],
743
+ agentCount: 0,
744
+ workflowCount: 0,
745
+ hasStorage: false,
746
+ hasObservability: false,
747
+ hasLogger: false,
748
+ hasServer: false,
749
+ hasStudio: false
750
+ };
751
+ 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.");
752
+ const moduleSource = await generateFsAgentsModule(entryFile ? require_utils.slash(entryFile) : void 0, agents, {
753
+ workflows,
754
+ storage,
755
+ observability,
756
+ logger,
757
+ server,
758
+ studio
759
+ });
760
+ const generatedEntry = (0, path.join)(outputDirectory, ".mastra-fs-agents-entry.mjs");
761
+ const normalizedMastraDir = require_utils.slash(mastraDir);
762
+ return {
763
+ entryFile: generatedEntry,
764
+ standalone,
765
+ toolPaths: agents.length > 0 ? [
766
+ path.posix.join(normalizedMastraDir, "agents/*/tools/**/*.{js,ts}"),
767
+ `!${path.posix.join(normalizedMastraDir, "agents/*/tools/**/*.{test,spec}.{js,ts}")}`,
768
+ `!${path.posix.join(normalizedMastraDir, "agents/*/tools/**/__tests__/**")}`
769
+ ] : [],
770
+ agentCount: agents.length,
771
+ workflowCount: workflows.length,
772
+ hasStorage: !!storage,
773
+ hasObservability: !!observability,
774
+ hasLogger: !!logger,
775
+ hasServer: !!server,
776
+ hasStudio: !!studio,
777
+ moduleSource
778
+ };
779
+ }
780
+ /**
781
+ * Write the generated fs-agents wrapper produced by {@link prepareFsAgentsEntry}
782
+ * to its `entryFile`. No-op when there are no fs-routed agents. Call this AFTER
783
+ * `bundler.prepare()` (which empties the output directory) so the wrapper
784
+ * survives for the bundler/watcher to read.
785
+ */
786
+ async function writeFsAgentsEntry(result) {
787
+ if (!result.moduleSource) return;
788
+ await (0, fs_promises.mkdir)((0, path.dirname)(result.entryFile), { recursive: true });
789
+ await (0, fs_promises.writeFile)(result.entryFile, result.moduleSource, "utf-8");
790
+ }
791
+ //#endregion
792
+ //#region src/build/fs-routing/mirror.ts
793
+ /**
794
+ * Skip symlinks when copying workspace seeds. A symlink under
795
+ * `agents/<name>/workspace/` could point outside the workspace and be preserved
796
+ * in the bundle, letting the agent read arbitrary files at runtime. We copy only
797
+ * regular files and directories.
798
+ */
799
+ async function rejectSymlinks(source) {
800
+ return !(await (0, fs_promises.lstat)(source)).isSymbolicLink();
801
+ }
802
+ async function mirrorAgentSeeds(agent, workspaceName, bundleDir, mirrored) {
803
+ if (agent.workspaceSeedDir) {
804
+ const destination = (0, path.join)(bundleDir, "workspace", ...workspaceName.split("/"));
805
+ await (0, fs_promises.mkdir)(destination, { recursive: true });
806
+ await (0, fs_promises.cp)(agent.workspaceSeedDir, destination, {
807
+ recursive: true,
808
+ filter: rejectSymlinks
809
+ });
810
+ mirrored.push(workspaceName);
811
+ }
812
+ for (const child of agent.subagents ?? []) await mirrorAgentSeeds(child, `${workspaceName}/${child.name}`, bundleDir, mirrored);
813
+ }
814
+ /**
815
+ * Mirror authored `agents/<name>/workspace/**` seed files into the bundled
816
+ * output so each fs-routed agent starts with them on disk (Eve parity). Files
817
+ * are copied to `<bundleDir>/workspace/<name>`, which is exactly where the
818
+ * generated entry roots each agent's default workspace at runtime (resolved
819
+ * relative to the bundled module via `import.meta.url`). Declared subagents
820
+ * mirror to the nested `<bundleDir>/workspace/<parent>/<child>` path.
821
+ *
822
+ * Must run AFTER the bundle step, since bundling recreates the output dir.
823
+ *
824
+ * @param mastraDir The user's `src/mastra` directory (source of seeds).
825
+ * @param bundleDir The final bundle directory (e.g. `<outputDirectory>/output`).
826
+ * @returns the workspace names whose seeds were mirrored (`<parent>/<child>` for subagents).
827
+ */
828
+ async function mirrorFsAgentWorkspaces(mastraDir, bundleDir) {
829
+ const agents = await discoverFsAgents(mastraDir);
830
+ const mirrored = [];
831
+ for (const agent of agents) await mirrorAgentSeeds(agent, agent.name, bundleDir, mirrored);
832
+ return mirrored;
833
+ }
834
+ //#endregion
835
+ Object.defineProperty(exports, "analyzeEntryProjectType", {
836
+ enumerable: true,
837
+ get: function() {
838
+ return analyzeEntryProjectType;
839
+ }
840
+ });
841
+ Object.defineProperty(exports, "createWatcher", {
842
+ enumerable: true,
843
+ get: function() {
844
+ return createWatcher;
845
+ }
846
+ });
847
+ Object.defineProperty(exports, "discoverFsAgents", {
848
+ enumerable: true,
849
+ get: function() {
850
+ return discoverFsAgents;
851
+ }
852
+ });
853
+ Object.defineProperty(exports, "discoverFsSingleton", {
854
+ enumerable: true,
855
+ get: function() {
856
+ return discoverFsSingleton;
857
+ }
858
+ });
859
+ Object.defineProperty(exports, "discoverFsWorkflows", {
860
+ enumerable: true,
861
+ get: function() {
862
+ return discoverFsWorkflows;
863
+ }
864
+ });
865
+ Object.defineProperty(exports, "generateFsAgentsModule", {
866
+ enumerable: true,
867
+ get: function() {
868
+ return generateFsAgentsModule;
869
+ }
870
+ });
871
+ Object.defineProperty(exports, "generateFsWorkflowsCodegen", {
872
+ enumerable: true,
873
+ get: function() {
874
+ return generateFsWorkflowsCodegen;
875
+ }
876
+ });
877
+ Object.defineProperty(exports, "getInputOptions", {
878
+ enumerable: true,
879
+ get: function() {
880
+ return getInputOptions;
881
+ }
882
+ });
883
+ Object.defineProperty(exports, "getServerOptions", {
884
+ enumerable: true,
885
+ get: function() {
886
+ return getServerOptions;
887
+ }
888
+ });
889
+ Object.defineProperty(exports, "mirrorFsAgentWorkspaces", {
890
+ enumerable: true,
891
+ get: function() {
892
+ return mirrorFsAgentWorkspaces;
893
+ }
894
+ });
895
+ Object.defineProperty(exports, "prepareFsAgentsEntry", {
896
+ enumerable: true,
897
+ get: function() {
898
+ return prepareFsAgentsEntry;
899
+ }
900
+ });
901
+ Object.defineProperty(exports, "writeFsAgentsEntry", {
902
+ enumerable: true,
903
+ get: function() {
904
+ return writeFsAgentsEntry;
905
+ }
906
+ });
907
+
908
+ //# sourceMappingURL=build-De4AZhfJ.cjs.map