@mastra/deployer 1.58.0-alpha.1 → 1.58.0-alpha.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +158 -0
- package/dist/_types/@mastra_hono/dist/index.d.ts +24 -1
- package/dist/{analyze-D100622N.cjs → analyze-BIrkd7zx.cjs} +2 -2
- package/dist/{analyze-D100622N.cjs.map → analyze-BIrkd7zx.cjs.map} +1 -1
- package/dist/{analyze-7xxwhB5F.js → analyze-CNv6Qdaz.js} +2 -2
- package/dist/{analyze-7xxwhB5F.js.map → analyze-CNv6Qdaz.js.map} +1 -1
- package/dist/build/analyze.cjs +1 -1
- package/dist/build/analyze.js +1 -1
- package/dist/build/bundler.cjs +1 -1
- package/dist/build/bundler.d.ts +2 -1
- package/dist/build/bundler.d.ts.map +1 -1
- package/dist/build/bundler.js +1 -1
- package/dist/build/fs-routing/codegen.d.ts +5 -4
- package/dist/build/fs-routing/codegen.d.ts.map +1 -1
- package/dist/build/fs-routing/discover.d.ts +12 -5
- package/dist/build/fs-routing/discover.d.ts.map +1 -1
- package/dist/build/index.cjs +4 -4
- package/dist/build/index.js +4 -4
- package/dist/build/types.d.ts +11 -0
- package/dist/build/types.d.ts.map +1 -1
- package/dist/build/watcher.d.ts.map +1 -1
- package/dist/{build-33wIyA35.cjs → build-BERX35Pi.cjs} +30 -18
- package/dist/build-BERX35Pi.cjs.map +1 -0
- package/dist/{build-xd6t8qiR.js → build-kZfvpuh9.js} +30 -18
- package/dist/build-kZfvpuh9.js.map +1 -0
- package/dist/bundler/entries.d.ts +12 -0
- package/dist/bundler/entries.d.ts.map +1 -0
- package/dist/bundler/index.cjs +6 -506
- package/dist/bundler/index.d.ts +1 -1
- package/dist/bundler/index.d.ts.map +1 -1
- package/dist/bundler/index.js +1 -497
- package/dist/bundler-Ct1ToG6x.js +565 -0
- package/dist/bundler-Ct1ToG6x.js.map +1 -0
- package/dist/{bundler-u9WOUtpl.cjs → bundler-DCGtF4jP.cjs} +7 -3
- package/dist/{bundler-u9WOUtpl.cjs.map → bundler-DCGtF4jP.cjs.map} +1 -1
- package/dist/bundler-DLXwkS7b.cjs +598 -0
- package/dist/bundler-DLXwkS7b.cjs.map +1 -0
- package/dist/{bundler-U9F2---r.js → bundler-gff4vn1T.js} +8 -4
- package/dist/bundler-gff4vn1T.js.map +1 -0
- package/dist/{bundlerOptions-CYRir4LE.cjs → bundlerOptions-CjjAPZYp.cjs} +2 -2
- package/dist/{bundlerOptions-CYRir4LE.cjs.map → bundlerOptions-CjjAPZYp.cjs.map} +1 -1
- package/dist/{bundlerOptions-9DigsVhY.js → bundlerOptions-NMtZPD7p.js} +2 -2
- package/dist/{bundlerOptions-9DigsVhY.js.map → bundlerOptions-NMtZPD7p.js.map} +1 -1
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/assets/SOURCE_MAP.json +1 -1
- package/dist/index.cjs +4 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +3 -3
- package/dist/server/index.cjs +86 -7
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +87 -8
- package/dist/server/index.js.map +1 -1
- package/package.json +8 -8
- package/dist/build-33wIyA35.cjs.map +0 -1
- package/dist/build-xd6t8qiR.js.map +0 -1
- package/dist/bundler/index.cjs.map +0 -1
- package/dist/bundler/index.js.map +0 -1
- package/dist/bundler-U9F2---r.js.map +0 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mastra/deployer",
|
|
3
|
-
"version": "1.58.0-alpha.
|
|
3
|
+
"version": "1.58.0-alpha.13",
|
|
4
4
|
"description": "",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"files": [
|
|
@@ -113,7 +113,7 @@
|
|
|
113
113
|
"typescript-paths": "^1.5.2",
|
|
114
114
|
"ws": "^8.21.0",
|
|
115
115
|
"yaml": "^2.9.0",
|
|
116
|
-
"@mastra/server": "1.58.0-alpha.
|
|
116
|
+
"@mastra/server": "1.58.0-alpha.13"
|
|
117
117
|
},
|
|
118
118
|
"devDependencies": {
|
|
119
119
|
"@hono/node-server": "^2.0.0",
|
|
@@ -133,13 +133,13 @@
|
|
|
133
133
|
"typescript": "^6.0.3",
|
|
134
134
|
"vitest": "4.1.10",
|
|
135
135
|
"zod": "^4.4.3",
|
|
136
|
-
"@internal/types-builder": "0.0.96",
|
|
137
136
|
"@internal/lint": "0.0.121",
|
|
138
|
-
"@mastra/agent-browser": "0.5.0",
|
|
139
|
-
"@mastra/
|
|
140
|
-
"@mastra/
|
|
141
|
-
"@
|
|
142
|
-
"@mastra/
|
|
137
|
+
"@mastra/agent-browser": "0.5.1-alpha.0",
|
|
138
|
+
"@mastra/core": "1.58.0-alpha.13",
|
|
139
|
+
"@mastra/hono": "1.6.0-alpha.13",
|
|
140
|
+
"@internal/types-builder": "0.0.96",
|
|
141
|
+
"@mastra/server": "1.58.0-alpha.13",
|
|
142
|
+
"@mastra/mcp": "^1.16.0-alpha.2"
|
|
143
143
|
},
|
|
144
144
|
"peerDependencies": {
|
|
145
145
|
"@mastra/core": ">=1.50.0-0 <2.0.0-0"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"build-33wIyA35.cjs","names":["bundleExternals","slash","getPackageName","pkg","slash","getWorkspaceInformation","posix","analyzeBundle","noopLogger","getPackageName","getBundlerInputOptions","tsConfigPaths","aliasHono","nodeModulesExtensionResolver","checkConfigExport","extractMastraOption","path","slash","MAX_FS_SUBAGENT_DEPTH","slash","posix"],"sources":["../src/build/plugins/workspace-deps-watcher.ts","../src/build/watcher.ts","../src/build/analyzeEntryProjectType.ts","../src/build/serverOptions.ts","../src/build/fs-routing/discover.ts","../src/build/fs-routing/codegen.ts","../src/build/fs-routing/prepare.ts","../src/build/fs-routing/mirror.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { stat } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport type { Plugin } from 'rollup';\nimport { glob } from 'tinyglobby';\nimport type { WorkspacePackageInfo } from '../../bundler/workspaceDependencies';\nimport { bundleExternals } from '../analyze/bundleExternals';\nimport type { BundlerOptions, DependencyMetadata } from '../types';\nimport type { BundlerPlatform } from '../utils';\nimport { getCompiledDepCachePath, getPackageName, slash } from '../utils';\n\nconst SOURCE_GLOBS = ['**/*.{ts,tsx,js,jsx,mjs,cjs,json}'];\nconst SOURCE_IGNORE = ['**/node_modules/**', '**/.cache/**'];\n\nexport type WorkspaceDepsWatcherOptions = {\n depsToOptimize: Map<string, DependencyMetadata>;\n /**\n * Optimized dependency → relative cache file path (from analyzeBundle.dependencies).\n * Used to detect missing cache files that must be regenerated.\n */\n optimizedDependencyFiles: Map<string, string>;\n workspaceMap: Map<string, WorkspacePackageInfo>;\n workspaceRoot: string;\n outputDir: string;\n platform: BundlerPlatform;\n bundlerOptions?: Pick<BundlerOptions, 'externals' | 'enableSourcemap' | 'dynamicPackages'> | null;\n};\n\n/**\n * During `mastra dev`, workspace packages are pre-transpiled into\n * `<pkg>/node_modules/.cache/*.mjs` and marked external in the main Rollup\n * watch graph. This plugin:\n * 1. Watches the original workspace package sources so edits trigger rebuilds.\n * 2. Regenerates the optimized `.cache` outputs when those sources change (or\n * when cache files are missing) before the rebuild finishes — so a later\n * server restart loads fresh package code.\n */\nexport function workspaceDepsWatcher(options: WorkspaceDepsWatcherOptions): Plugin {\n const { depsToOptimize, optimizedDependencyFiles, workspaceMap, workspaceRoot, outputDir, platform, bundlerOptions } =\n options;\n\n let isFirstBuild = true;\n\n const usedPackageRoots = collectUsedPackageRoots(depsToOptimize, workspaceMap);\n const cachePaths = collectAbsoluteCachePaths(optimizedDependencyFiles, workspaceRoot);\n\n return {\n name: 'workspace-deps-watcher',\n async buildStart() {\n const sourceFiles = await discoverWorkspaceSourceFiles(usedPackageRoots);\n\n for (const file of sourceFiles) {\n this.addWatchFile(resolve(file));\n }\n\n // Initial optimize already ran in getWatcherInputOptions / analyzeBundle.\n if (isFirstBuild) {\n isFirstBuild = false;\n return;\n }\n\n const needsReoptimize = await isWorkspaceOutputStale(sourceFiles, cachePaths);\n\n if (!needsReoptimize) {\n return;\n }\n\n // bundleExternals may mutate the map when externalsPreset is true; copy first.\n const depsCopy = cloneDepsToOptimize(depsToOptimize);\n\n await bundleExternals(depsCopy, outputDir, {\n bundlerOptions: {\n ...bundlerOptions,\n externals: bundlerOptions?.externals ?? true,\n isDev: true,\n },\n projectRoot: workspaceRoot,\n workspaceRoot,\n workspaceMap,\n platform,\n });\n },\n };\n}\n\nfunction collectUsedPackageRoots(\n depsToOptimize: Map<string, DependencyMetadata>,\n workspaceMap: Map<string, WorkspacePackageInfo>,\n): string[] {\n const roots = new Set<string>();\n\n for (const [dep, metadata] of depsToOptimize.entries()) {\n if (!metadata.isWorkspace) {\n continue;\n }\n\n if (metadata.rootPath) {\n roots.add(slash(metadata.rootPath));\n continue;\n }\n\n const pkgName = getPackageName(dep);\n const location = pkgName ? workspaceMap.get(pkgName)?.location : undefined;\n if (location) {\n roots.add(slash(location));\n }\n }\n\n return Array.from(roots);\n}\n\nfunction collectAbsoluteCachePaths(optimizedDependencyFiles: Map<string, string>, workspaceRoot: string): string[] {\n return Array.from(optimizedDependencyFiles.values()).map(relativePath => resolve(workspaceRoot, relativePath));\n}\n\nasync function discoverWorkspaceSourceFiles(packageRoots: string[]): Promise<string[]> {\n if (packageRoots.length === 0) {\n return [];\n }\n\n const files = await Promise.all(\n packageRoots.map(root =>\n glob(SOURCE_GLOBS, {\n cwd: root,\n absolute: true,\n ignore: SOURCE_IGNORE,\n onlyFiles: true,\n }),\n ),\n );\n\n return files.flat();\n}\n\nasync function isCacheMissing(cachePaths: string[]): Promise<boolean> {\n for (const cachePath of cachePaths) {\n if (!existsSync(cachePath)) {\n return true;\n }\n }\n return false;\n}\n\nasync function isWorkspaceOutputStale(sourceFiles: string[], cachePaths: string[]): Promise<boolean> {\n if (await isCacheMissing(cachePaths)) {\n return true;\n }\n\n let cacheBaselineMs = 0;\n for (const cachePath of cachePaths) {\n try {\n const { mtimeMs } = await stat(cachePath);\n cacheBaselineMs = Math.max(cacheBaselineMs, mtimeMs);\n } catch {\n return true;\n }\n }\n\n for (const file of sourceFiles) {\n try {\n const { mtimeMs } = await stat(file);\n if (mtimeMs > cacheBaselineMs) {\n return true;\n }\n } catch {\n // File may have been deleted; treat as dirty so we re-optimize.\n return true;\n }\n }\n\n return false;\n}\n\nfunction cloneDepsToOptimize(deps: Map<string, DependencyMetadata>): Map<string, DependencyMetadata> {\n const copy = new Map<string, DependencyMetadata>();\n for (const [dep, metadata] of deps.entries()) {\n copy.set(dep, {\n ...metadata,\n exports: [...metadata.exports],\n });\n }\n return copy;\n}\n\n/**\n * On-disk cache entry path for a workspace dependency after optimization.\n * Naming matches createVirtualDependencies: dep.replaceAll('/', '__').\n */\nexport function getWorkspaceDepCacheEntryPath(rootPath: string, dep: string): string {\n const fileName = dep.replaceAll('/', '__');\n return `${getCompiledDepCachePath(rootPath, fileName)}.mjs`;\n}\n","import { dirname, posix } from 'node:path';\nimport { noopLogger } from '@mastra/core/logger';\nimport * as pkg from 'empathic/package';\nimport type { InputOptions, OutputOptions, Plugin } from 'rollup';\nimport { watch } from 'rollup';\nimport { getWorkspaceInformation } from '../bundler/workspaceDependencies';\nimport { analyzeBundle } from './analyze';\nimport { getInputOptions as getBundlerInputOptions } from './bundler';\nimport { aliasHono } from './plugins/hono-alias';\nimport { nodeModulesExtensionResolver } from './plugins/node-modules-extension-resolver';\nimport { tsConfigPaths } from './plugins/tsconfig-paths';\nimport { workspaceDepsWatcher } from './plugins/workspace-deps-watcher';\nimport type { BundlerOptions } from './types';\nimport { getPackageName, slash } from './utils';\nimport type { BundlerPlatform } from './utils';\n\nexport async function getInputOptions(\n entryFile: string,\n platform: BundlerPlatform,\n env?: Record<string, string>,\n {\n sourcemap = false,\n bundlerOptions = {\n enableSourcemap: false,\n enableEsmShim: true,\n externals: true,\n },\n analysisEntries = [entryFile],\n }: { sourcemap?: boolean; bundlerOptions?: BundlerOptions; analysisEntries?: string[] } = {},\n) {\n const closestPkgJson = pkg.up({ cwd: dirname(entryFile) });\n const projectRoot = closestPkgJson ? dirname(slash(closestPkgJson)) : slash(process.cwd());\n const { workspaceMap, workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile: entryFile });\n\n const outputDir = posix.join(process.cwd(), '.mastra', '.build');\n\n const analyzeEntryResult = await analyzeBundle(\n analysisEntries,\n entryFile,\n {\n outputDir,\n projectRoot: workspaceRoot || process.cwd(),\n platform,\n isDev: true,\n bundlerOptions,\n },\n noopLogger,\n );\n\n const deps = /* @__PURE__ */ new Map();\n for (const [dep, metadata] of analyzeEntryResult.dependencies.entries()) {\n const pkgName = getPackageName(dep);\n if (pkgName && workspaceMap.has(pkgName)) {\n deps.set(dep, metadata);\n }\n }\n\n const inputOptions = await getBundlerInputOptions(\n entryFile,\n {\n dependencies: deps,\n externalDependencies: new Map(),\n workspaceMap,\n },\n platform,\n env,\n { sourcemap, isDev: true, workspaceRoot, projectRoot, externalsPreset: bundlerOptions?.externals === true },\n );\n\n if (Array.isArray(inputOptions.plugins)) {\n // filter out node-resolve plugin so all node_modules are external\n // and tsconfig-paths plugin as we are injection a custom one\n const plugins = [] as Plugin[];\n inputOptions.plugins.forEach(plugin => {\n if ((plugin as Plugin | undefined)?.name === 'node-resolve') {\n return;\n }\n\n if ((plugin as Plugin | undefined)?.name === 'tsconfig-paths') {\n plugins.push(\n tsConfigPaths({\n localResolve: true,\n }),\n );\n return;\n }\n\n plugins.push(plugin as Plugin);\n });\n\n inputOptions.plugins = plugins;\n inputOptions.plugins.push(aliasHono());\n // fixes imports like lodash/fp/get\n inputOptions.plugins.push(nodeModulesExtensionResolver());\n\n const depsToOptimize = analyzeEntryResult.depsToOptimize;\n const resolvedWorkspaceRoot = analyzeEntryResult.workspaceRoot || workspaceRoot;\n if (depsToOptimize?.size && resolvedWorkspaceRoot) {\n inputOptions.plugins.push(\n workspaceDepsWatcher({\n depsToOptimize,\n optimizedDependencyFiles: deps,\n workspaceMap,\n workspaceRoot: resolvedWorkspaceRoot,\n outputDir: analyzeEntryResult.outputDir || outputDir,\n platform,\n bundlerOptions,\n }),\n );\n }\n }\n\n return inputOptions;\n}\n\nexport async function createWatcher(inputOptions: InputOptions, outputOptions: OutputOptions) {\n const watcher = await watch({\n ...inputOptions,\n output: {\n ...outputOptions,\n format: 'esm',\n entryFileNames: '[name].mjs',\n chunkFileNames: '[name].mjs',\n },\n });\n\n return watcher;\n}\n","import { readFile } from 'node:fs/promises';\nimport { transformAsync } from '@babel/core';\nimport { checkConfigExport } from './babel/check-config-export';\n\n/**\n * Lightweight entry analysis that returns the detected project type by running\n * only the Babel check-config-export plugin on the Mastra entry file. This is\n * intentionally cheaper than `analyzeBundle` and is used by the CLI before\n * `prepare()` clears `.mastra` to decide whether Factory-specific assets\n * should be copied.\n *\n * Returns `'factory'` when the entry imports `MastraFactory` and\n * constructs it, or `undefined` for ordinary Mastra projects.\n */\nexport async function analyzeEntryProjectType(mastraEntry: string): Promise<string | undefined> {\n const code = await readFile(mastraEntry, 'utf-8');\n const result: { hasValidConfig: boolean; projectType?: string } = { hasValidConfig: false };\n\n await transformAsync(code, {\n filename: mastraEntry,\n presets: [import.meta.resolve('@babel/preset-typescript')],\n plugins: [() => checkConfigExport(result)],\n });\n\n return result.projectType;\n}\n","import type { IMastraLogger } from '@mastra/core/logger';\nimport type { Config } from '@mastra/core/mastra';\nimport { extractMastraOption, extractMastraOptionBundler } from './shared/extract-mastra-option';\n\nexport function getServerOptionsBundler(\n entryFile: string,\n result: {\n hasCustomConfig: false;\n },\n) {\n return extractMastraOptionBundler('server', entryFile, result);\n}\n\nexport async function getServerOptions(\n entryFile: string,\n outputDir: string,\n logger?: IMastraLogger,\n): Promise<Config['server'] | null> {\n const result = await extractMastraOption('server', entryFile, outputDir, logger);\n if (!result) {\n return null;\n }\n\n return result.getConfig();\n}\n","import { lstat, readdir, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { MAX_FS_SUBAGENT_DEPTH } from '@mastra/core/agent';\nimport type { AgentSchedulePromptDefinition } from '@mastra/core/schedules';\nimport matter from 'gray-matter';\nimport { slash } from '../utils';\n\n/**\n * A file-system routed agent directory discovered under `<mastraDir>/agents/`.\n * All paths are absolute and slash-normalized so they can be embedded into\n * generated module source on any platform.\n */\nexport interface DiscoveredFsAgent {\n /** Agent directory name. Used as the default `id`/`name`. */\n name: string;\n /** Absolute, slash-normalized path to the agent directory. */\n dir: string;\n /** Absolute path to `config.ts`/`config.js`, if present. */\n configPath?: string;\n /** Absolute path to `instructions.md`, if present. */\n instructionsPath?: string;\n /** Absolute path to `workspace.ts`/`workspace.js`, if present. */\n workspacePath?: string;\n /** Absolute path to `memory.ts`/`memory.js`, if present. */\n memoryPath?: string;\n /**\n * Absolute, slash-normalized path to an authored `workspace/` directory of\n * seed files, if present. These are mirrored into the deployed workspace at\n * build time (Eve parity) so the agent starts with them on disk.\n */\n workspaceSeedDir?: string;\n /** Tools discovered under `tools/`, in stable (sorted) order. */\n tools: { key: string; path: string }[];\n /** Input processors discovered under `processors/input/`, in stable (sorted) order. */\n inputProcessors: { key: string; path: string }[];\n /** Output processors discovered under `processors/output/`, in stable (sorted) order. */\n outputProcessors: { key: string; path: string }[];\n /** Scorers discovered under `scorers/`, in stable (sorted) order. */\n scorers: { key: string; path: string }[];\n /** Skills discovered under `skills/`, in stable (sorted) order. */\n skills: DiscoveredFsSkill[];\n /**\n * Schedules discovered under `schedules/`, in stable (path-sorted) order.\n * Nested files keep their relative path in `key` (`billing/sweep.ts` →\n * `billing/sweep`) so a schedule's identity is stable across builds.\n */\n schedules: DiscoveredFsSchedule[];\n /**\n * Declared subagents discovered under `subagents/`, in stable (sorted) order.\n * Subagents may declare their own `subagents/`, up to `MAX_FS_SUBAGENT_DEPTH`\n * levels below the top-level agent; deeper `subagents/` directories are\n * ignored with a warning.\n */\n subagents: DiscoveredFsAgent[];\n}\n\n/**\n * A skill discovered under `agents/<name>/skills/`.\n *\n * - `kind: 'module'` — a `.ts`/`.js` file whose default export is a `createSkill(...)`\n * result. Codegen imports it directly; `name`/`description`/`instructions` are\n * unknown at discovery time and resolved at runtime from the module.\n * - `kind: 'packaged'` — a `SKILL.md` (optionally with a `references/` subdir) or a\n * flat `<skill>.md`. Codegen inlines it via `createSkill(...)` using the parsed\n * fields below so the deployed bundle carries no filesystem dependency.\n */\nexport type DiscoveredFsSkill =\n | {\n kind: 'module';\n /** Absolute, slash-normalized path to the `.ts`/`.js` skill module. */\n path: string;\n }\n | {\n kind: 'packaged';\n name: string;\n description: string;\n instructions: string;\n /** Reference file contents keyed by relative path (from `references/`). */\n references: Record<string, string>;\n };\n\n/**\n * A schedule discovered under `agents/<name>/schedules/`.\n *\n * - `kind: 'module'` — a `.ts`/`.js` file whose default export is a\n * `defineSchedule(...)` result. Codegen imports it directly, which is what\n * makes handler mode possible: the handler is a live function, not data.\n * - `kind: 'markdown'` — a `.md` file with cron frontmatter and the document\n * body as the prompt. Codegen inlines it so the bundle carries no filesystem\n * dependency.\n */\nexport type DiscoveredFsSchedule =\n | {\n kind: 'module';\n /** Path-derived identity relative to `schedules/`, extension stripped. */\n key: string;\n /** Absolute, slash-normalized path to the `.ts`/`.js` schedule module. */\n path: string;\n }\n | {\n kind: 'markdown';\n key: string;\n /**\n * Absolute, slash-normalized path to the `.md` file. Its contents are\n * inlined at build time, so the dev watcher has to watch this path\n * explicitly — nothing imports it.\n */\n path: string;\n /** Parsed frontmatter fields plus the body as `prompt`. */\n definition: MarkdownScheduleDefinition;\n };\n\n/**\n * A markdown schedule is always prompt mode — the document body is the prompt\n * and handler mode needs a function, so it needs a `.ts`/`.js` module. Reuses core's\n * definition type so the two can't drift; core validates the parsed result\n * during agent assembly.\n */\nexport type MarkdownScheduleDefinition = AgentSchedulePromptDefinition;\n\n/**\n * Frontmatter keys a markdown schedule may set, in the order they are copied\n * onto the definition. Anything outside this list fails the build rather than\n * being silently dropped — a schedule that quietly ignores half its config is\n * worse than one that refuses to build.\n *\n * The `satisfies` binds this list to core's definition type, so renaming or\n * removing a field there breaks the build here instead of silently rejecting\n * frontmatter that used to be valid. (`prompt` is excluded because the document\n * body supplies it, `handler` because markdown can't carry a function.)\n */\nconst MARKDOWN_SCHEDULE_KEYS = [\n 'cron',\n 'timezone',\n 'name',\n 'threadId',\n 'resourceId',\n 'signalType',\n 'tagName',\n 'attributes',\n 'providerOptions',\n 'ifActive',\n 'ifIdle',\n 'status',\n 'metadata',\n] as const satisfies readonly (keyof Omit<AgentSchedulePromptDefinition, 'prompt' | 'handler'>)[];\n\nconst CONFIG_BASENAMES = ['config.ts', 'config.js'];\nconst WORKSPACE_BASENAMES = ['workspace.ts', 'workspace.js'];\nconst MEMORY_BASENAMES = ['memory.ts', 'memory.js'];\nconst INSTRUCTIONS_BASENAME = 'instructions.md';\nconst TOOL_EXTENSIONS = ['.ts', '.js'];\nconst SCHEDULE_MODULE_EXTENSIONS = ['.ts', '.js'];\nconst SKILL_MODULE_EXTENSIONS = ['.ts', '.js'];\nconst SKILL_MD_BASENAME = 'SKILL.md';\n\n/**\n * Presence check that does NOT follow symlinks. Returns `false` for symlinks\n * (and broken links) so a symlinked `config.ts`/`instructions.md`/`workspace.ts`/\n * `memory.ts` is never inlined or imported into the generated bundle.\n */\nasync function exists(path: string): Promise<boolean> {\n try {\n return !(await lstat(path)).isSymbolicLink();\n } catch {\n return false;\n }\n}\n\n/**\n * Returns the slash-normalized path when `path` is a real directory (not a\n * symlink). Symlinked directories are rejected to prevent the build from\n * following links out of the project tree during discovery.\n */\nasync function realDirectory(path: string): Promise<string | undefined> {\n try {\n const info = await lstat(path);\n if (info.isDirectory() && !info.isSymbolicLink()) {\n return slash(path);\n }\n } catch {\n // not present\n }\n return undefined;\n}\n\nasync function directoryExists(path: string): Promise<string | undefined> {\n return realDirectory(path);\n}\n\nasync function firstExisting(dir: string, basenames: string[]): Promise<string | undefined> {\n for (const basename of basenames) {\n const candidate = join(dir, basename);\n if (await exists(candidate)) {\n return slash(candidate);\n }\n }\n return undefined;\n}\n\nfunction isTestFile(basename: string): boolean {\n return /\\.(test|spec)\\.(ts|js)$/.test(basename);\n}\n\nfunction toolKey(basename: string): string {\n return basename.replace(/\\.(ts|js)$/, '');\n}\n\n/**\n * Discover default-exporting `.ts`/`.js` modules directly under `dir`, returning\n * `{ key, path }` entries in stable (sorted) order. Test files, symlinks, and\n * subdirectories are skipped: a symlinked module could point anywhere on the\n * build machine and be embedded into generated import code. Shared by the\n * `tools/` and `scorers/` scanners.\n */\nasync function discoverModuleDir(dir: string): Promise<{ key: string; path: string }[]> {\n if (!(await exists(dir))) {\n return [];\n }\n\n let entries: string[];\n try {\n entries = await readdir(dir);\n } catch {\n return [];\n }\n\n const modules: { key: string; path: string }[] = [];\n for (const basename of entries.sort()) {\n if (isTestFile(basename)) {\n continue;\n }\n if (!TOOL_EXTENSIONS.some(ext => basename.endsWith(ext))) {\n continue;\n }\n const path = join(dir, basename);\n // Use lstat so symlinks are detected (not followed). Skip symlinks and\n // directories: a symlinked module file could point anywhere on the build\n // machine and be embedded into generated import code.\n const stats = await lstat(path);\n if (stats.isSymbolicLink() || stats.isDirectory()) {\n continue;\n }\n modules.push({ key: toolKey(basename), path: slash(path) });\n }\n\n return modules;\n}\n\nasync function discoverTools(toolsDir: string): Promise<DiscoveredFsAgent['tools']> {\n return discoverModuleDir(toolsDir);\n}\n\nasync function discoverProcessors(\n processorsDir: string,\n): Promise<{ input: { key: string; path: string }[]; output: { key: string; path: string }[] }> {\n const result = { input: [] as { key: string; path: string }[], output: [] as { key: string; path: string }[] };\n\n for (const type of ['input', 'output'] as const) {\n const typeDir = join(processorsDir, type);\n if (!(await exists(typeDir))) {\n continue;\n }\n\n let entries: string[];\n try {\n entries = await readdir(typeDir);\n } catch {\n continue;\n }\n\n for (const basename of entries.sort()) {\n if (isTestFile(basename)) {\n continue;\n }\n if (!TOOL_EXTENSIONS.some(ext => basename.endsWith(ext))) {\n continue;\n }\n const path = join(typeDir, basename);\n const stats = await lstat(path);\n if (stats.isSymbolicLink() || stats.isDirectory()) {\n continue;\n }\n result[type].push({ key: toolKey(basename), path: slash(path) });\n }\n }\n\n return result;\n}\n\nasync function readReferences(referencesDir: string): Promise<Record<string, string>> {\n if (!(await exists(referencesDir))) {\n return {};\n }\n const references: Record<string, string> = {};\n let entries: string[];\n try {\n entries = await readdir(referencesDir);\n } catch {\n return {};\n }\n for (const basename of entries.sort()) {\n const path = join(referencesDir, basename);\n // Use lstat so symlinks are detected (not followed). Skip symlinks: a\n // symlink under `references/` could point anywhere on the build machine and\n // silently embed arbitrary file contents into the generated bundle.\n const stats = await lstat(path);\n if (stats.isSymbolicLink() || stats.isDirectory()) {\n continue;\n }\n references[basename] = await readFile(path, 'utf-8');\n }\n return references;\n}\n\nasync function parsePackagedSkill(\n skillMdPath: string,\n fallbackName: string,\n references: Record<string, string> = {},\n): Promise<Extract<DiscoveredFsSkill, { kind: 'packaged' }>> {\n const raw = await readFile(skillMdPath, 'utf-8');\n const parsed = matter(raw);\n const frontmatter = parsed.data as { name?: string; description?: string };\n const name = frontmatter.name ?? fallbackName;\n const description = frontmatter.description;\n\n if (!description) {\n throw new Error(\n `Skill \"${name}\" in ${skillMdPath} is missing a required \"description\". ` +\n `Add a YAML frontmatter block with a \"description:\" field. ` +\n `See https://agentskills.io/specification for the SKILL.md format.`,\n );\n }\n\n const instructions = parsed.content.trim();\n return { kind: 'packaged', name, description, instructions, references };\n}\n\nfunction skillModuleName(basename: string): string {\n return basename.replace(/\\.(ts|js)$/, '');\n}\n\nasync function discoverSkills(skillsDir: string): Promise<DiscoveredFsSkill[]> {\n if (!(await exists(skillsDir))) {\n return [];\n }\n\n let entries: string[];\n try {\n entries = await readdir(skillsDir);\n } catch {\n return [];\n }\n\n const skills: DiscoveredFsSkill[] = [];\n for (const basename of entries.sort()) {\n if (isTestFile(basename)) {\n continue;\n }\n const path = join(skillsDir, basename);\n // Use lstat so symlinks are detected (not followed). Skip symlinks: a\n // symlinked skill module/markdown could point anywhere on the build machine\n // and be bundled or inlined into the generated output.\n const stats = await lstat(path);\n if (stats.isSymbolicLink()) {\n continue;\n }\n const isDir = stats.isDirectory();\n\n // Packaged skill directory: <skill>/SKILL.md (+ references/)\n if (isDir) {\n const skillMd = join(path, SKILL_MD_BASENAME);\n if (await exists(skillMd)) {\n const references = await readReferences(join(path, 'references'));\n skills.push(await parsePackagedSkill(skillMd, skillModuleName(basename), references));\n }\n continue;\n }\n\n // createSkill module: <skill>.ts | <skill>.js\n if (SKILL_MODULE_EXTENSIONS.some(ext => basename.endsWith(ext))) {\n skills.push({ kind: 'module', path: slash(path) });\n continue;\n }\n\n // Flat markdown skill: <skill>.md\n if (basename.endsWith('.md')) {\n const skill = await parsePackagedSkill(path, basename.replace(/\\.md$/, ''));\n skills.push(skill);\n }\n }\n\n return skills;\n}\n\n/**\n * Parse a markdown schedule: YAML frontmatter for the cron (and other JSON-safe\n * options), document body for the prompt.\n *\n * Throws a build error naming the file when `cron` is missing or the body is\n * empty — a schedule that can't fire is never what the author meant.\n */\nasync function parseMarkdownSchedule(path: string, key: string): Promise<MarkdownScheduleDefinition> {\n const raw = await readFile(path, 'utf-8');\n\n let parsed: ReturnType<typeof matter>;\n try {\n parsed = matter(raw);\n } catch (error) {\n // The most common cron form starts with `*`, which YAML reads as an alias\n // indicator, so `cron: */5 * * * *` fails with an opaque parser error.\n // Name the actual fix instead of surfacing that raw.\n const detail = error instanceof Error ? error.message.split('\\n')[0] : String(error);\n throw new Error(\n `Schedule \"${key}\" in ${path} has invalid YAML frontmatter: ${detail}. ` +\n `Cron expressions must be quoted (cron: \"*/5 * * * *\"), because a leading \"*\" is a YAML alias.`,\n );\n }\n\n const frontmatter = (parsed.data ?? {}) as Record<string, unknown>;\n const prompt = parsed.content.trim();\n\n const unknown = Object.keys(frontmatter).filter(\n field => !(MARKDOWN_SCHEDULE_KEYS as readonly string[]).includes(field),\n );\n if (unknown.length > 0) {\n const hint = unknown.includes('prompt')\n ? ` The document body is used as the prompt, so \"prompt\" cannot be set in frontmatter.`\n : ` Supported fields: ${MARKDOWN_SCHEDULE_KEYS.join(', ')}. Handler mode requires a .ts or .js schedule.`;\n throw new Error(`Schedule \"${key}\" in ${path} has unknown frontmatter field(s): ${unknown.join(', ')}.${hint}`);\n }\n\n if (!frontmatter.cron || typeof frontmatter.cron !== 'string') {\n throw new Error(\n `Schedule \"${key}\" in ${path} is missing a required \"cron\". ` +\n `Add a YAML frontmatter block with a \"cron:\" field (e.g. cron: \"0 9 * * *\").`,\n );\n }\n\n if (!prompt) {\n throw new Error(\n `Schedule \"${key}\" in ${path} has an empty body. ` +\n `The document body is used as the prompt, so it cannot be blank.`,\n );\n }\n\n const definition: Record<string, unknown> = { cron: frontmatter.cron, prompt };\n for (const field of MARKDOWN_SCHEDULE_KEYS) {\n if (field === 'cron') continue;\n if (frontmatter[field] !== undefined) {\n definition[field] = frontmatter[field];\n }\n }\n return definition as unknown as MarkdownScheduleDefinition;\n}\n\n/**\n * Discover schedules under `agents/<name>/schedules/`, recursing into\n * subdirectories so a schedule's identity is its path relative to `schedules/`\n * with the extension stripped (`billing/sweep.ts` → `billing/sweep`).\n *\n * Test files and symlinks (files and directories alike) are skipped for the\n * same reason as the other scanners: a symlink could point anywhere on the\n * build machine and be embedded into generated import code.\n */\nasync function discoverSchedules(schedulesDir: string, prefix = ''): Promise<DiscoveredFsSchedule[]> {\n if (!(await exists(schedulesDir))) {\n return [];\n }\n\n let entries: string[];\n try {\n entries = await readdir(schedulesDir);\n } catch {\n return [];\n }\n\n const schedules: DiscoveredFsSchedule[] = [];\n for (const basename of entries.sort()) {\n const path = join(schedulesDir, basename);\n\n let stats;\n try {\n stats = await lstat(path);\n } catch {\n continue;\n }\n if (stats.isSymbolicLink()) {\n continue;\n }\n\n if (stats.isDirectory()) {\n schedules.push(...(await discoverSchedules(path, `${prefix}${basename}/`)));\n continue;\n }\n\n if (isTestFile(basename)) {\n continue;\n }\n\n if (SCHEDULE_MODULE_EXTENSIONS.some(ext => basename.endsWith(ext))) {\n schedules.push({\n kind: 'module',\n key: `${prefix}${basename.replace(/\\.(ts|js)$/, '')}`,\n path: slash(path),\n });\n continue;\n }\n\n if (basename.endsWith('.md')) {\n const key = `${prefix}${basename.replace(/\\.md$/, '')}`;\n schedules.push({\n kind: 'markdown',\n key,\n path: slash(path),\n definition: await parseMarkdownSchedule(path, key),\n });\n }\n }\n\n // Sort by key, not by traversal order. Sorting basenames only orders each\n // directory: given `a.ts` alongside a directory `a/`, `a` sorts before\n // `a.ts`, so recursion emits `a/job` before `a`. Codegen order follows this\n // list, so a global sort is what actually makes it path-sorted and stable.\n return schedules.sort((left, right) => (left.key < right.key ? -1 : left.key > right.key ? 1 : 0));\n}\n\n/**\n * Discover a single agent directory: its `config`/`instructions`/`workspace`\n * files plus `tools/`, `skills/`, and declared `subagents/`. Returns\n * `undefined` when `dir` is not an agent directory (no `config.(ts|js)` and no\n * `instructions.md`).\n *\n * `depth` is the subagent nesting level (`0` for top-level agents). Discovery\n * recurses into `subagents/` until `MAX_FS_SUBAGENT_DEPTH`; deeper directories\n * are ignored with a warning.\n */\nasync function discoverAgentDir(\n dir: string,\n name: string,\n depth: number,\n onWarn?: (message: string) => void,\n): Promise<DiscoveredFsAgent | undefined> {\n const configPath = await firstExisting(dir, CONFIG_BASENAMES);\n const instructionsPath = (await exists(join(dir, INSTRUCTIONS_BASENAME)))\n ? slash(join(dir, INSTRUCTIONS_BASENAME))\n : undefined;\n\n // Not an agent directory unless it has a config or instructions file.\n if (!configPath && !instructionsPath) {\n return undefined;\n }\n\n const workspacePath = await firstExisting(dir, WORKSPACE_BASENAMES);\n const memoryPath = await firstExisting(dir, MEMORY_BASENAMES);\n const workspaceSeedDir = await directoryExists(join(dir, 'workspace'));\n const tools = await discoverTools(join(dir, 'tools'));\n const processors = await discoverProcessors(join(dir, 'processors'));\n const scorers = await discoverModuleDir(join(dir, 'scorers'));\n const skills = await discoverSkills(join(dir, 'skills'));\n const schedules = await discoverSchedules(join(dir, 'schedules'));\n const subagents = await discoverSubagents(dir, depth, onWarn);\n\n return {\n name,\n dir: slash(dir),\n configPath,\n instructionsPath,\n workspacePath,\n memoryPath,\n workspaceSeedDir,\n tools,\n inputProcessors: processors.input,\n outputProcessors: processors.output,\n scorers,\n skills,\n schedules,\n subagents,\n };\n}\n\n/**\n * Discover declared subagents under `<dir>/subagents/*`. `parentDepth` is the\n * parent agent's nesting level (`0` for top-level agents). Discovery recurses\n * until `MAX_FS_SUBAGENT_DEPTH` levels of subagents; a `subagents/` directory\n * that would exceed the cap is skipped with a warning.\n */\nasync function discoverSubagents(\n parentDir: string,\n parentDepth: number,\n onWarn?: (message: string) => void,\n): Promise<DiscoveredFsAgent[]> {\n const subagentsDir = join(parentDir, 'subagents');\n if (!(await exists(subagentsDir))) {\n return [];\n }\n\n if (parentDepth >= MAX_FS_SUBAGENT_DEPTH) {\n onWarn?.(\n `Ignoring subagents in \"${slash(subagentsDir)}\": subagents may only nest ${MAX_FS_SUBAGENT_DEPTH} levels below a top-level agent.`,\n );\n return [];\n }\n\n let entries: string[];\n try {\n entries = await readdir(subagentsDir);\n } catch {\n return [];\n }\n\n const subagents: DiscoveredFsAgent[] = [];\n for (const name of entries.sort()) {\n const dir = join(subagentsDir, name);\n if (!(await realDirectory(dir))) {\n continue;\n }\n const child = await discoverAgentDir(dir, name, parentDepth + 1, onWarn);\n if (child) {\n subagents.push(child);\n }\n }\n\n return subagents;\n}\n\n/**\n * Scan `<mastraDir>/agents/*` for file-system routed agents. A directory is\n * treated as an agent only when it contains a `config.(ts|js)` or an\n * `instructions.md`; other directories are ignored. Each agent may declare\n * `subagents/` up to `MAX_FS_SUBAGENT_DEPTH` levels deep. Returns descriptors\n * with absolute, slash-normalized paths ready for codegen. Performs no module\n * evaluation — only filesystem inspection.\n */\nexport async function discoverFsAgents(\n mastraDir: string,\n onWarn?: (message: string) => void,\n): Promise<DiscoveredFsAgent[]> {\n const agentsDir = join(mastraDir, 'agents');\n if (!(await exists(agentsDir))) {\n return [];\n }\n\n let entries: string[];\n try {\n entries = await readdir(agentsDir);\n } catch {\n return [];\n }\n\n const discovered: DiscoveredFsAgent[] = [];\n for (const name of entries.sort()) {\n const dir = join(agentsDir, name);\n if (!(await realDirectory(dir))) {\n continue;\n }\n const agent = await discoverAgentDir(dir, name, 0, onWarn);\n if (agent) {\n discovered.push(agent);\n }\n }\n\n return discovered;\n}\n\n/**\n * A file-system routed workflow file discovered under `<mastraDir>/workflows/`.\n * All paths are absolute and slash-normalized so they can be embedded into\n * generated module source on any platform.\n */\nexport interface DiscoveredFsWorkflow {\n /** Workflow key derived from the filename (without extension). */\n key: string;\n /** Absolute, slash-normalized path to the workflow module. */\n path: string;\n}\n\n/**\n * Scan `<mastraDir>/workflows/` for file-system routed workflow modules. Only\n * files whose source contains an `export default` are treated as fs-routed\n * workflows — this convention distinguishes them from workflow files that are\n * manually imported and registered programmatically. Returns descriptors with\n * absolute, slash-normalized paths ready for codegen. Performs no module\n * evaluation — only filesystem and source-text inspection.\n */\nexport async function discoverFsWorkflows(mastraDir: string): Promise<DiscoveredFsWorkflow[]> {\n const workflowsDir = join(mastraDir, 'workflows');\n if (!(await exists(workflowsDir))) {\n return [];\n }\n\n let entries: string[];\n try {\n entries = await readdir(workflowsDir);\n } catch {\n return [];\n }\n\n const discovered: DiscoveredFsWorkflow[] = [];\n for (const basename of entries.sort()) {\n if (isTestFile(basename)) {\n continue;\n }\n if (!TOOL_EXTENSIONS.some(ext => basename.endsWith(ext))) {\n continue;\n }\n const path = join(workflowsDir, basename);\n const stats = await lstat(path);\n if (stats.isSymbolicLink() || stats.isDirectory()) {\n continue;\n }\n // Convention: only files with `export default` are fs-routed workflows.\n // Files using named exports are assumed to be manually imported.\n const source = await readFile(path, 'utf-8');\n if (!/\\bexport\\s+default\\b/.test(source)) {\n continue;\n }\n discovered.push({ key: toolKey(basename), path: slash(path) });\n }\n\n return discovered;\n}\n\n/**\n * A discovered singleton config file under `<mastraDir>/`. All paths are\n * absolute and slash-normalized so they can be embedded into generated module\n * source on any platform.\n */\nexport interface DiscoveredFsSingleton {\n /** Absolute, slash-normalized path to the singleton module. */\n path: string;\n}\n\nconst SINGLETON_EXTENSIONS = ['.ts', '.js', '.mts', '.mjs'];\n\n/** Safe singleton identifier: no path separators, `..`, or other traversal. */\nconst SINGLETON_NAME_PATTERN = /^[a-zA-Z0-9_-]+$/;\n\n/**\n * Check for a singleton config file (e.g. `storage.ts`, `storage.js`) directly\n * under `<mastraDir>`. Returns the first matching file path or `undefined`.\n * Symlinks are rejected for security.\n *\n * Convention: only files with `export default` are fs-routed singletons. Files\n * using named exports are assumed to be manually imported into the user's\n * `index.ts`, so they are ignored to remain backward-compatible with existing\n * project structures.\n *\n * `name` must be a bare identifier — path separators and traversal sequences are\n * rejected so the lookup can never escape `<mastraDir>`.\n */\nexport async function discoverFsSingleton(mastraDir: string, name: string): Promise<DiscoveredFsSingleton | undefined> {\n if (!SINGLETON_NAME_PATTERN.test(name)) {\n throw new Error(`Invalid fs-singleton name ${JSON.stringify(name)}: expected a bare identifier.`);\n }\n\n for (const ext of SINGLETON_EXTENSIONS) {\n const candidate = join(mastraDir, `${name}${ext}`);\n try {\n const stats = await lstat(candidate);\n if (!stats.isFile() || stats.isSymbolicLink()) {\n continue;\n }\n const source = await readFile(candidate, 'utf-8');\n // Only files with a default export are fs-routed. A named-export file with\n // this name is user-managed, so skip it and keep scanning other extensions.\n if (!/\\bexport\\s+default\\b/.test(source)) {\n continue;\n }\n return { path: slash(candidate) };\n } catch {\n // not present\n }\n }\n return undefined;\n}\n","import { readFile } from 'node:fs/promises';\nimport type { DiscoveredFsAgent, DiscoveredFsSingleton, DiscoveredFsWorkflow } from './discover';\n\nfunction sanitizeIdentifier(name: string, prefix: string, index: string): string {\n const cleaned = name.replace(/[^a-zA-Z0-9_$]/g, '_');\n return `${prefix}_${index}_${cleaned}`;\n}\n\n/**\n * Emit the imports for a single discovered agent into `lines` and return the\n * source of its `assembleAgentFromFsEntry` entry object (the `{ name, config,\n * ... }` argument). `idPath` is a dot-free, unique path index (e.g. `0` for the\n * first top-level agent, `0_1` for its second subagent) used to keep generated\n * identifiers unique across the parent/child tree. `workspaceName` is the\n * slash-joined workspace key (`<parent>/<child>` for subagents) so seed files\n * don't collide. Discovered subagents are emitted recursively as a nested\n * `subagents: [...]` field (discovery already enforces the depth cap).\n */\nasync function emitAgentEntry(\n agent: DiscoveredFsAgent,\n idPath: string,\n workspaceName: string,\n lines: string[],\n): Promise<string> {\n const configIdent = sanitizeIdentifier(agent.name, 'config', idPath);\n const toolIdents: { key: string; ident: string }[] = [];\n\n if (agent.configPath) {\n lines.push(`import ${configIdent} from ${JSON.stringify(agent.configPath)};`);\n }\n\n let workspaceIdent: string | undefined;\n if (agent.workspacePath) {\n workspaceIdent = sanitizeIdentifier(`${agent.name}_workspace`, 'workspace', idPath);\n lines.push(`import ${workspaceIdent} from ${JSON.stringify(agent.workspacePath)};`);\n }\n\n let memoryIdent: string | undefined;\n if (agent.memoryPath) {\n memoryIdent = sanitizeIdentifier(`${agent.name}_memory`, 'memory', idPath);\n lines.push(`import ${memoryIdent} from ${JSON.stringify(agent.memoryPath)};`);\n }\n\n for (let t = 0; t < agent.tools.length; t++) {\n const tool = agent.tools[t]!;\n const ident = sanitizeIdentifier(`${agent.name}_${tool.key}`, 'tool', `${idPath}_${t}`);\n lines.push(`import ${ident} from ${JSON.stringify(tool.path)};`);\n toolIdents.push({ key: tool.key, ident });\n }\n\n const inputProcessorIdents: string[] = [];\n for (let p = 0; p < agent.inputProcessors.length; p++) {\n const proc = agent.inputProcessors[p]!;\n const ident = sanitizeIdentifier(`${agent.name}_inputProc_${proc.key}`, 'proc', `${idPath}_ip${p}`);\n lines.push(`import ${ident} from ${JSON.stringify(proc.path)};`);\n inputProcessorIdents.push(ident);\n }\n\n const outputProcessorIdents: string[] = [];\n for (let p = 0; p < agent.outputProcessors.length; p++) {\n const proc = agent.outputProcessors[p]!;\n const ident = sanitizeIdentifier(`${agent.name}_outputProc_${proc.key}`, 'proc', `${idPath}_op${p}`);\n lines.push(`import ${ident} from ${JSON.stringify(proc.path)};`);\n outputProcessorIdents.push(ident);\n }\n\n const scorerIdents: { key: string; ident: string }[] = [];\n for (let s = 0; s < agent.scorers.length; s++) {\n const scorer = agent.scorers[s]!;\n const ident = sanitizeIdentifier(`${agent.name}_scorer_${scorer.key}`, 'scorer', `${idPath}_${s}`);\n lines.push(`import ${ident} from ${JSON.stringify(scorer.path)};`);\n scorerIdents.push({ key: scorer.key, ident });\n }\n\n // Skills: `createSkill(...)` modules are imported and used directly;\n // packaged `SKILL.md` skills are inlined via `createSkill({...})`.\n const skillExprs: string[] = [];\n const agentSkills = agent.skills ?? [];\n for (let s = 0; s < agentSkills.length; s++) {\n const skill = agentSkills[s]!;\n if (skill.kind === 'module') {\n const ident = sanitizeIdentifier(`${agent.name}_skill`, 'skill', `${idPath}_${s}`);\n lines.push(`import ${ident} from ${JSON.stringify(skill.path)};`);\n skillExprs.push(ident);\n } else {\n const referenceFields = Object.entries(skill.references).map(\n ([key, value]) => `${JSON.stringify(key)}: ${JSON.stringify(value)}`,\n );\n const skillFields = [\n `name: ${JSON.stringify(skill.name)}`,\n `description: ${JSON.stringify(skill.description)}`,\n `instructions: ${JSON.stringify(skill.instructions)}`,\n ];\n if (referenceFields.length > 0) {\n skillFields.push(`references: { ${referenceFields.join(', ')} }`);\n }\n skillExprs.push(`__createSkill({ ${skillFields.join(', ')} })`);\n }\n }\n\n // Schedules: `.ts`/`.js` modules are imported so handler-mode schedules keep\n // a live function; markdown schedules are inlined as plain data.\n const scheduleExprs: string[] = [];\n const agentSchedules = agent.schedules ?? [];\n for (let s = 0; s < agentSchedules.length; s++) {\n const schedule = agentSchedules[s]!;\n const keyField = `key: ${JSON.stringify(schedule.key)}`;\n if (schedule.kind === 'module') {\n const ident = sanitizeIdentifier(`${agent.name}_schedule`, 'schedule', `${idPath}_${s}`);\n lines.push(`import ${ident} from ${JSON.stringify(schedule.path)};`);\n scheduleExprs.push(`{ ${keyField}, schedule: ${ident} }`);\n } else {\n scheduleExprs.push(`{ ${keyField}, schedule: ${JSON.stringify(schedule.definition)} }`);\n }\n }\n\n let instructionsMd: string | undefined;\n if (agent.instructionsPath) {\n instructionsMd = await readFile(agent.instructionsPath, 'utf-8');\n }\n\n // Declared subagents. Each is itself an `assembleAgentFromFsEntry` entry\n // object, recursively carrying its own `subagents`.\n const subagentExprs: string[] = [];\n for (let c = 0; c < agent.subagents.length; c++) {\n const child = agent.subagents[c]!;\n const childExpr = await emitAgentEntry(child, `${idPath}_${c}`, `${workspaceName}/${child.name}`, lines);\n subagentExprs.push(childExpr);\n }\n\n const entryFields: string[] = [`name: ${JSON.stringify(agent.name)}`];\n if (agent.configPath) {\n entryFields.push(`config: ${configIdent}`);\n }\n if (instructionsMd !== undefined) {\n entryFields.push(`instructionsMd: ${JSON.stringify(instructionsMd)}`);\n }\n if (toolIdents.length > 0) {\n const toolEntries = toolIdents.map(({ key, ident }) => `{ key: ${JSON.stringify(key)}, tool: ${ident} }`);\n entryFields.push(`tools: [${toolEntries.join(', ')}]`);\n }\n if (skillExprs.length > 0) {\n entryFields.push(`skills: [${skillExprs.join(', ')}]`);\n }\n if (inputProcessorIdents.length > 0) {\n entryFields.push(`inputProcessors: [${inputProcessorIdents.join(', ')}]`);\n }\n if (outputProcessorIdents.length > 0) {\n entryFields.push(`outputProcessors: [${outputProcessorIdents.join(', ')}]`);\n }\n if (scorerIdents.length > 0) {\n const scorerEntries = scorerIdents.map(({ key, ident }) => `{ key: ${JSON.stringify(key)}, scorer: ${ident} }`);\n entryFields.push(`scorers: [${scorerEntries.join(', ')}]`);\n }\n if (scheduleExprs.length > 0) {\n entryFields.push(`schedules: [${scheduleExprs.join(', ')}]`);\n }\n if (subagentExprs.length > 0) {\n entryFields.push(`subagents: [${subagentExprs.join(', ')}]`);\n }\n if (workspaceIdent) {\n entryFields.push(`workspace: ${workspaceIdent}`);\n }\n if (memoryIdent) {\n entryFields.push(`memory: ${memoryIdent}`);\n }\n // Default-on parity: every FS agent gets a default workspace (file + shell\n // tools) rooted at a per-agent `workspace/` dir next to the bundle, unless\n // config.ts or workspace.ts supplies one. Assembly applies the explicit >\n // convention > default precedence. Subagents nest under `<parent>/<child>` so\n // their seed directories never collide with the parent's.\n entryFields.push(`defaultWorkspaceBasePath: __workspaceBasePath(${JSON.stringify(workspaceName)})`);\n\n return `{ ${entryFields.join(', ')} }`;\n}\n\n/**\n * Generate the source of a wrapper module that:\n * 1. imports the user's real Mastra entry,\n * 2. imports each discovered `config.ts`, `tools/*.ts`, `skills/*.ts`\n * (`createSkill(...)` modules), `workspace.ts`, and `memory.ts`, inlining\n * packaged `SKILL.md` skills,\n * 3. assembles `Agent` instances via `assembleAgentFromFsEntry`, wiring any\n * declared `subagents/` into the parent (nested up to `MAX_FS_SUBAGENT_DEPTH`),\n * 4. registers them onto the user's `mastra` instance (code-registered agents\n * win on name collisions), and\n * 5. re-exports everything from the user's entry so this module is a drop-in\n * replacement for the original `#mastra` target.\n *\n * `instructions.md` is read into the generated wrapper. In dev, the CLI watcher\n * regenerates that wrapper when the markdown file changes.\n *\n * @param userEntry slash-normalized absolute path to the user's mastra entry.\n * @param agents discovered fs-routed agents (absolute, slash-normalized paths).\n */\nexport async function generateFsAgentsModule(\n userEntry: string | undefined,\n agents: DiscoveredFsAgent[],\n options?: {\n workflows?: DiscoveredFsWorkflow[];\n storage?: DiscoveredFsSingleton;\n observability?: DiscoveredFsSingleton;\n logger?: DiscoveredFsSingleton;\n server?: DiscoveredFsSingleton;\n studio?: DiscoveredFsSingleton;\n },\n): Promise<string> {\n const workflows = options?.workflows ?? [];\n const storage = options?.storage;\n const observability = options?.observability;\n const logger = options?.logger;\n const server = options?.server;\n const studio = options?.studio;\n const standalone = userEntry === undefined;\n const lines: string[] = [];\n\n const hasInlineSkills = (function check(list: DiscoveredFsAgent[]): boolean {\n return list.some(a => (a.skills ?? []).some(s => s.kind === 'packaged') || check(a.subagents ?? []));\n })(agents);\n\n lines.push(`import { assembleAgentFromFsEntry } from '@mastra/core/agent';`);\n if (hasInlineSkills) {\n lines.push(`import { createSkill as __createSkill } from '@mastra/core/skills';`);\n }\n if (standalone) {\n lines.push(`import { Mastra } from '@mastra/core';`);\n }\n lines.push(`import { fileURLToPath as __fileURLToPath } from 'node:url';`);\n lines.push(`import { dirname as __dirname, join as __join } from 'node:path';`);\n if (userEntry) {\n lines.push(`import * as __userEntry from ${JSON.stringify(userEntry)};`);\n lines.push(`export * from ${JSON.stringify(userEntry)};`);\n }\n lines.push(``);\n // Resolve workspace base paths relative to this bundled module so they point\n // at `<bundle>/workspace/<name>` wherever the bundle is deployed. Seed files\n // authored under `agents/<name>/workspace/**` are mirrored there at build time.\n // `name` may be a slash-joined path (`<parent>/<child>`) for subagents.\n lines.push(`const __bundleDir = __dirname(__fileURLToPath(import.meta.url));`);\n lines.push(`const __workspaceBasePath = name => __join(__bundleDir, 'workspace', ...name.split('/'));`);\n lines.push(``);\n\n // Singleton imports (storage.ts, observability.ts, etc.).\n const singletonImports: string[] = [];\n if (storage) {\n singletonImports.push(`import __fsStorage from ${JSON.stringify(storage.path)};`);\n }\n if (observability) {\n singletonImports.push(`import __fsObservability from ${JSON.stringify(observability.path)};`);\n }\n if (logger) {\n singletonImports.push(`import __fsLogger from ${JSON.stringify(logger.path)};`);\n }\n if (server) {\n singletonImports.push(`import __fsServer from ${JSON.stringify(server.path)};`);\n }\n if (studio) {\n singletonImports.push(`import __fsStudio from ${JSON.stringify(studio.path)};`);\n }\n if (singletonImports.length > 0) {\n lines.push(...singletonImports);\n lines.push(``);\n }\n\n const wfCodegen = workflows.length > 0 ? generateFsWorkflowsCodegen(workflows) : undefined;\n\n // Workflow imports (placed alongside other imports, before agent entries).\n if (wfCodegen) {\n for (const line of wfCodegen.importLines) {\n lines.push(line);\n }\n lines.push(``);\n }\n\n const entryExprs: string[] = [];\n for (let i = 0; i < agents.length; i++) {\n const agent = agents[i]!;\n const expr = await emitAgentEntry(agent, `${i}`, agent.name, lines);\n entryExprs.push(expr);\n }\n\n // In standalone mode (no user entry), auto-construct a Mastra instance.\n // In wrapper mode, reference the user's exported instance.\n if (standalone) {\n lines.push(``);\n lines.push(`const __mastra = new Mastra({});`);\n } else {\n lines.push(``);\n lines.push(`const __mastra = __userEntry.mastra;`);\n }\n\n lines.push(``);\n lines.push(`const __fsAgentEntries = [`);\n for (const expr of entryExprs) {\n lines.push(` ${expr},`);\n }\n lines.push(`];`);\n lines.push(``);\n // Singleton registration (storage, observability, etc.) MUST run before\n // agents/workflows. `addMemory`/`addAgent` bind the current store to\n // storage-dependent primitives at registration time, so the fs singletons\n // have to be in place first — otherwise fs-discovered agents/workflows would\n // stay bound to the default InMemoryStore.\n\n // Logger is registered before everything else so storage/observability and\n // agents receive the fs-provided logger when they are wired up below.\n if (logger) {\n lines.push(`if (__mastra && typeof __mastra.__registerFsLogger === 'function') {`);\n lines.push(` __mastra.__registerFsLogger(__fsLogger);`);\n lines.push(`}`);\n lines.push(``);\n }\n\n if (storage) {\n lines.push(`if (__mastra && typeof __mastra.__registerFsStorage === 'function') {`);\n lines.push(` __mastra.__registerFsStorage(__fsStorage);`);\n lines.push(`}`);\n lines.push(``);\n }\n\n if (observability) {\n lines.push(`if (__mastra && typeof __mastra.__registerFsObservability === 'function') {`);\n lines.push(` __mastra.__registerFsObservability(__fsObservability);`);\n lines.push(`}`);\n lines.push(``);\n }\n\n if (server) {\n lines.push(`if (__mastra && typeof __mastra.__registerFsServer === 'function') {`);\n lines.push(` __mastra.__registerFsServer(__fsServer);`);\n lines.push(`}`);\n lines.push(``);\n }\n\n if (studio) {\n lines.push(`if (__mastra && typeof __mastra.__registerFsStudio === 'function') {`);\n lines.push(` __mastra.__registerFsStudio(__fsStudio);`);\n lines.push(`}`);\n lines.push(``);\n }\n\n lines.push(`const __fsAgents = Object.create(null);`);\n lines.push(`for (const __entry of __fsAgentEntries) {`);\n lines.push(` __fsAgents[__entry.name] = assembleAgentFromFsEntry(__entry, {`);\n lines.push(` onWarn: msg => __mastra?.getLogger?.()?.warn?.(msg) ?? console.warn(msg),`);\n lines.push(` });`);\n lines.push(`}`);\n lines.push(``);\n\n lines.push(`if (__mastra && typeof __mastra.__registerFsAgents === 'function') {`);\n lines.push(` __mastra.__registerFsAgents(__fsAgents);`);\n lines.push(`}`);\n\n // Workflow registration (after agents, before final export).\n if (wfCodegen) {\n lines.push(``);\n\n for (const line of wfCodegen.registrationLines) {\n lines.push(line);\n }\n }\n\n lines.push(``);\n lines.push(`export const mastra = __mastra;`);\n\n return lines.join('\\n');\n}\n\n/**\n * Generate the workflow-registration lines to splice into the generated wrapper\n * module. Emits import statements for each discovered workflow module and a\n * registration block that calls `__registerFsWorkflows` on the user's mastra.\n *\n * Returns `{ importLines, registrationLines }` so the caller can place them at\n * the correct positions in the wrapper source.\n */\nexport function generateFsWorkflowsCodegen(workflows: DiscoveredFsWorkflow[]): {\n importLines: string[];\n registrationLines: string[];\n} {\n const importLines: string[] = [];\n const registrationLines: string[] = [];\n\n for (let i = 0; i < workflows.length; i++) {\n const wf = workflows[i]!;\n const ident = sanitizeIdentifier(wf.key, 'workflow', `${i}`);\n importLines.push(`import ${ident} from ${JSON.stringify(wf.path)};`);\n }\n\n registrationLines.push(`const __fsWorkflows = Object.create(null);`);\n for (let i = 0; i < workflows.length; i++) {\n const wf = workflows[i]!;\n const ident = sanitizeIdentifier(wf.key, 'workflow', `${i}`);\n registrationLines.push(`__fsWorkflows[${JSON.stringify(wf.key)}] = ${ident};`);\n }\n registrationLines.push(``);\n registrationLines.push(`if (__mastra && typeof __mastra.__registerFsWorkflows === 'function') {`);\n registrationLines.push(` __mastra.__registerFsWorkflows(__fsWorkflows);`);\n registrationLines.push(`}`);\n\n return { importLines, registrationLines };\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, posix } from 'node:path';\nimport { slash } from '../utils';\nimport { generateFsAgentsModule } from './codegen';\nimport { discoverFsAgents, discoverFsSingleton, discoverFsWorkflows } from './discover';\n\nexport interface PrepareFsAgentsEntryResult {\n /**\n * The entry file that should be fed to the bundler/analyzer. When fs-routed\n * primitives (agents, workflows, storage, observability, logger, server,\n * studio) are\n * found this is a generated wrapper module that registers them onto the\n * user's mastra instance; otherwise it is the original entry unchanged.\n * When auto-constructing (no user entry), this is always the generated module.\n */\n entryFile: string;\n /** Whether a standalone Mastra instance was auto-constructed (no index.ts). */\n standalone: boolean;\n /**\n * Glob tool paths for tools defined under `agents/*\\/tools` so they are\n * bundled alongside the top-level `tools/` directory.\n */\n toolPaths: string[];\n /** Number of fs-routed agents discovered. */\n agentCount: number;\n /** Number of fs-routed workflows discovered. */\n workflowCount: number;\n /** Whether a `storage.ts` singleton was discovered. */\n hasStorage: boolean;\n /** Whether an `observability.ts` singleton was discovered. */\n hasObservability: boolean;\n /** Whether a `logger.ts` singleton was discovered. */\n hasLogger: boolean;\n /** Whether a `server.ts` singleton was discovered. */\n hasServer: boolean;\n /** Whether a `studio.ts` singleton was discovered. */\n hasStudio: boolean;\n /**\n * Generated wrapper source to write to {@link entryFile}, or `undefined` when\n * there are no fs-routed primitives. The write is deferred so callers can run\n * it *after* `bundler.prepare()` empties the output directory — otherwise the\n * wrapper is wiped before the bundler reads it.\n */\n moduleSource?: string;\n}\n\n/**\n * Discover fs-routed agents under `<mastraDir>/agents/*`, workflows under\n * `<mastraDir>/workflows/`, and singleton config files (e.g. `storage.ts`,\n * `observability.ts`, `logger.ts`, `server.ts`, `studio.ts`).\n * When any are found, generate a wrapper entry module that registers them onto\n * the user's mastra instance. Returns the entry the bundler should use plus\n * extra tool glob paths so `agents/*\\/tools` are bundled.\n *\n * This does NOT write the wrapper to disk; call {@link writeFsAgentsEntry} with\n * the result after `bundler.prepare()` so the generated file is not wiped when\n * the output directory is emptied.\n *\n * When `entryFile` is `undefined` (no `index.ts`/`index.js`) and fs-routed\n * primitives are found, a standalone Mastra instance is auto-constructed from\n * them — no user code required.\n *\n * When no fs-routed primitives are present the original entry is returned\n * unchanged, so existing code-only projects are completely unaffected.\n */\nexport async function prepareFsAgentsEntry(\n mastraDir: string,\n entryFile: string | undefined,\n outputDirectory: string,\n): Promise<PrepareFsAgentsEntryResult> {\n const [agents, workflows, storage, observability, logger, server, studio] = await Promise.all([\n discoverFsAgents(mastraDir),\n discoverFsWorkflows(mastraDir),\n discoverFsSingleton(mastraDir, 'storage'),\n discoverFsSingleton(mastraDir, 'observability'),\n discoverFsSingleton(mastraDir, 'logger'),\n discoverFsSingleton(mastraDir, 'server'),\n discoverFsSingleton(mastraDir, 'studio'),\n ]);\n\n const standalone = entryFile === undefined;\n const hasFsPrimitives =\n agents.length > 0 || workflows.length > 0 || !!storage || !!observability || !!logger || !!server || !!studio;\n\n if (!hasFsPrimitives && entryFile !== undefined) {\n return {\n entryFile,\n standalone: false,\n toolPaths: [],\n agentCount: 0,\n workflowCount: 0,\n hasStorage: false,\n hasObservability: false,\n hasLogger: false,\n hasServer: false,\n hasStudio: false,\n };\n }\n\n if (!hasFsPrimitives && standalone) {\n throw new Error(\n 'No index.ts and no file-based primitives found. ' +\n 'Create src/mastra/index.ts with a Mastra instance, or add file-based agents/workflows/storage.',\n );\n }\n\n const moduleSource = await generateFsAgentsModule(entryFile ? slash(entryFile) : undefined, agents, {\n workflows,\n storage,\n observability,\n logger,\n server,\n studio,\n });\n const generatedEntry = join(outputDirectory, '.mastra-fs-agents-entry.mjs');\n\n const normalizedMastraDir = slash(mastraDir);\n const toolPaths =\n agents.length > 0\n ? [\n posix.join(normalizedMastraDir, 'agents/*/tools/**/*.{js,ts}'),\n `!${posix.join(normalizedMastraDir, 'agents/*/tools/**/*.{test,spec}.{js,ts}')}`,\n `!${posix.join(normalizedMastraDir, 'agents/*/tools/**/__tests__/**')}`,\n ]\n : [];\n\n return {\n entryFile: generatedEntry,\n standalone,\n toolPaths,\n agentCount: agents.length,\n workflowCount: workflows.length,\n hasStorage: !!storage,\n hasObservability: !!observability,\n hasLogger: !!logger,\n hasServer: !!server,\n hasStudio: !!studio,\n moduleSource,\n };\n}\n\n/**\n * Write the generated fs-agents wrapper produced by {@link prepareFsAgentsEntry}\n * to its `entryFile`. No-op when there are no fs-routed agents. Call this AFTER\n * `bundler.prepare()` (which empties the output directory) so the wrapper\n * survives for the bundler/watcher to read.\n */\nexport async function writeFsAgentsEntry(result: PrepareFsAgentsEntryResult): Promise<void> {\n if (!result.moduleSource) {\n return;\n }\n\n await mkdir(dirname(result.entryFile), { recursive: true });\n await writeFile(result.entryFile, result.moduleSource, 'utf-8');\n}\n","import { cp, lstat, mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { discoverFsAgents } from './discover';\nimport type { DiscoveredFsAgent } from './discover';\n\n/**\n * Skip symlinks when copying workspace seeds. A symlink under\n * `agents/<name>/workspace/` could point outside the workspace and be preserved\n * in the bundle, letting the agent read arbitrary files at runtime. We copy only\n * regular files and directories.\n */\nasync function rejectSymlinks(source: string): Promise<boolean> {\n const stats = await lstat(source);\n return !stats.isSymbolicLink();\n}\n\nasync function mirrorAgentSeeds(\n agent: DiscoveredFsAgent,\n workspaceName: string,\n bundleDir: string,\n mirrored: string[],\n): Promise<void> {\n if (agent.workspaceSeedDir) {\n const destination = join(bundleDir, 'workspace', ...workspaceName.split('/'));\n await mkdir(destination, { recursive: true });\n await cp(agent.workspaceSeedDir, destination, { recursive: true, filter: rejectSymlinks });\n mirrored.push(workspaceName);\n }\n\n // Subagents nest under `<parent>/<child>`, matching the codegen workspace key.\n for (const child of agent.subagents ?? []) {\n await mirrorAgentSeeds(child, `${workspaceName}/${child.name}`, bundleDir, mirrored);\n }\n}\n\n/**\n * Mirror authored `agents/<name>/workspace/**` seed files into the bundled\n * output so each fs-routed agent starts with them on disk (Eve parity). Files\n * are copied to `<bundleDir>/workspace/<name>`, which is exactly where the\n * generated entry roots each agent's default workspace at runtime (resolved\n * relative to the bundled module via `import.meta.url`). Declared subagents\n * mirror to the nested `<bundleDir>/workspace/<parent>/<child>` path.\n *\n * Must run AFTER the bundle step, since bundling recreates the output dir.\n *\n * @param mastraDir The user's `src/mastra` directory (source of seeds).\n * @param bundleDir The final bundle directory (e.g. `<outputDirectory>/output`).\n * @returns the workspace names whose seeds were mirrored (`<parent>/<child>` for subagents).\n */\nexport async function mirrorFsAgentWorkspaces(mastraDir: string, bundleDir: string): Promise<string[]> {\n const agents = await discoverFsAgents(mastraDir);\n const mirrored: string[] = [];\n\n for (const agent of agents) {\n await mirrorAgentSeeds(agent, agent.name, bundleDir, mirrored);\n }\n\n return mirrored;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAWA,MAAM,eAAe,CAAC,mCAAmC;AACzD,MAAM,gBAAgB,CAAC,sBAAsB,cAAc;;;;;;;;;;AAyB3D,SAAgB,qBAAqB,SAA8C;CACjF,MAAM,EAAE,gBAAgB,0BAA0B,cAAc,eAAe,WAAW,UAAU,mBAClG;CAEF,IAAI,eAAe;CAEnB,MAAM,mBAAmB,wBAAwB,gBAAgB,YAAY;CAC7E,MAAM,aAAa,0BAA0B,0BAA0B,aAAa;CAEpF,OAAO;EACL,MAAM;EACN,MAAM,aAAa;GACjB,MAAM,cAAc,MAAM,6BAA6B,gBAAgB;GAEvE,KAAK,MAAM,QAAQ,aACjB,KAAK,cAAA,GAAA,KAAA,QAAA,CAAqB,IAAI,CAAC;GAIjC,IAAI,cAAc;IAChB,eAAe;IACf;GACF;GAIA,IAAI,CAAC,MAFyB,uBAAuB,aAAa,UAAU,GAG1E;GAMF,MAAMA,gBAAAA,gBAFW,oBAAoB,cAER,GAAG,WAAW;IACzC,gBAAgB;KACd,GAAG;KACH,WAAW,gBAAgB,aAAa;KACxC,OAAO;IACT;IACA,aAAa;IACb;IACA;IACA;GACF,CAAC;EACH;CACF;AACF;AAEA,SAAS,wBACP,gBACA,cACU;CACV,MAAM,wBAAQ,IAAI,IAAY;CAE9B,KAAK,MAAM,CAAC,KAAK,aAAa,eAAe,QAAQ,GAAG;EACtD,IAAI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AO,WAAW,OAAO,cAAc,OAAO;AAChE;;;;;;;;;AC/IA,eAAe,eAAe,QAAkC;CAE9D,OAAO,EAAC,OAAA,GAAA,YAAA,MAAA,CADkB,MAAM,EAAA,CAClB,eAAe;AAC/B;AAEA,eAAe,iBACb,OACA,eACA,WACA,UACe;CACf,IAAI,MAAM,kBAAkB;EAC1B,MAAM,eAAA,GAAA,KAAA,KAAA,CAAmB,WAAW,aAAa,GAAG,cAAc,MAAM,GAAG,CAAC;EAC5E,OAAA,GAAA,YAAA,MAAA,CAAY,aAAa,EAAE,WAAW,KAAK,CAAC;EAC5C,OAAA,GAAA,YAAA,GAAA,CAAS,MAAM,kBAAkB,aAAa;GAAE,WAAW;GAAM,QAAQ;EAAe,CAAC;EACzF,SAAS,KAAK,aAAa;CAC7B;CAGA,KAAK,MAAM,SAAS,MAAM,aAAa,CAAC,GACtC,MAAM,iBAAiB,OAAO,GAAG,cAAc,GAAG,MAAM,QAAQ,WAAW,QAAQ;AAEvF;;;;;;;;;;;;;;;AAgBA,eAAsB,wBAAwB,WAAmB,WAAsC;CACrG,MAAM,SAAS,MAAM,iBAAiB,SAAS;CAC/C,MAAM,WAAqB,CAAC;CAE5B,KAAK,MAAM,SAAS,QAClB,MAAM,iBAAiB,OAAO,MAAM,MAAM,WAAW,QAAQ;CAG/D,OAAO;AACT"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"build-xd6t8qiR.js","names":["getBundlerInputOptions"],"sources":["../src/build/plugins/workspace-deps-watcher.ts","../src/build/watcher.ts","../src/build/analyzeEntryProjectType.ts","../src/build/serverOptions.ts","../src/build/fs-routing/discover.ts","../src/build/fs-routing/codegen.ts","../src/build/fs-routing/prepare.ts","../src/build/fs-routing/mirror.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { stat } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport type { Plugin } from 'rollup';\nimport { glob } from 'tinyglobby';\nimport type { WorkspacePackageInfo } from '../../bundler/workspaceDependencies';\nimport { bundleExternals } from '../analyze/bundleExternals';\nimport type { BundlerOptions, DependencyMetadata } from '../types';\nimport type { BundlerPlatform } from '../utils';\nimport { getCompiledDepCachePath, getPackageName, slash } from '../utils';\n\nconst SOURCE_GLOBS = ['**/*.{ts,tsx,js,jsx,mjs,cjs,json}'];\nconst SOURCE_IGNORE = ['**/node_modules/**', '**/.cache/**'];\n\nexport type WorkspaceDepsWatcherOptions = {\n depsToOptimize: Map<string, DependencyMetadata>;\n /**\n * Optimized dependency → relative cache file path (from analyzeBundle.dependencies).\n * Used to detect missing cache files that must be regenerated.\n */\n optimizedDependencyFiles: Map<string, string>;\n workspaceMap: Map<string, WorkspacePackageInfo>;\n workspaceRoot: string;\n outputDir: string;\n platform: BundlerPlatform;\n bundlerOptions?: Pick<BundlerOptions, 'externals' | 'enableSourcemap' | 'dynamicPackages'> | null;\n};\n\n/**\n * During `mastra dev`, workspace packages are pre-transpiled into\n * `<pkg>/node_modules/.cache/*.mjs` and marked external in the main Rollup\n * watch graph. This plugin:\n * 1. Watches the original workspace package sources so edits trigger rebuilds.\n * 2. Regenerates the optimized `.cache` outputs when those sources change (or\n * when cache files are missing) before the rebuild finishes — so a later\n * server restart loads fresh package code.\n */\nexport function workspaceDepsWatcher(options: WorkspaceDepsWatcherOptions): Plugin {\n const { depsToOptimize, optimizedDependencyFiles, workspaceMap, workspaceRoot, outputDir, platform, bundlerOptions } =\n options;\n\n let isFirstBuild = true;\n\n const usedPackageRoots = collectUsedPackageRoots(depsToOptimize, workspaceMap);\n const cachePaths = collectAbsoluteCachePaths(optimizedDependencyFiles, workspaceRoot);\n\n return {\n name: 'workspace-deps-watcher',\n async buildStart() {\n const sourceFiles = await discoverWorkspaceSourceFiles(usedPackageRoots);\n\n for (const file of sourceFiles) {\n this.addWatchFile(resolve(file));\n }\n\n // Initial optimize already ran in getWatcherInputOptions / analyzeBundle.\n if (isFirstBuild) {\n isFirstBuild = false;\n return;\n }\n\n const needsReoptimize = await isWorkspaceOutputStale(sourceFiles, cachePaths);\n\n if (!needsReoptimize) {\n return;\n }\n\n // bundleExternals may mutate the map when externalsPreset is true; copy first.\n const depsCopy = cloneDepsToOptimize(depsToOptimize);\n\n await bundleExternals(depsCopy, outputDir, {\n bundlerOptions: {\n ...bundlerOptions,\n externals: bundlerOptions?.externals ?? true,\n isDev: true,\n },\n projectRoot: workspaceRoot,\n workspaceRoot,\n workspaceMap,\n platform,\n });\n },\n };\n}\n\nfunction collectUsedPackageRoots(\n depsToOptimize: Map<string, DependencyMetadata>,\n workspaceMap: Map<string, WorkspacePackageInfo>,\n): string[] {\n const roots = new Set<string>();\n\n for (const [dep, metadata] of depsToOptimize.entries()) {\n if (!metadata.isWorkspace) {\n continue;\n }\n\n if (metadata.rootPath) {\n roots.add(slash(metadata.rootPath));\n continue;\n }\n\n const pkgName = getPackageName(dep);\n const location = pkgName ? workspaceMap.get(pkgName)?.location : undefined;\n if (location) {\n roots.add(slash(location));\n }\n }\n\n return Array.from(roots);\n}\n\nfunction collectAbsoluteCachePaths(optimizedDependencyFiles: Map<string, string>, workspaceRoot: string): string[] {\n return Array.from(optimizedDependencyFiles.values()).map(relativePath => resolve(workspaceRoot, relativePath));\n}\n\nasync function discoverWorkspaceSourceFiles(packageRoots: string[]): Promise<string[]> {\n if (packageRoots.length === 0) {\n return [];\n }\n\n const files = await Promise.all(\n packageRoots.map(root =>\n glob(SOURCE_GLOBS, {\n cwd: root,\n absolute: true,\n ignore: SOURCE_IGNORE,\n onlyFiles: true,\n }),\n ),\n );\n\n return files.flat();\n}\n\nasync function isCacheMissing(cachePaths: string[]): Promise<boolean> {\n for (const cachePath of cachePaths) {\n if (!existsSync(cachePath)) {\n return true;\n }\n }\n return false;\n}\n\nasync function isWorkspaceOutputStale(sourceFiles: string[], cachePaths: string[]): Promise<boolean> {\n if (await isCacheMissing(cachePaths)) {\n return true;\n }\n\n let cacheBaselineMs = 0;\n for (const cachePath of cachePaths) {\n try {\n const { mtimeMs } = await stat(cachePath);\n cacheBaselineMs = Math.max(cacheBaselineMs, mtimeMs);\n } catch {\n return true;\n }\n }\n\n for (const file of sourceFiles) {\n try {\n const { mtimeMs } = await stat(file);\n if (mtimeMs > cacheBaselineMs) {\n return true;\n }\n } catch {\n // File may have been deleted; treat as dirty so we re-optimize.\n return true;\n }\n }\n\n return false;\n}\n\nfunction cloneDepsToOptimize(deps: Map<string, DependencyMetadata>): Map<string, DependencyMetadata> {\n const copy = new Map<string, DependencyMetadata>();\n for (const [dep, metadata] of deps.entries()) {\n copy.set(dep, {\n ...metadata,\n exports: [...metadata.exports],\n });\n }\n return copy;\n}\n\n/**\n * On-disk cache entry path for a workspace dependency after optimization.\n * Naming matches createVirtualDependencies: dep.replaceAll('/', '__').\n */\nexport function getWorkspaceDepCacheEntryPath(rootPath: string, dep: string): string {\n const fileName = dep.replaceAll('/', '__');\n return `${getCompiledDepCachePath(rootPath, fileName)}.mjs`;\n}\n","import { dirname, posix } from 'node:path';\nimport { noopLogger } from '@mastra/core/logger';\nimport * as pkg from 'empathic/package';\nimport type { InputOptions, OutputOptions, Plugin } from 'rollup';\nimport { watch } from 'rollup';\nimport { getWorkspaceInformation } from '../bundler/workspaceDependencies';\nimport { analyzeBundle } from './analyze';\nimport { getInputOptions as getBundlerInputOptions } from './bundler';\nimport { aliasHono } from './plugins/hono-alias';\nimport { nodeModulesExtensionResolver } from './plugins/node-modules-extension-resolver';\nimport { tsConfigPaths } from './plugins/tsconfig-paths';\nimport { workspaceDepsWatcher } from './plugins/workspace-deps-watcher';\nimport type { BundlerOptions } from './types';\nimport { getPackageName, slash } from './utils';\nimport type { BundlerPlatform } from './utils';\n\nexport async function getInputOptions(\n entryFile: string,\n platform: BundlerPlatform,\n env?: Record<string, string>,\n {\n sourcemap = false,\n bundlerOptions = {\n enableSourcemap: false,\n enableEsmShim: true,\n externals: true,\n },\n analysisEntries = [entryFile],\n }: { sourcemap?: boolean; bundlerOptions?: BundlerOptions; analysisEntries?: string[] } = {},\n) {\n const closestPkgJson = pkg.up({ cwd: dirname(entryFile) });\n const projectRoot = closestPkgJson ? dirname(slash(closestPkgJson)) : slash(process.cwd());\n const { workspaceMap, workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile: entryFile });\n\n const outputDir = posix.join(process.cwd(), '.mastra', '.build');\n\n const analyzeEntryResult = await analyzeBundle(\n analysisEntries,\n entryFile,\n {\n outputDir,\n projectRoot: workspaceRoot || process.cwd(),\n platform,\n isDev: true,\n bundlerOptions,\n },\n noopLogger,\n );\n\n const deps = /* @__PURE__ */ new Map();\n for (const [dep, metadata] of analyzeEntryResult.dependencies.entries()) {\n const pkgName = getPackageName(dep);\n if (pkgName && workspaceMap.has(pkgName)) {\n deps.set(dep, metadata);\n }\n }\n\n const inputOptions = await getBundlerInputOptions(\n entryFile,\n {\n dependencies: deps,\n externalDependencies: new Map(),\n workspaceMap,\n },\n platform,\n env,\n { sourcemap, isDev: true, workspaceRoot, projectRoot, externalsPreset: bundlerOptions?.externals === true },\n );\n\n if (Array.isArray(inputOptions.plugins)) {\n // filter out node-resolve plugin so all node_modules are external\n // and tsconfig-paths plugin as we are injection a custom one\n const plugins = [] as Plugin[];\n inputOptions.plugins.forEach(plugin => {\n if ((plugin as Plugin | undefined)?.name === 'node-resolve') {\n return;\n }\n\n if ((plugin as Plugin | undefined)?.name === 'tsconfig-paths') {\n plugins.push(\n tsConfigPaths({\n localResolve: true,\n }),\n );\n return;\n }\n\n plugins.push(plugin as Plugin);\n });\n\n inputOptions.plugins = plugins;\n inputOptions.plugins.push(aliasHono());\n // fixes imports like lodash/fp/get\n inputOptions.plugins.push(nodeModulesExtensionResolver());\n\n const depsToOptimize = analyzeEntryResult.depsToOptimize;\n const resolvedWorkspaceRoot = analyzeEntryResult.workspaceRoot || workspaceRoot;\n if (depsToOptimize?.size && resolvedWorkspaceRoot) {\n inputOptions.plugins.push(\n workspaceDepsWatcher({\n depsToOptimize,\n optimizedDependencyFiles: deps,\n workspaceMap,\n workspaceRoot: resolvedWorkspaceRoot,\n outputDir: analyzeEntryResult.outputDir || outputDir,\n platform,\n bundlerOptions,\n }),\n );\n }\n }\n\n return inputOptions;\n}\n\nexport async function createWatcher(inputOptions: InputOptions, outputOptions: OutputOptions) {\n const watcher = await watch({\n ...inputOptions,\n output: {\n ...outputOptions,\n format: 'esm',\n entryFileNames: '[name].mjs',\n chunkFileNames: '[name].mjs',\n },\n });\n\n return watcher;\n}\n","import { readFile } from 'node:fs/promises';\nimport { transformAsync } from '@babel/core';\nimport { checkConfigExport } from './babel/check-config-export';\n\n/**\n * Lightweight entry analysis that returns the detected project type by running\n * only the Babel check-config-export plugin on the Mastra entry file. This is\n * intentionally cheaper than `analyzeBundle` and is used by the CLI before\n * `prepare()` clears `.mastra` to decide whether Factory-specific assets\n * should be copied.\n *\n * Returns `'factory'` when the entry imports `MastraFactory` and\n * constructs it, or `undefined` for ordinary Mastra projects.\n */\nexport async function analyzeEntryProjectType(mastraEntry: string): Promise<string | undefined> {\n const code = await readFile(mastraEntry, 'utf-8');\n const result: { hasValidConfig: boolean; projectType?: string } = { hasValidConfig: false };\n\n await transformAsync(code, {\n filename: mastraEntry,\n presets: [import.meta.resolve('@babel/preset-typescript')],\n plugins: [() => checkConfigExport(result)],\n });\n\n return result.projectType;\n}\n","import type { IMastraLogger } from '@mastra/core/logger';\nimport type { Config } from '@mastra/core/mastra';\nimport { extractMastraOption, extractMastraOptionBundler } from './shared/extract-mastra-option';\n\nexport function getServerOptionsBundler(\n entryFile: string,\n result: {\n hasCustomConfig: false;\n },\n) {\n return extractMastraOptionBundler('server', entryFile, result);\n}\n\nexport async function getServerOptions(\n entryFile: string,\n outputDir: string,\n logger?: IMastraLogger,\n): Promise<Config['server'] | null> {\n const result = await extractMastraOption('server', entryFile, outputDir, logger);\n if (!result) {\n return null;\n }\n\n return result.getConfig();\n}\n","import { lstat, readdir, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { MAX_FS_SUBAGENT_DEPTH } from '@mastra/core/agent';\nimport type { AgentSchedulePromptDefinition } from '@mastra/core/schedules';\nimport matter from 'gray-matter';\nimport { slash } from '../utils';\n\n/**\n * A file-system routed agent directory discovered under `<mastraDir>/agents/`.\n * All paths are absolute and slash-normalized so they can be embedded into\n * generated module source on any platform.\n */\nexport interface DiscoveredFsAgent {\n /** Agent directory name. Used as the default `id`/`name`. */\n name: string;\n /** Absolute, slash-normalized path to the agent directory. */\n dir: string;\n /** Absolute path to `config.ts`/`config.js`, if present. */\n configPath?: string;\n /** Absolute path to `instructions.md`, if present. */\n instructionsPath?: string;\n /** Absolute path to `workspace.ts`/`workspace.js`, if present. */\n workspacePath?: string;\n /** Absolute path to `memory.ts`/`memory.js`, if present. */\n memoryPath?: string;\n /**\n * Absolute, slash-normalized path to an authored `workspace/` directory of\n * seed files, if present. These are mirrored into the deployed workspace at\n * build time (Eve parity) so the agent starts with them on disk.\n */\n workspaceSeedDir?: string;\n /** Tools discovered under `tools/`, in stable (sorted) order. */\n tools: { key: string; path: string }[];\n /** Input processors discovered under `processors/input/`, in stable (sorted) order. */\n inputProcessors: { key: string; path: string }[];\n /** Output processors discovered under `processors/output/`, in stable (sorted) order. */\n outputProcessors: { key: string; path: string }[];\n /** Scorers discovered under `scorers/`, in stable (sorted) order. */\n scorers: { key: string; path: string }[];\n /** Skills discovered under `skills/`, in stable (sorted) order. */\n skills: DiscoveredFsSkill[];\n /**\n * Schedules discovered under `schedules/`, in stable (path-sorted) order.\n * Nested files keep their relative path in `key` (`billing/sweep.ts` →\n * `billing/sweep`) so a schedule's identity is stable across builds.\n */\n schedules: DiscoveredFsSchedule[];\n /**\n * Declared subagents discovered under `subagents/`, in stable (sorted) order.\n * Subagents may declare their own `subagents/`, up to `MAX_FS_SUBAGENT_DEPTH`\n * levels below the top-level agent; deeper `subagents/` directories are\n * ignored with a warning.\n */\n subagents: DiscoveredFsAgent[];\n}\n\n/**\n * A skill discovered under `agents/<name>/skills/`.\n *\n * - `kind: 'module'` — a `.ts`/`.js` file whose default export is a `createSkill(...)`\n * result. Codegen imports it directly; `name`/`description`/`instructions` are\n * unknown at discovery time and resolved at runtime from the module.\n * - `kind: 'packaged'` — a `SKILL.md` (optionally with a `references/` subdir) or a\n * flat `<skill>.md`. Codegen inlines it via `createSkill(...)` using the parsed\n * fields below so the deployed bundle carries no filesystem dependency.\n */\nexport type DiscoveredFsSkill =\n | {\n kind: 'module';\n /** Absolute, slash-normalized path to the `.ts`/`.js` skill module. */\n path: string;\n }\n | {\n kind: 'packaged';\n name: string;\n description: string;\n instructions: string;\n /** Reference file contents keyed by relative path (from `references/`). */\n references: Record<string, string>;\n };\n\n/**\n * A schedule discovered under `agents/<name>/schedules/`.\n *\n * - `kind: 'module'` — a `.ts`/`.js` file whose default export is a\n * `defineSchedule(...)` result. Codegen imports it directly, which is what\n * makes handler mode possible: the handler is a live function, not data.\n * - `kind: 'markdown'` — a `.md` file with cron frontmatter and the document\n * body as the prompt. Codegen inlines it so the bundle carries no filesystem\n * dependency.\n */\nexport type DiscoveredFsSchedule =\n | {\n kind: 'module';\n /** Path-derived identity relative to `schedules/`, extension stripped. */\n key: string;\n /** Absolute, slash-normalized path to the `.ts`/`.js` schedule module. */\n path: string;\n }\n | {\n kind: 'markdown';\n key: string;\n /**\n * Absolute, slash-normalized path to the `.md` file. Its contents are\n * inlined at build time, so the dev watcher has to watch this path\n * explicitly — nothing imports it.\n */\n path: string;\n /** Parsed frontmatter fields plus the body as `prompt`. */\n definition: MarkdownScheduleDefinition;\n };\n\n/**\n * A markdown schedule is always prompt mode — the document body is the prompt\n * and handler mode needs a function, so it needs a `.ts`/`.js` module. Reuses core's\n * definition type so the two can't drift; core validates the parsed result\n * during agent assembly.\n */\nexport type MarkdownScheduleDefinition = AgentSchedulePromptDefinition;\n\n/**\n * Frontmatter keys a markdown schedule may set, in the order they are copied\n * onto the definition. Anything outside this list fails the build rather than\n * being silently dropped — a schedule that quietly ignores half its config is\n * worse than one that refuses to build.\n *\n * The `satisfies` binds this list to core's definition type, so renaming or\n * removing a field there breaks the build here instead of silently rejecting\n * frontmatter that used to be valid. (`prompt` is excluded because the document\n * body supplies it, `handler` because markdown can't carry a function.)\n */\nconst MARKDOWN_SCHEDULE_KEYS = [\n 'cron',\n 'timezone',\n 'name',\n 'threadId',\n 'resourceId',\n 'signalType',\n 'tagName',\n 'attributes',\n 'providerOptions',\n 'ifActive',\n 'ifIdle',\n 'status',\n 'metadata',\n] as const satisfies readonly (keyof Omit<AgentSchedulePromptDefinition, 'prompt' | 'handler'>)[];\n\nconst CONFIG_BASENAMES = ['config.ts', 'config.js'];\nconst WORKSPACE_BASENAMES = ['workspace.ts', 'workspace.js'];\nconst MEMORY_BASENAMES = ['memory.ts', 'memory.js'];\nconst INSTRUCTIONS_BASENAME = 'instructions.md';\nconst TOOL_EXTENSIONS = ['.ts', '.js'];\nconst SCHEDULE_MODULE_EXTENSIONS = ['.ts', '.js'];\nconst SKILL_MODULE_EXTENSIONS = ['.ts', '.js'];\nconst SKILL_MD_BASENAME = 'SKILL.md';\n\n/**\n * Presence check that does NOT follow symlinks. Returns `false` for symlinks\n * (and broken links) so a symlinked `config.ts`/`instructions.md`/`workspace.ts`/\n * `memory.ts` is never inlined or imported into the generated bundle.\n */\nasync function exists(path: string): Promise<boolean> {\n try {\n return !(await lstat(path)).isSymbolicLink();\n } catch {\n return false;\n }\n}\n\n/**\n * Returns the slash-normalized path when `path` is a real directory (not a\n * symlink). Symlinked directories are rejected to prevent the build from\n * following links out of the project tree during discovery.\n */\nasync function realDirectory(path: string): Promise<string | undefined> {\n try {\n const info = await lstat(path);\n if (info.isDirectory() && !info.isSymbolicLink()) {\n return slash(path);\n }\n } catch {\n // not present\n }\n return undefined;\n}\n\nasync function directoryExists(path: string): Promise<string | undefined> {\n return realDirectory(path);\n}\n\nasync function firstExisting(dir: string, basenames: string[]): Promise<string | undefined> {\n for (const basename of basenames) {\n const candidate = join(dir, basename);\n if (await exists(candidate)) {\n return slash(candidate);\n }\n }\n return undefined;\n}\n\nfunction isTestFile(basename: string): boolean {\n return /\\.(test|spec)\\.(ts|js)$/.test(basename);\n}\n\nfunction toolKey(basename: string): string {\n return basename.replace(/\\.(ts|js)$/, '');\n}\n\n/**\n * Discover default-exporting `.ts`/`.js` modules directly under `dir`, returning\n * `{ key, path }` entries in stable (sorted) order. Test files, symlinks, and\n * subdirectories are skipped: a symlinked module could point anywhere on the\n * build machine and be embedded into generated import code. Shared by the\n * `tools/` and `scorers/` scanners.\n */\nasync function discoverModuleDir(dir: string): Promise<{ key: string; path: string }[]> {\n if (!(await exists(dir))) {\n return [];\n }\n\n let entries: string[];\n try {\n entries = await readdir(dir);\n } catch {\n return [];\n }\n\n const modules: { key: string; path: string }[] = [];\n for (const basename of entries.sort()) {\n if (isTestFile(basename)) {\n continue;\n }\n if (!TOOL_EXTENSIONS.some(ext => basename.endsWith(ext))) {\n continue;\n }\n const path = join(dir, basename);\n // Use lstat so symlinks are detected (not followed). Skip symlinks and\n // directories: a symlinked module file could point anywhere on the build\n // machine and be embedded into generated import code.\n const stats = await lstat(path);\n if (stats.isSymbolicLink() || stats.isDirectory()) {\n continue;\n }\n modules.push({ key: toolKey(basename), path: slash(path) });\n }\n\n return modules;\n}\n\nasync function discoverTools(toolsDir: string): Promise<DiscoveredFsAgent['tools']> {\n return discoverModuleDir(toolsDir);\n}\n\nasync function discoverProcessors(\n processorsDir: string,\n): Promise<{ input: { key: string; path: string }[]; output: { key: string; path: string }[] }> {\n const result = { input: [] as { key: string; path: string }[], output: [] as { key: string; path: string }[] };\n\n for (const type of ['input', 'output'] as const) {\n const typeDir = join(processorsDir, type);\n if (!(await exists(typeDir))) {\n continue;\n }\n\n let entries: string[];\n try {\n entries = await readdir(typeDir);\n } catch {\n continue;\n }\n\n for (const basename of entries.sort()) {\n if (isTestFile(basename)) {\n continue;\n }\n if (!TOOL_EXTENSIONS.some(ext => basename.endsWith(ext))) {\n continue;\n }\n const path = join(typeDir, basename);\n const stats = await lstat(path);\n if (stats.isSymbolicLink() || stats.isDirectory()) {\n continue;\n }\n result[type].push({ key: toolKey(basename), path: slash(path) });\n }\n }\n\n return result;\n}\n\nasync function readReferences(referencesDir: string): Promise<Record<string, string>> {\n if (!(await exists(referencesDir))) {\n return {};\n }\n const references: Record<string, string> = {};\n let entries: string[];\n try {\n entries = await readdir(referencesDir);\n } catch {\n return {};\n }\n for (const basename of entries.sort()) {\n const path = join(referencesDir, basename);\n // Use lstat so symlinks are detected (not followed). Skip symlinks: a\n // symlink under `references/` could point anywhere on the build machine and\n // silently embed arbitrary file contents into the generated bundle.\n const stats = await lstat(path);\n if (stats.isSymbolicLink() || stats.isDirectory()) {\n continue;\n }\n references[basename] = await readFile(path, 'utf-8');\n }\n return references;\n}\n\nasync function parsePackagedSkill(\n skillMdPath: string,\n fallbackName: string,\n references: Record<string, string> = {},\n): Promise<Extract<DiscoveredFsSkill, { kind: 'packaged' }>> {\n const raw = await readFile(skillMdPath, 'utf-8');\n const parsed = matter(raw);\n const frontmatter = parsed.data as { name?: string; description?: string };\n const name = frontmatter.name ?? fallbackName;\n const description = frontmatter.description;\n\n if (!description) {\n throw new Error(\n `Skill \"${name}\" in ${skillMdPath} is missing a required \"description\". ` +\n `Add a YAML frontmatter block with a \"description:\" field. ` +\n `See https://agentskills.io/specification for the SKILL.md format.`,\n );\n }\n\n const instructions = parsed.content.trim();\n return { kind: 'packaged', name, description, instructions, references };\n}\n\nfunction skillModuleName(basename: string): string {\n return basename.replace(/\\.(ts|js)$/, '');\n}\n\nasync function discoverSkills(skillsDir: string): Promise<DiscoveredFsSkill[]> {\n if (!(await exists(skillsDir))) {\n return [];\n }\n\n let entries: string[];\n try {\n entries = await readdir(skillsDir);\n } catch {\n return [];\n }\n\n const skills: DiscoveredFsSkill[] = [];\n for (const basename of entries.sort()) {\n if (isTestFile(basename)) {\n continue;\n }\n const path = join(skillsDir, basename);\n // Use lstat so symlinks are detected (not followed). Skip symlinks: a\n // symlinked skill module/markdown could point anywhere on the build machine\n // and be bundled or inlined into the generated output.\n const stats = await lstat(path);\n if (stats.isSymbolicLink()) {\n continue;\n }\n const isDir = stats.isDirectory();\n\n // Packaged skill directory: <skill>/SKILL.md (+ references/)\n if (isDir) {\n const skillMd = join(path, SKILL_MD_BASENAME);\n if (await exists(skillMd)) {\n const references = await readReferences(join(path, 'references'));\n skills.push(await parsePackagedSkill(skillMd, skillModuleName(basename), references));\n }\n continue;\n }\n\n // createSkill module: <skill>.ts | <skill>.js\n if (SKILL_MODULE_EXTENSIONS.some(ext => basename.endsWith(ext))) {\n skills.push({ kind: 'module', path: slash(path) });\n continue;\n }\n\n // Flat markdown skill: <skill>.md\n if (basename.endsWith('.md')) {\n const skill = await parsePackagedSkill(path, basename.replace(/\\.md$/, ''));\n skills.push(skill);\n }\n }\n\n return skills;\n}\n\n/**\n * Parse a markdown schedule: YAML frontmatter for the cron (and other JSON-safe\n * options), document body for the prompt.\n *\n * Throws a build error naming the file when `cron` is missing or the body is\n * empty — a schedule that can't fire is never what the author meant.\n */\nasync function parseMarkdownSchedule(path: string, key: string): Promise<MarkdownScheduleDefinition> {\n const raw = await readFile(path, 'utf-8');\n\n let parsed: ReturnType<typeof matter>;\n try {\n parsed = matter(raw);\n } catch (error) {\n // The most common cron form starts with `*`, which YAML reads as an alias\n // indicator, so `cron: */5 * * * *` fails with an opaque parser error.\n // Name the actual fix instead of surfacing that raw.\n const detail = error instanceof Error ? error.message.split('\\n')[0] : String(error);\n throw new Error(\n `Schedule \"${key}\" in ${path} has invalid YAML frontmatter: ${detail}. ` +\n `Cron expressions must be quoted (cron: \"*/5 * * * *\"), because a leading \"*\" is a YAML alias.`,\n );\n }\n\n const frontmatter = (parsed.data ?? {}) as Record<string, unknown>;\n const prompt = parsed.content.trim();\n\n const unknown = Object.keys(frontmatter).filter(\n field => !(MARKDOWN_SCHEDULE_KEYS as readonly string[]).includes(field),\n );\n if (unknown.length > 0) {\n const hint = unknown.includes('prompt')\n ? ` The document body is used as the prompt, so \"prompt\" cannot be set in frontmatter.`\n : ` Supported fields: ${MARKDOWN_SCHEDULE_KEYS.join(', ')}. Handler mode requires a .ts or .js schedule.`;\n throw new Error(`Schedule \"${key}\" in ${path} has unknown frontmatter field(s): ${unknown.join(', ')}.${hint}`);\n }\n\n if (!frontmatter.cron || typeof frontmatter.cron !== 'string') {\n throw new Error(\n `Schedule \"${key}\" in ${path} is missing a required \"cron\". ` +\n `Add a YAML frontmatter block with a \"cron:\" field (e.g. cron: \"0 9 * * *\").`,\n );\n }\n\n if (!prompt) {\n throw new Error(\n `Schedule \"${key}\" in ${path} has an empty body. ` +\n `The document body is used as the prompt, so it cannot be blank.`,\n );\n }\n\n const definition: Record<string, unknown> = { cron: frontmatter.cron, prompt };\n for (const field of MARKDOWN_SCHEDULE_KEYS) {\n if (field === 'cron') continue;\n if (frontmatter[field] !== undefined) {\n definition[field] = frontmatter[field];\n }\n }\n return definition as unknown as MarkdownScheduleDefinition;\n}\n\n/**\n * Discover schedules under `agents/<name>/schedules/`, recursing into\n * subdirectories so a schedule's identity is its path relative to `schedules/`\n * with the extension stripped (`billing/sweep.ts` → `billing/sweep`).\n *\n * Test files and symlinks (files and directories alike) are skipped for the\n * same reason as the other scanners: a symlink could point anywhere on the\n * build machine and be embedded into generated import code.\n */\nasync function discoverSchedules(schedulesDir: string, prefix = ''): Promise<DiscoveredFsSchedule[]> {\n if (!(await exists(schedulesDir))) {\n return [];\n }\n\n let entries: string[];\n try {\n entries = await readdir(schedulesDir);\n } catch {\n return [];\n }\n\n const schedules: DiscoveredFsSchedule[] = [];\n for (const basename of entries.sort()) {\n const path = join(schedulesDir, basename);\n\n let stats;\n try {\n stats = await lstat(path);\n } catch {\n continue;\n }\n if (stats.isSymbolicLink()) {\n continue;\n }\n\n if (stats.isDirectory()) {\n schedules.push(...(await discoverSchedules(path, `${prefix}${basename}/`)));\n continue;\n }\n\n if (isTestFile(basename)) {\n continue;\n }\n\n if (SCHEDULE_MODULE_EXTENSIONS.some(ext => basename.endsWith(ext))) {\n schedules.push({\n kind: 'module',\n key: `${prefix}${basename.replace(/\\.(ts|js)$/, '')}`,\n path: slash(path),\n });\n continue;\n }\n\n if (basename.endsWith('.md')) {\n const key = `${prefix}${basename.replace(/\\.md$/, '')}`;\n schedules.push({\n kind: 'markdown',\n key,\n path: slash(path),\n definition: await parseMarkdownSchedule(path, key),\n });\n }\n }\n\n // Sort by key, not by traversal order. Sorting basenames only orders each\n // directory: given `a.ts` alongside a directory `a/`, `a` sorts before\n // `a.ts`, so recursion emits `a/job` before `a`. Codegen order follows this\n // list, so a global sort is what actually makes it path-sorted and stable.\n return schedules.sort((left, right) => (left.key < right.key ? -1 : left.key > right.key ? 1 : 0));\n}\n\n/**\n * Discover a single agent directory: its `config`/`instructions`/`workspace`\n * files plus `tools/`, `skills/`, and declared `subagents/`. Returns\n * `undefined` when `dir` is not an agent directory (no `config.(ts|js)` and no\n * `instructions.md`).\n *\n * `depth` is the subagent nesting level (`0` for top-level agents). Discovery\n * recurses into `subagents/` until `MAX_FS_SUBAGENT_DEPTH`; deeper directories\n * are ignored with a warning.\n */\nasync function discoverAgentDir(\n dir: string,\n name: string,\n depth: number,\n onWarn?: (message: string) => void,\n): Promise<DiscoveredFsAgent | undefined> {\n const configPath = await firstExisting(dir, CONFIG_BASENAMES);\n const instructionsPath = (await exists(join(dir, INSTRUCTIONS_BASENAME)))\n ? slash(join(dir, INSTRUCTIONS_BASENAME))\n : undefined;\n\n // Not an agent directory unless it has a config or instructions file.\n if (!configPath && !instructionsPath) {\n return undefined;\n }\n\n const workspacePath = await firstExisting(dir, WORKSPACE_BASENAMES);\n const memoryPath = await firstExisting(dir, MEMORY_BASENAMES);\n const workspaceSeedDir = await directoryExists(join(dir, 'workspace'));\n const tools = await discoverTools(join(dir, 'tools'));\n const processors = await discoverProcessors(join(dir, 'processors'));\n const scorers = await discoverModuleDir(join(dir, 'scorers'));\n const skills = await discoverSkills(join(dir, 'skills'));\n const schedules = await discoverSchedules(join(dir, 'schedules'));\n const subagents = await discoverSubagents(dir, depth, onWarn);\n\n return {\n name,\n dir: slash(dir),\n configPath,\n instructionsPath,\n workspacePath,\n memoryPath,\n workspaceSeedDir,\n tools,\n inputProcessors: processors.input,\n outputProcessors: processors.output,\n scorers,\n skills,\n schedules,\n subagents,\n };\n}\n\n/**\n * Discover declared subagents under `<dir>/subagents/*`. `parentDepth` is the\n * parent agent's nesting level (`0` for top-level agents). Discovery recurses\n * until `MAX_FS_SUBAGENT_DEPTH` levels of subagents; a `subagents/` directory\n * that would exceed the cap is skipped with a warning.\n */\nasync function discoverSubagents(\n parentDir: string,\n parentDepth: number,\n onWarn?: (message: string) => void,\n): Promise<DiscoveredFsAgent[]> {\n const subagentsDir = join(parentDir, 'subagents');\n if (!(await exists(subagentsDir))) {\n return [];\n }\n\n if (parentDepth >= MAX_FS_SUBAGENT_DEPTH) {\n onWarn?.(\n `Ignoring subagents in \"${slash(subagentsDir)}\": subagents may only nest ${MAX_FS_SUBAGENT_DEPTH} levels below a top-level agent.`,\n );\n return [];\n }\n\n let entries: string[];\n try {\n entries = await readdir(subagentsDir);\n } catch {\n return [];\n }\n\n const subagents: DiscoveredFsAgent[] = [];\n for (const name of entries.sort()) {\n const dir = join(subagentsDir, name);\n if (!(await realDirectory(dir))) {\n continue;\n }\n const child = await discoverAgentDir(dir, name, parentDepth + 1, onWarn);\n if (child) {\n subagents.push(child);\n }\n }\n\n return subagents;\n}\n\n/**\n * Scan `<mastraDir>/agents/*` for file-system routed agents. A directory is\n * treated as an agent only when it contains a `config.(ts|js)` or an\n * `instructions.md`; other directories are ignored. Each agent may declare\n * `subagents/` up to `MAX_FS_SUBAGENT_DEPTH` levels deep. Returns descriptors\n * with absolute, slash-normalized paths ready for codegen. Performs no module\n * evaluation — only filesystem inspection.\n */\nexport async function discoverFsAgents(\n mastraDir: string,\n onWarn?: (message: string) => void,\n): Promise<DiscoveredFsAgent[]> {\n const agentsDir = join(mastraDir, 'agents');\n if (!(await exists(agentsDir))) {\n return [];\n }\n\n let entries: string[];\n try {\n entries = await readdir(agentsDir);\n } catch {\n return [];\n }\n\n const discovered: DiscoveredFsAgent[] = [];\n for (const name of entries.sort()) {\n const dir = join(agentsDir, name);\n if (!(await realDirectory(dir))) {\n continue;\n }\n const agent = await discoverAgentDir(dir, name, 0, onWarn);\n if (agent) {\n discovered.push(agent);\n }\n }\n\n return discovered;\n}\n\n/**\n * A file-system routed workflow file discovered under `<mastraDir>/workflows/`.\n * All paths are absolute and slash-normalized so they can be embedded into\n * generated module source on any platform.\n */\nexport interface DiscoveredFsWorkflow {\n /** Workflow key derived from the filename (without extension). */\n key: string;\n /** Absolute, slash-normalized path to the workflow module. */\n path: string;\n}\n\n/**\n * Scan `<mastraDir>/workflows/` for file-system routed workflow modules. Only\n * files whose source contains an `export default` are treated as fs-routed\n * workflows — this convention distinguishes them from workflow files that are\n * manually imported and registered programmatically. Returns descriptors with\n * absolute, slash-normalized paths ready for codegen. Performs no module\n * evaluation — only filesystem and source-text inspection.\n */\nexport async function discoverFsWorkflows(mastraDir: string): Promise<DiscoveredFsWorkflow[]> {\n const workflowsDir = join(mastraDir, 'workflows');\n if (!(await exists(workflowsDir))) {\n return [];\n }\n\n let entries: string[];\n try {\n entries = await readdir(workflowsDir);\n } catch {\n return [];\n }\n\n const discovered: DiscoveredFsWorkflow[] = [];\n for (const basename of entries.sort()) {\n if (isTestFile(basename)) {\n continue;\n }\n if (!TOOL_EXTENSIONS.some(ext => basename.endsWith(ext))) {\n continue;\n }\n const path = join(workflowsDir, basename);\n const stats = await lstat(path);\n if (stats.isSymbolicLink() || stats.isDirectory()) {\n continue;\n }\n // Convention: only files with `export default` are fs-routed workflows.\n // Files using named exports are assumed to be manually imported.\n const source = await readFile(path, 'utf-8');\n if (!/\\bexport\\s+default\\b/.test(source)) {\n continue;\n }\n discovered.push({ key: toolKey(basename), path: slash(path) });\n }\n\n return discovered;\n}\n\n/**\n * A discovered singleton config file under `<mastraDir>/`. All paths are\n * absolute and slash-normalized so they can be embedded into generated module\n * source on any platform.\n */\nexport interface DiscoveredFsSingleton {\n /** Absolute, slash-normalized path to the singleton module. */\n path: string;\n}\n\nconst SINGLETON_EXTENSIONS = ['.ts', '.js', '.mts', '.mjs'];\n\n/** Safe singleton identifier: no path separators, `..`, or other traversal. */\nconst SINGLETON_NAME_PATTERN = /^[a-zA-Z0-9_-]+$/;\n\n/**\n * Check for a singleton config file (e.g. `storage.ts`, `storage.js`) directly\n * under `<mastraDir>`. Returns the first matching file path or `undefined`.\n * Symlinks are rejected for security.\n *\n * Convention: only files with `export default` are fs-routed singletons. Files\n * using named exports are assumed to be manually imported into the user's\n * `index.ts`, so they are ignored to remain backward-compatible with existing\n * project structures.\n *\n * `name` must be a bare identifier — path separators and traversal sequences are\n * rejected so the lookup can never escape `<mastraDir>`.\n */\nexport async function discoverFsSingleton(mastraDir: string, name: string): Promise<DiscoveredFsSingleton | undefined> {\n if (!SINGLETON_NAME_PATTERN.test(name)) {\n throw new Error(`Invalid fs-singleton name ${JSON.stringify(name)}: expected a bare identifier.`);\n }\n\n for (const ext of SINGLETON_EXTENSIONS) {\n const candidate = join(mastraDir, `${name}${ext}`);\n try {\n const stats = await lstat(candidate);\n if (!stats.isFile() || stats.isSymbolicLink()) {\n continue;\n }\n const source = await readFile(candidate, 'utf-8');\n // Only files with a default export are fs-routed. A named-export file with\n // this name is user-managed, so skip it and keep scanning other extensions.\n if (!/\\bexport\\s+default\\b/.test(source)) {\n continue;\n }\n return { path: slash(candidate) };\n } catch {\n // not present\n }\n }\n return undefined;\n}\n","import { readFile } from 'node:fs/promises';\nimport type { DiscoveredFsAgent, DiscoveredFsSingleton, DiscoveredFsWorkflow } from './discover';\n\nfunction sanitizeIdentifier(name: string, prefix: string, index: string): string {\n const cleaned = name.replace(/[^a-zA-Z0-9_$]/g, '_');\n return `${prefix}_${index}_${cleaned}`;\n}\n\n/**\n * Emit the imports for a single discovered agent into `lines` and return the\n * source of its `assembleAgentFromFsEntry` entry object (the `{ name, config,\n * ... }` argument). `idPath` is a dot-free, unique path index (e.g. `0` for the\n * first top-level agent, `0_1` for its second subagent) used to keep generated\n * identifiers unique across the parent/child tree. `workspaceName` is the\n * slash-joined workspace key (`<parent>/<child>` for subagents) so seed files\n * don't collide. Discovered subagents are emitted recursively as a nested\n * `subagents: [...]` field (discovery already enforces the depth cap).\n */\nasync function emitAgentEntry(\n agent: DiscoveredFsAgent,\n idPath: string,\n workspaceName: string,\n lines: string[],\n): Promise<string> {\n const configIdent = sanitizeIdentifier(agent.name, 'config', idPath);\n const toolIdents: { key: string; ident: string }[] = [];\n\n if (agent.configPath) {\n lines.push(`import ${configIdent} from ${JSON.stringify(agent.configPath)};`);\n }\n\n let workspaceIdent: string | undefined;\n if (agent.workspacePath) {\n workspaceIdent = sanitizeIdentifier(`${agent.name}_workspace`, 'workspace', idPath);\n lines.push(`import ${workspaceIdent} from ${JSON.stringify(agent.workspacePath)};`);\n }\n\n let memoryIdent: string | undefined;\n if (agent.memoryPath) {\n memoryIdent = sanitizeIdentifier(`${agent.name}_memory`, 'memory', idPath);\n lines.push(`import ${memoryIdent} from ${JSON.stringify(agent.memoryPath)};`);\n }\n\n for (let t = 0; t < agent.tools.length; t++) {\n const tool = agent.tools[t]!;\n const ident = sanitizeIdentifier(`${agent.name}_${tool.key}`, 'tool', `${idPath}_${t}`);\n lines.push(`import ${ident} from ${JSON.stringify(tool.path)};`);\n toolIdents.push({ key: tool.key, ident });\n }\n\n const inputProcessorIdents: string[] = [];\n for (let p = 0; p < agent.inputProcessors.length; p++) {\n const proc = agent.inputProcessors[p]!;\n const ident = sanitizeIdentifier(`${agent.name}_inputProc_${proc.key}`, 'proc', `${idPath}_ip${p}`);\n lines.push(`import ${ident} from ${JSON.stringify(proc.path)};`);\n inputProcessorIdents.push(ident);\n }\n\n const outputProcessorIdents: string[] = [];\n for (let p = 0; p < agent.outputProcessors.length; p++) {\n const proc = agent.outputProcessors[p]!;\n const ident = sanitizeIdentifier(`${agent.name}_outputProc_${proc.key}`, 'proc', `${idPath}_op${p}`);\n lines.push(`import ${ident} from ${JSON.stringify(proc.path)};`);\n outputProcessorIdents.push(ident);\n }\n\n const scorerIdents: { key: string; ident: string }[] = [];\n for (let s = 0; s < agent.scorers.length; s++) {\n const scorer = agent.scorers[s]!;\n const ident = sanitizeIdentifier(`${agent.name}_scorer_${scorer.key}`, 'scorer', `${idPath}_${s}`);\n lines.push(`import ${ident} from ${JSON.stringify(scorer.path)};`);\n scorerIdents.push({ key: scorer.key, ident });\n }\n\n // Skills: `createSkill(...)` modules are imported and used directly;\n // packaged `SKILL.md` skills are inlined via `createSkill({...})`.\n const skillExprs: string[] = [];\n const agentSkills = agent.skills ?? [];\n for (let s = 0; s < agentSkills.length; s++) {\n const skill = agentSkills[s]!;\n if (skill.kind === 'module') {\n const ident = sanitizeIdentifier(`${agent.name}_skill`, 'skill', `${idPath}_${s}`);\n lines.push(`import ${ident} from ${JSON.stringify(skill.path)};`);\n skillExprs.push(ident);\n } else {\n const referenceFields = Object.entries(skill.references).map(\n ([key, value]) => `${JSON.stringify(key)}: ${JSON.stringify(value)}`,\n );\n const skillFields = [\n `name: ${JSON.stringify(skill.name)}`,\n `description: ${JSON.stringify(skill.description)}`,\n `instructions: ${JSON.stringify(skill.instructions)}`,\n ];\n if (referenceFields.length > 0) {\n skillFields.push(`references: { ${referenceFields.join(', ')} }`);\n }\n skillExprs.push(`__createSkill({ ${skillFields.join(', ')} })`);\n }\n }\n\n // Schedules: `.ts`/`.js` modules are imported so handler-mode schedules keep\n // a live function; markdown schedules are inlined as plain data.\n const scheduleExprs: string[] = [];\n const agentSchedules = agent.schedules ?? [];\n for (let s = 0; s < agentSchedules.length; s++) {\n const schedule = agentSchedules[s]!;\n const keyField = `key: ${JSON.stringify(schedule.key)}`;\n if (schedule.kind === 'module') {\n const ident = sanitizeIdentifier(`${agent.name}_schedule`, 'schedule', `${idPath}_${s}`);\n lines.push(`import ${ident} from ${JSON.stringify(schedule.path)};`);\n scheduleExprs.push(`{ ${keyField}, schedule: ${ident} }`);\n } else {\n scheduleExprs.push(`{ ${keyField}, schedule: ${JSON.stringify(schedule.definition)} }`);\n }\n }\n\n let instructionsMd: string | undefined;\n if (agent.instructionsPath) {\n instructionsMd = await readFile(agent.instructionsPath, 'utf-8');\n }\n\n // Declared subagents. Each is itself an `assembleAgentFromFsEntry` entry\n // object, recursively carrying its own `subagents`.\n const subagentExprs: string[] = [];\n for (let c = 0; c < agent.subagents.length; c++) {\n const child = agent.subagents[c]!;\n const childExpr = await emitAgentEntry(child, `${idPath}_${c}`, `${workspaceName}/${child.name}`, lines);\n subagentExprs.push(childExpr);\n }\n\n const entryFields: string[] = [`name: ${JSON.stringify(agent.name)}`];\n if (agent.configPath) {\n entryFields.push(`config: ${configIdent}`);\n }\n if (instructionsMd !== undefined) {\n entryFields.push(`instructionsMd: ${JSON.stringify(instructionsMd)}`);\n }\n if (toolIdents.length > 0) {\n const toolEntries = toolIdents.map(({ key, ident }) => `{ key: ${JSON.stringify(key)}, tool: ${ident} }`);\n entryFields.push(`tools: [${toolEntries.join(', ')}]`);\n }\n if (skillExprs.length > 0) {\n entryFields.push(`skills: [${skillExprs.join(', ')}]`);\n }\n if (inputProcessorIdents.length > 0) {\n entryFields.push(`inputProcessors: [${inputProcessorIdents.join(', ')}]`);\n }\n if (outputProcessorIdents.length > 0) {\n entryFields.push(`outputProcessors: [${outputProcessorIdents.join(', ')}]`);\n }\n if (scorerIdents.length > 0) {\n const scorerEntries = scorerIdents.map(({ key, ident }) => `{ key: ${JSON.stringify(key)}, scorer: ${ident} }`);\n entryFields.push(`scorers: [${scorerEntries.join(', ')}]`);\n }\n if (scheduleExprs.length > 0) {\n entryFields.push(`schedules: [${scheduleExprs.join(', ')}]`);\n }\n if (subagentExprs.length > 0) {\n entryFields.push(`subagents: [${subagentExprs.join(', ')}]`);\n }\n if (workspaceIdent) {\n entryFields.push(`workspace: ${workspaceIdent}`);\n }\n if (memoryIdent) {\n entryFields.push(`memory: ${memoryIdent}`);\n }\n // Default-on parity: every FS agent gets a default workspace (file + shell\n // tools) rooted at a per-agent `workspace/` dir next to the bundle, unless\n // config.ts or workspace.ts supplies one. Assembly applies the explicit >\n // convention > default precedence. Subagents nest under `<parent>/<child>` so\n // their seed directories never collide with the parent's.\n entryFields.push(`defaultWorkspaceBasePath: __workspaceBasePath(${JSON.stringify(workspaceName)})`);\n\n return `{ ${entryFields.join(', ')} }`;\n}\n\n/**\n * Generate the source of a wrapper module that:\n * 1. imports the user's real Mastra entry,\n * 2. imports each discovered `config.ts`, `tools/*.ts`, `skills/*.ts`\n * (`createSkill(...)` modules), `workspace.ts`, and `memory.ts`, inlining\n * packaged `SKILL.md` skills,\n * 3. assembles `Agent` instances via `assembleAgentFromFsEntry`, wiring any\n * declared `subagents/` into the parent (nested up to `MAX_FS_SUBAGENT_DEPTH`),\n * 4. registers them onto the user's `mastra` instance (code-registered agents\n * win on name collisions), and\n * 5. re-exports everything from the user's entry so this module is a drop-in\n * replacement for the original `#mastra` target.\n *\n * `instructions.md` is read into the generated wrapper. In dev, the CLI watcher\n * regenerates that wrapper when the markdown file changes.\n *\n * @param userEntry slash-normalized absolute path to the user's mastra entry.\n * @param agents discovered fs-routed agents (absolute, slash-normalized paths).\n */\nexport async function generateFsAgentsModule(\n userEntry: string | undefined,\n agents: DiscoveredFsAgent[],\n options?: {\n workflows?: DiscoveredFsWorkflow[];\n storage?: DiscoveredFsSingleton;\n observability?: DiscoveredFsSingleton;\n logger?: DiscoveredFsSingleton;\n server?: DiscoveredFsSingleton;\n studio?: DiscoveredFsSingleton;\n },\n): Promise<string> {\n const workflows = options?.workflows ?? [];\n const storage = options?.storage;\n const observability = options?.observability;\n const logger = options?.logger;\n const server = options?.server;\n const studio = options?.studio;\n const standalone = userEntry === undefined;\n const lines: string[] = [];\n\n const hasInlineSkills = (function check(list: DiscoveredFsAgent[]): boolean {\n return list.some(a => (a.skills ?? []).some(s => s.kind === 'packaged') || check(a.subagents ?? []));\n })(agents);\n\n lines.push(`import { assembleAgentFromFsEntry } from '@mastra/core/agent';`);\n if (hasInlineSkills) {\n lines.push(`import { createSkill as __createSkill } from '@mastra/core/skills';`);\n }\n if (standalone) {\n lines.push(`import { Mastra } from '@mastra/core';`);\n }\n lines.push(`import { fileURLToPath as __fileURLToPath } from 'node:url';`);\n lines.push(`import { dirname as __dirname, join as __join } from 'node:path';`);\n if (userEntry) {\n lines.push(`import * as __userEntry from ${JSON.stringify(userEntry)};`);\n lines.push(`export * from ${JSON.stringify(userEntry)};`);\n }\n lines.push(``);\n // Resolve workspace base paths relative to this bundled module so they point\n // at `<bundle>/workspace/<name>` wherever the bundle is deployed. Seed files\n // authored under `agents/<name>/workspace/**` are mirrored there at build time.\n // `name` may be a slash-joined path (`<parent>/<child>`) for subagents.\n lines.push(`const __bundleDir = __dirname(__fileURLToPath(import.meta.url));`);\n lines.push(`const __workspaceBasePath = name => __join(__bundleDir, 'workspace', ...name.split('/'));`);\n lines.push(``);\n\n // Singleton imports (storage.ts, observability.ts, etc.).\n const singletonImports: string[] = [];\n if (storage) {\n singletonImports.push(`import __fsStorage from ${JSON.stringify(storage.path)};`);\n }\n if (observability) {\n singletonImports.push(`import __fsObservability from ${JSON.stringify(observability.path)};`);\n }\n if (logger) {\n singletonImports.push(`import __fsLogger from ${JSON.stringify(logger.path)};`);\n }\n if (server) {\n singletonImports.push(`import __fsServer from ${JSON.stringify(server.path)};`);\n }\n if (studio) {\n singletonImports.push(`import __fsStudio from ${JSON.stringify(studio.path)};`);\n }\n if (singletonImports.length > 0) {\n lines.push(...singletonImports);\n lines.push(``);\n }\n\n const wfCodegen = workflows.length > 0 ? generateFsWorkflowsCodegen(workflows) : undefined;\n\n // Workflow imports (placed alongside other imports, before agent entries).\n if (wfCodegen) {\n for (const line of wfCodegen.importLines) {\n lines.push(line);\n }\n lines.push(``);\n }\n\n const entryExprs: string[] = [];\n for (let i = 0; i < agents.length; i++) {\n const agent = agents[i]!;\n const expr = await emitAgentEntry(agent, `${i}`, agent.name, lines);\n entryExprs.push(expr);\n }\n\n // In standalone mode (no user entry), auto-construct a Mastra instance.\n // In wrapper mode, reference the user's exported instance.\n if (standalone) {\n lines.push(``);\n lines.push(`const __mastra = new Mastra({});`);\n } else {\n lines.push(``);\n lines.push(`const __mastra = __userEntry.mastra;`);\n }\n\n lines.push(``);\n lines.push(`const __fsAgentEntries = [`);\n for (const expr of entryExprs) {\n lines.push(` ${expr},`);\n }\n lines.push(`];`);\n lines.push(``);\n // Singleton registration (storage, observability, etc.) MUST run before\n // agents/workflows. `addMemory`/`addAgent` bind the current store to\n // storage-dependent primitives at registration time, so the fs singletons\n // have to be in place first — otherwise fs-discovered agents/workflows would\n // stay bound to the default InMemoryStore.\n\n // Logger is registered before everything else so storage/observability and\n // agents receive the fs-provided logger when they are wired up below.\n if (logger) {\n lines.push(`if (__mastra && typeof __mastra.__registerFsLogger === 'function') {`);\n lines.push(` __mastra.__registerFsLogger(__fsLogger);`);\n lines.push(`}`);\n lines.push(``);\n }\n\n if (storage) {\n lines.push(`if (__mastra && typeof __mastra.__registerFsStorage === 'function') {`);\n lines.push(` __mastra.__registerFsStorage(__fsStorage);`);\n lines.push(`}`);\n lines.push(``);\n }\n\n if (observability) {\n lines.push(`if (__mastra && typeof __mastra.__registerFsObservability === 'function') {`);\n lines.push(` __mastra.__registerFsObservability(__fsObservability);`);\n lines.push(`}`);\n lines.push(``);\n }\n\n if (server) {\n lines.push(`if (__mastra && typeof __mastra.__registerFsServer === 'function') {`);\n lines.push(` __mastra.__registerFsServer(__fsServer);`);\n lines.push(`}`);\n lines.push(``);\n }\n\n if (studio) {\n lines.push(`if (__mastra && typeof __mastra.__registerFsStudio === 'function') {`);\n lines.push(` __mastra.__registerFsStudio(__fsStudio);`);\n lines.push(`}`);\n lines.push(``);\n }\n\n lines.push(`const __fsAgents = Object.create(null);`);\n lines.push(`for (const __entry of __fsAgentEntries) {`);\n lines.push(` __fsAgents[__entry.name] = assembleAgentFromFsEntry(__entry, {`);\n lines.push(` onWarn: msg => __mastra?.getLogger?.()?.warn?.(msg) ?? console.warn(msg),`);\n lines.push(` });`);\n lines.push(`}`);\n lines.push(``);\n\n lines.push(`if (__mastra && typeof __mastra.__registerFsAgents === 'function') {`);\n lines.push(` __mastra.__registerFsAgents(__fsAgents);`);\n lines.push(`}`);\n\n // Workflow registration (after agents, before final export).\n if (wfCodegen) {\n lines.push(``);\n\n for (const line of wfCodegen.registrationLines) {\n lines.push(line);\n }\n }\n\n lines.push(``);\n lines.push(`export const mastra = __mastra;`);\n\n return lines.join('\\n');\n}\n\n/**\n * Generate the workflow-registration lines to splice into the generated wrapper\n * module. Emits import statements for each discovered workflow module and a\n * registration block that calls `__registerFsWorkflows` on the user's mastra.\n *\n * Returns `{ importLines, registrationLines }` so the caller can place them at\n * the correct positions in the wrapper source.\n */\nexport function generateFsWorkflowsCodegen(workflows: DiscoveredFsWorkflow[]): {\n importLines: string[];\n registrationLines: string[];\n} {\n const importLines: string[] = [];\n const registrationLines: string[] = [];\n\n for (let i = 0; i < workflows.length; i++) {\n const wf = workflows[i]!;\n const ident = sanitizeIdentifier(wf.key, 'workflow', `${i}`);\n importLines.push(`import ${ident} from ${JSON.stringify(wf.path)};`);\n }\n\n registrationLines.push(`const __fsWorkflows = Object.create(null);`);\n for (let i = 0; i < workflows.length; i++) {\n const wf = workflows[i]!;\n const ident = sanitizeIdentifier(wf.key, 'workflow', `${i}`);\n registrationLines.push(`__fsWorkflows[${JSON.stringify(wf.key)}] = ${ident};`);\n }\n registrationLines.push(``);\n registrationLines.push(`if (__mastra && typeof __mastra.__registerFsWorkflows === 'function') {`);\n registrationLines.push(` __mastra.__registerFsWorkflows(__fsWorkflows);`);\n registrationLines.push(`}`);\n\n return { importLines, registrationLines };\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, posix } from 'node:path';\nimport { slash } from '../utils';\nimport { generateFsAgentsModule } from './codegen';\nimport { discoverFsAgents, discoverFsSingleton, discoverFsWorkflows } from './discover';\n\nexport interface PrepareFsAgentsEntryResult {\n /**\n * The entry file that should be fed to the bundler/analyzer. When fs-routed\n * primitives (agents, workflows, storage, observability, logger, server,\n * studio) are\n * found this is a generated wrapper module that registers them onto the\n * user's mastra instance; otherwise it is the original entry unchanged.\n * When auto-constructing (no user entry), this is always the generated module.\n */\n entryFile: string;\n /** Whether a standalone Mastra instance was auto-constructed (no index.ts). */\n standalone: boolean;\n /**\n * Glob tool paths for tools defined under `agents/*\\/tools` so they are\n * bundled alongside the top-level `tools/` directory.\n */\n toolPaths: string[];\n /** Number of fs-routed agents discovered. */\n agentCount: number;\n /** Number of fs-routed workflows discovered. */\n workflowCount: number;\n /** Whether a `storage.ts` singleton was discovered. */\n hasStorage: boolean;\n /** Whether an `observability.ts` singleton was discovered. */\n hasObservability: boolean;\n /** Whether a `logger.ts` singleton was discovered. */\n hasLogger: boolean;\n /** Whether a `server.ts` singleton was discovered. */\n hasServer: boolean;\n /** Whether a `studio.ts` singleton was discovered. */\n hasStudio: boolean;\n /**\n * Generated wrapper source to write to {@link entryFile}, or `undefined` when\n * there are no fs-routed primitives. The write is deferred so callers can run\n * it *after* `bundler.prepare()` empties the output directory — otherwise the\n * wrapper is wiped before the bundler reads it.\n */\n moduleSource?: string;\n}\n\n/**\n * Discover fs-routed agents under `<mastraDir>/agents/*`, workflows under\n * `<mastraDir>/workflows/`, and singleton config files (e.g. `storage.ts`,\n * `observability.ts`, `logger.ts`, `server.ts`, `studio.ts`).\n * When any are found, generate a wrapper entry module that registers them onto\n * the user's mastra instance. Returns the entry the bundler should use plus\n * extra tool glob paths so `agents/*\\/tools` are bundled.\n *\n * This does NOT write the wrapper to disk; call {@link writeFsAgentsEntry} with\n * the result after `bundler.prepare()` so the generated file is not wiped when\n * the output directory is emptied.\n *\n * When `entryFile` is `undefined` (no `index.ts`/`index.js`) and fs-routed\n * primitives are found, a standalone Mastra instance is auto-constructed from\n * them — no user code required.\n *\n * When no fs-routed primitives are present the original entry is returned\n * unchanged, so existing code-only projects are completely unaffected.\n */\nexport async function prepareFsAgentsEntry(\n mastraDir: string,\n entryFile: string | undefined,\n outputDirectory: string,\n): Promise<PrepareFsAgentsEntryResult> {\n const [agents, workflows, storage, observability, logger, server, studio] = await Promise.all([\n discoverFsAgents(mastraDir),\n discoverFsWorkflows(mastraDir),\n discoverFsSingleton(mastraDir, 'storage'),\n discoverFsSingleton(mastraDir, 'observability'),\n discoverFsSingleton(mastraDir, 'logger'),\n discoverFsSingleton(mastraDir, 'server'),\n discoverFsSingleton(mastraDir, 'studio'),\n ]);\n\n const standalone = entryFile === undefined;\n const hasFsPrimitives =\n agents.length > 0 || workflows.length > 0 || !!storage || !!observability || !!logger || !!server || !!studio;\n\n if (!hasFsPrimitives && entryFile !== undefined) {\n return {\n entryFile,\n standalone: false,\n toolPaths: [],\n agentCount: 0,\n workflowCount: 0,\n hasStorage: false,\n hasObservability: false,\n hasLogger: false,\n hasServer: false,\n hasStudio: false,\n };\n }\n\n if (!hasFsPrimitives && standalone) {\n throw new Error(\n 'No index.ts and no file-based primitives found. ' +\n 'Create src/mastra/index.ts with a Mastra instance, or add file-based agents/workflows/storage.',\n );\n }\n\n const moduleSource = await generateFsAgentsModule(entryFile ? slash(entryFile) : undefined, agents, {\n workflows,\n storage,\n observability,\n logger,\n server,\n studio,\n });\n const generatedEntry = join(outputDirectory, '.mastra-fs-agents-entry.mjs');\n\n const normalizedMastraDir = slash(mastraDir);\n const toolPaths =\n agents.length > 0\n ? [\n posix.join(normalizedMastraDir, 'agents/*/tools/**/*.{js,ts}'),\n `!${posix.join(normalizedMastraDir, 'agents/*/tools/**/*.{test,spec}.{js,ts}')}`,\n `!${posix.join(normalizedMastraDir, 'agents/*/tools/**/__tests__/**')}`,\n ]\n : [];\n\n return {\n entryFile: generatedEntry,\n standalone,\n toolPaths,\n agentCount: agents.length,\n workflowCount: workflows.length,\n hasStorage: !!storage,\n hasObservability: !!observability,\n hasLogger: !!logger,\n hasServer: !!server,\n hasStudio: !!studio,\n moduleSource,\n };\n}\n\n/**\n * Write the generated fs-agents wrapper produced by {@link prepareFsAgentsEntry}\n * to its `entryFile`. No-op when there are no fs-routed agents. Call this AFTER\n * `bundler.prepare()` (which empties the output directory) so the wrapper\n * survives for the bundler/watcher to read.\n */\nexport async function writeFsAgentsEntry(result: PrepareFsAgentsEntryResult): Promise<void> {\n if (!result.moduleSource) {\n return;\n }\n\n await mkdir(dirname(result.entryFile), { recursive: true });\n await writeFile(result.entryFile, result.moduleSource, 'utf-8');\n}\n","import { cp, lstat, mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { discoverFsAgents } from './discover';\nimport type { DiscoveredFsAgent } from './discover';\n\n/**\n * Skip symlinks when copying workspace seeds. A symlink under\n * `agents/<name>/workspace/` could point outside the workspace and be preserved\n * in the bundle, letting the agent read arbitrary files at runtime. We copy only\n * regular files and directories.\n */\nasync function rejectSymlinks(source: string): Promise<boolean> {\n const stats = await lstat(source);\n return !stats.isSymbolicLink();\n}\n\nasync function mirrorAgentSeeds(\n agent: DiscoveredFsAgent,\n workspaceName: string,\n bundleDir: string,\n mirrored: string[],\n): Promise<void> {\n if (agent.workspaceSeedDir) {\n const destination = join(bundleDir, 'workspace', ...workspaceName.split('/'));\n await mkdir(destination, { recursive: true });\n await cp(agent.workspaceSeedDir, destination, { recursive: true, filter: rejectSymlinks });\n mirrored.push(workspaceName);\n }\n\n // Subagents nest under `<parent>/<child>`, matching the codegen workspace key.\n for (const child of agent.subagents ?? []) {\n await mirrorAgentSeeds(child, `${workspaceName}/${child.name}`, bundleDir, mirrored);\n }\n}\n\n/**\n * Mirror authored `agents/<name>/workspace/**` seed files into the bundled\n * output so each fs-routed agent starts with them on disk (Eve parity). Files\n * are copied to `<bundleDir>/workspace/<name>`, which is exactly where the\n * generated entry roots each agent's default workspace at runtime (resolved\n * relative to the bundled module via `import.meta.url`). Declared subagents\n * mirror to the nested `<bundleDir>/workspace/<parent>/<child>` path.\n *\n * Must run AFTER the bundle step, since bundling recreates the output dir.\n *\n * @param mastraDir The user's `src/mastra` directory (source of seeds).\n * @param bundleDir The final bundle directory (e.g. `<outputDirectory>/output`).\n * @returns the workspace names whose seeds were mirrored (`<parent>/<child>` for subagents).\n */\nexport async function mirrorFsAgentWorkspaces(mastraDir: string, bundleDir: string): Promise<string[]> {\n const agents = await discoverFsAgents(mastraDir);\n const mirrored: string[] = [];\n\n for (const agent of agents) {\n await mirrorAgentSeeds(agent, agent.name, bundleDir, mirrored);\n }\n\n return mirrored;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAWA,MAAM,eAAe,CAAC,mCAAmC;AACzD,MAAM,gBAAgB,CAAC,sBAAsB,cAAc;;;;;;;;;;AAyB3D,SAAgB,qBAAqB,SAA8C;CACjF,MAAM,EAAE,gBAAgB,0BAA0B,cAAc,eAAe,WAAW,UAAU,mBAClG;CAEF,IAAI,eAAe;CAEnB,MAAM,mBAAmB,wBAAwB,gBAAgB,YAAY;CAC7E,MAAM,aAAa,0BAA0B,0BAA0B,aAAa;CAEpF,OAAO;EACL,MAAM;EACN,MAAM,aAAa;GACjB,MAAM,cAAc,MAAM,6BAA6B,gBAAgB;GAEvE,KAAK,MAAM,QAAQ,aACjB,KAAK,aAAa,QAAQ,IAAI,CAAC;GAIjC,IAAI,cAAc;IAChB,eAAe;IACf;GACF;GAIA,IAAI,CAAC,MAFyB,uBAAuB,aAAa,UAAU,GAG1E;GAMF,MAAM,gBAFW,oBAAoB,cAER,GAAG,WAAW;IACzC,gBAAgB;KACd,GAAG;KACH,WAAW,gBAAgB,aAAa;KACxC,OAAO;IACT;IACA,aAAa;IACb;IACA;IACA;GACF,CAAC;EACH;CACF;AACF;AAEA,SAAS,wBACP,gBACA,cACU;CACV,MAAM,wBAAQ,IAAI,IAAY;CAE9B,KAAK,MAAM,CAAC,KAAK,aAAa,eAAe,QAAQ,GAAG;EACtD,IAAI,CAAC,SAAS,aACZ;EAGF,IAAI,SAAS,UAAU;GACrB,MAAM,IAAI,MAAM,SAAS,QAAQ,CAAC;GAClC;EACF;EAEA,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S,KAAK,aAAa;CAC7B;CAGA,KAAK,MAAM,SAAS,MAAM,aAAa,CAAC,GACtC,MAAM,iBAAiB,OAAO,GAAG,cAAc,GAAG,MAAM,QAAQ,WAAW,QAAQ;AAEvF;;;;;;;;;;;;;;;AAgBA,eAAsB,wBAAwB,WAAmB,WAAsC;CACrG,MAAM,SAAS,MAAM,iBAAiB,SAAS;CAC/C,MAAM,WAAqB,CAAC;CAE5B,KAAK,MAAM,SAAS,QAClB,MAAM,iBAAiB,OAAO,MAAM,MAAM,WAAW,QAAQ;CAG/D,OAAO;AACT"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["pkg","getPackageName","MastraBundler","createBundlerUtil","getBundlerOptions","analyzeBundle","DepsService","fsExtra","MastraError","ErrorDomain","ErrorCategory","getWorkspaceInformation","getInputOptions","slash","posix","path","FileService","isBareModuleSpecifier","collectTransitiveWorkspaceDependencies","packWorkspaceDependencies"],"sources":["../../src/bundler/index.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { readFile, rm, stat, writeFile } from 'node:fs/promises';\nimport { dirname, join, posix } from 'node:path';\nimport { MastraBundler } from '@mastra/core/bundler';\nimport { MastraError, ErrorDomain, ErrorCategory } from '@mastra/core/error';\nimport type { Config } from '@mastra/core/mastra';\nimport virtual from '@rollup/plugin-virtual';\nimport * as pkg from 'empathic/package';\nimport fsExtra, { copy, ensureDir, emptyDir, readJSON } from 'fs-extra/esm';\nimport type { InputOptions, OutputOptions } from 'rollup';\nimport { glob } from 'tinyglobby';\nimport { analyzeBundle } from '../build/analyze';\nimport { createBundler as createBundlerUtil, getInputOptions } from '../build/bundler';\nimport { getBundlerOptions } from '../build/bundlerOptions';\nimport type { BundlerOptions, ExternalDependencyInfo } from '../build/types';\nimport type { BundlerPlatform } from '../build/utils';\nimport { getPackageName, isBareModuleSpecifier, slash } from '../build/utils';\nimport { DepsService } from '../services/deps';\nimport { FileService } from '../services/fs';\nimport {\n collectTransitiveWorkspaceDependencies,\n getWorkspaceInformation,\n packWorkspaceDependencies,\n} from './workspaceDependencies';\n\nexport type { BundlerOptions, ExternalDependencyInfo } from '../build/types';\nexport type { BundlerPlatform } from '../build/utils';\n\nexport const IS_DEFAULT = Symbol('IS_DEFAULT');\n\nconst NPM_ALIAS_PREFIX = 'npm:';\n/** Characters a registry range or dist tag can contain. Protocols need `:`, git shorthand needs `/` or `#`. */\nconst REGISTRY_SPEC_PATTERN = /^[A-Za-z0-9.+_^~><=*|!\\s-]+$/;\nconst PACKAGE_NAME_PATTERN = /^(?:@[A-Za-z0-9._-]+\\/)?[A-Za-z0-9._-]+$/;\nconst TARBALL_SUFFIX_PATTERN = /\\.(?:tgz|tar\\.gz|tar)$/i;\n/** npm reads a value starting like this as a path, whatever follows. A bare `~` is a semver range. */\nconst FILE_SPEC_PREFIX_PATTERN = /^(?:\\.|~[/\\\\]|[/\\\\]|[A-Za-z]:[/\\\\])/;\n/** A range admitting any published version: `*`, `x`, `>=0`, and any union containing one. */\nconst UNBOUNDED_RANGE_PATTERN = /(?:^|\\|\\||\\s)\\s*(?:[*xX]|>=?\\s*0(?:\\.0)*(?:\\.0)*)\\s*(?:$|\\|\\|)/;\n\n/**\n * Constraints declared by the source app, plus the packages some resolution field pins.\n *\n * Only `dependencies` values are read. Override fields contribute names, never values: which of\n * `overrides`, `resolutions`, `pnpm.overrides` or `pnpm-workspace.yaml` a given install honoured\n * depends on the package manager and its version, so reproducing that precedence would mean\n * emulating three package managers. A name appearing in any of them is enough to know the resolved\n * version was chosen deliberately, which is all this needs.\n */\nexport type SourceDependencyConstraints = {\n dependencies: Record<string, string>;\n pinnedByResolutionField: Set<string>;\n};\n\nconst toStringRecord = (value: unknown): Record<string, string> => {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return {};\n }\n\n return Object.fromEntries(\n Object.entries(value).filter((entry): entry is [string, string] => typeof entry[1] === 'string'),\n );\n};\n\n/**\n * True when a specifier is something the isolated install in `.mastra/output` can resolve from the\n * registry: a semver range, a dist tag, a wildcard, or an npm alias whose target is a registry\n * package and range.\n *\n * This is an allowlist rather than a denylist of known protocols, so an unfamiliar protocol is\n * rejected without this code having to know it exists. The output directory is not a workspace, has\n * no catalog definitions and has a different relative-path base, so `catalog:`, `workspace:`,\n * `file:`, `link:` and git specifiers are all either uninstallable there or point somewhere else.\n */\nexport const isRegistryVersionSpec = (spec: string): boolean => {\n if (FILE_SPEC_PREFIX_PATTERN.test(spec) || TARBALL_SUFFIX_PATTERN.test(spec)) {\n return false;\n }\n\n if (spec.startsWith(NPM_ALIAS_PREFIX)) {\n const alias = spec.slice(NPM_ALIAS_PREFIX.length);\n // Skip index 0 so `npm:@scope/pkg` reads as an alias with no range rather than an empty name.\n const rangeSeparator = alias.lastIndexOf('@');\n const name = rangeSeparator > 0 ? alias.slice(0, rangeSeparator) : alias;\n const range = rangeSeparator > 0 ? alias.slice(rangeSeparator + 1) : '*';\n\n return PACKAGE_NAME_PATTERN.test(name) && isRegistryVersionSpec(range);\n }\n\n return REGISTRY_SPEC_PATTERN.test(spec);\n};\n\n/**\n * True when a specifier names a version the output install can be held to.\n *\n * A range admitting anything (`*`, `latest`, `>=0`, an alias with no range) is looser than the\n * version already resolved, so writing it would let a later install pull something the bundle was\n * never analyzed against.\n */\nconst isBoundedVersionSpec = (spec: string): boolean => {\n const range = spec.startsWith(NPM_ALIAS_PREFIX)\n ? (() => {\n const alias = spec.slice(NPM_ALIAS_PREFIX.length);\n const rangeSeparator = alias.lastIndexOf('@');\n return rangeSeparator > 0 ? alias.slice(rangeSeparator + 1) : '';\n })()\n : spec;\n\n return /\\d/.test(range) && !UNBOUNDED_RANGE_PATTERN.test(range);\n};\n\nconst readManifest = async (manifestPath: string | undefined): Promise<Record<string, unknown> | undefined> => {\n if (!manifestPath) {\n return undefined;\n }\n\n try {\n const manifest = await readJSON(manifestPath);\n return manifest && typeof manifest === 'object' ? manifest : undefined;\n } catch {\n // A manifest that cannot be read tells us nothing about intent.\n return undefined;\n }\n};\n\n/** Collect the package names a manifest's resolution fields pin, ignoring their values. */\nconst collectManifestPinnedNames = (manifest: Record<string, unknown> | undefined, pinned: Set<string>) => {\n const pnpmSection = manifest?.pnpm;\n const records = [\n manifest?.overrides,\n manifest?.resolutions,\n pnpmSection && typeof pnpmSection === 'object' ? (pnpmSection as { overrides?: unknown }).overrides : undefined,\n ];\n\n for (const record of records) {\n if (record && typeof record === 'object' && !Array.isArray(record)) {\n for (const key of Object.keys(record)) {\n pinned.add(key);\n }\n }\n }\n};\n\n/**\n * Collect the names under a top-level `overrides:` block in `pnpm-workspace.yaml`.\n *\n * pnpm moved overrides out of `package.json` into this file, so a workspace on a current pnpm keeps\n * them only here. Reading names off the indented block avoids a YAML dependency, the same tradeoff\n * `copyPnpmWorkspaceSettings` already makes for the top-level keys it copies.\n */\nconst collectPnpmWorkspacePinnedNames = (source: string, pinned: Set<string>) => {\n const lines = source.split(/\\r?\\n/);\n let insideOverrides = false;\n\n for (const line of lines) {\n if (/^\\S/.test(line)) {\n insideOverrides = /^overrides:\\s*$/.test(line);\n continue;\n }\n\n if (!insideOverrides) {\n continue;\n }\n\n const key = /^\\s+(?:'([^']+)'|\"([^\"]+)\"|([^'\"\\s:][^:]*?))\\s*:/.exec(line);\n if (key) {\n pinned.add((key[1] ?? key[2] ?? key[3] ?? '').trim());\n }\n }\n};\n\n/**\n * Read the constraints the source app declared.\n *\n * `dependencies` come from the manifest at `projectRoot`, the package the build was invoked for and\n * whose directory receives the output, falling back to the manifest above the entry file. Anchoring\n * on `projectRoot` rather than the entry file keeps the answer deterministic when the entry handed\n * to the bundler is a generated wrapper rather than the app's own source file.\n *\n * Resolution-field names are collected from both that manifest and the workspace root, including the\n * root `pnpm-workspace.yaml`, because a name pinned anywhere means the resolved version may have been\n * chosen deliberately rather than hoisted by accident.\n */\nexport const getSourceDependencyConstraints = async ({\n projectRoot,\n mastraEntryFile,\n workspaceRoot,\n}: {\n projectRoot: string;\n mastraEntryFile: string;\n workspaceRoot?: string;\n}): Promise<SourceDependencyConstraints> => {\n const manifestPaths = [pkg.up({ cwd: projectRoot }), pkg.up({ cwd: dirname(mastraEntryFile) })].filter(\n (entry, index, entries): entry is string => !!entry && entries.indexOf(entry) === index,\n );\n\n if (workspaceRoot) {\n manifestPaths.push(join(workspaceRoot, 'package.json'));\n }\n\n const pinnedByResolutionField = new Set<string>();\n let dependencies: Record<string, string> | undefined;\n\n for (const manifestPath of manifestPaths) {\n const manifest = await readManifest(manifestPath);\n if (!manifest) {\n continue;\n }\n\n // Nearest manifest wins, and an empty `dependencies` record is still that package's answer.\n dependencies ??= toStringRecord(manifest.dependencies);\n collectManifestPinnedNames(manifest, pinnedByResolutionField);\n }\n\n if (workspaceRoot) {\n try {\n collectPnpmWorkspacePinnedNames(\n await readFile(join(workspaceRoot, 'pnpm-workspace.yaml'), 'utf-8'),\n pinnedByResolutionField,\n );\n } catch {\n // No pnpm workspace config, or unreadable: nothing to learn from it.\n }\n }\n\n return { dependencies: dependencies ?? {}, pinnedByResolutionField };\n};\n\nconst findDeclaredConstraint = (\n constraints: SourceDependencyConstraints,\n dependencyName: string,\n): string | undefined => {\n const names = [dependencyName, getPackageName(dependencyName)].filter(\n (name, index, all): name is string => !!name && all.indexOf(name) === index,\n );\n\n for (const name of names) {\n // A pinned package's resolved version is the deliberate answer, so leave it as `main` wrote it.\n if (constraints.pinnedByResolutionField.has(name)) {\n return undefined;\n }\n }\n\n for (const name of names) {\n const declared = (constraints.dependencies[name] ?? '').trim();\n if (declared && isBoundedVersionSpec(declared) && isRegistryVersionSpec(declared)) {\n return declared;\n }\n }\n\n return undefined;\n};\n\n/**\n * Prefer the constraint the app declared over the version resolved from `node_modules`.\n *\n * The resolved version is whatever the install happened to hoist, so an app declaring `zod: ^4.3.6`\n * next to a hoisted `zod@3.25.76` gets the hoisted version written into the output manifest and the\n * isolated install then locks it in.\n */\nexport const applySourceDependencyRange = (\n dependencyName: string,\n dependencyInfo: ExternalDependencyInfo,\n constraints: SourceDependencyConstraints,\n): ExternalDependencyInfo => {\n const declared = findDeclaredConstraint(constraints, dependencyName);\n if (!declared) {\n return dependencyInfo;\n }\n\n if (declared.startsWith(NPM_ALIAS_PREFIX)) {\n return { ...dependencyInfo, packageSpec: declared };\n }\n\n // `packageSpec` is set only when the resolved package's own name differs from the requested one, so\n // a bare range under this key describes a different package and the resolved alias is the answer.\n if (dependencyInfo.packageSpec) {\n return dependencyInfo;\n }\n\n return { ...dependencyInfo, version: declared };\n};\n\nexport abstract class Bundler extends MastraBundler {\n protected analyzeOutputDir = '.build';\n protected outputDir = 'output';\n protected platform: BundlerPlatform = 'node';\n\n constructor(name: string, component: 'BUNDLER' | 'DEPLOYER' = 'BUNDLER') {\n super({ name, component });\n }\n\n async prepare(outputDirectory: string): Promise<void> {\n // Clean up the output directory first\n await emptyDir(outputDirectory);\n\n await ensureDir(join(outputDirectory, this.analyzeOutputDir));\n await ensureDir(join(outputDirectory, this.outputDir));\n }\n\n async writePackageJson(\n outputDirectory: string,\n dependencies: Map<string, string | ExternalDependencyInfo>,\n resolutions?: Record<string, string>,\n ) {\n this.logger.debug(\"Writing project's package.json\");\n\n await ensureDir(outputDirectory);\n const pkgPath = join(outputDirectory, 'package.json');\n\n const dependenciesMap = new Map();\n for (const [key, value] of dependencies.entries()) {\n const dependencyValue = typeof value === 'string' ? value : (value.packageSpec ?? value.version ?? 'latest');\n if (key.startsWith('@')) {\n // Handle scoped packages (e.g. @org/package)\n const pkgChunks = key.split('/');\n dependenciesMap.set(`${pkgChunks[0]}/${pkgChunks[1]}`, dependencyValue);\n } else {\n // For non-scoped packages, take only the first part before any slash\n const pkgName = key.split('/')[0] || key;\n dependenciesMap.set(pkgName, dependencyValue);\n }\n }\n\n await writeFile(\n pkgPath,\n JSON.stringify(\n {\n name: 'server',\n version: '1.0.0',\n private: true,\n type: 'module',\n main: 'index.mjs',\n scripts: {\n start: 'node ./index.mjs',\n },\n dependencies: Object.fromEntries(dependenciesMap.entries()),\n ...(Object.keys(resolutions ?? {}).length > 0 && { resolutions }),\n },\n null,\n 2,\n ),\n );\n }\n\n protected createBundler(inputOptions: InputOptions, outputOptions: Partial<OutputOptions> & { dir: string }) {\n return createBundlerUtil(inputOptions, outputOptions);\n }\n\n protected async getUserBundlerOptions(\n mastraEntryFile: string,\n outputDirectory: string,\n ): Promise<NonNullable<Config['bundler']>> {\n const defaultBundlerOptions: Config['bundler'] = {\n externals: [],\n sourcemap: false,\n transpilePackages: [],\n [IS_DEFAULT]: true,\n } as const;\n\n try {\n const bundlerOptions = await getBundlerOptions(mastraEntryFile, outputDirectory);\n\n return bundlerOptions ?? defaultBundlerOptions;\n } catch (error) {\n this.logger.debug('Failed to get bundler options, sourcemap will be disabled', { error });\n }\n\n return defaultBundlerOptions;\n }\n\n protected async analyze(entry: string | string[], mastraFile: string, outputDirectory: string) {\n return await analyzeBundle(\n ([] as string[]).concat(entry),\n mastraFile,\n {\n outputDir: join(outputDirectory, this.analyzeOutputDir),\n projectRoot: outputDirectory,\n platform: this.platform,\n },\n this.logger,\n );\n }\n\n protected pnpmNodeLinker?: 'hoisted';\n\n protected async installDependencies(\n outputDirectory: string,\n rootDir = process.cwd(),\n pnpmOverrides?: Record<string, string>,\n ) {\n const deps = new DepsService(rootDir);\n deps.__setLogger(this.logger);\n\n await deps.install({\n dir: join(outputDirectory, this.outputDir),\n pnpmOverrides,\n pnpmNodeLinker: this.pnpmNodeLinker,\n });\n }\n\n /**\n * Generate a package-lock.json for the output directory so that deploy targets\n * can use `npm ci` instead of `npm install`, skipping version resolution entirely.\n * This is a lockfile-only operation — no packages are downloaded.\n *\n * Temporarily moves node_modules out of the way because pnpm's symlink-based\n * layout confuses npm's arborist, then restores it afterwards so that\n * `mastra start` (or wrangler) can still resolve dependencies at runtime.\n */\n private async generateNpmLockfile(outputDir: string): Promise<void> {\n const nodeModules = join(outputDir, 'node_modules');\n const nodeModulesTmp = join(outputDir, 'node_modules.__tmp');\n let movedNodeModules = false;\n try {\n // Move node_modules aside — pnpm's symlink layout confuses npm's arborist\n if (await fsExtra.pathExists(nodeModules)) {\n await fsExtra.move(nodeModules, nodeModulesTmp, { overwrite: true });\n movedNodeModules = true;\n }\n execSync('npm install --package-lock-only --force', {\n cwd: outputDir,\n stdio: 'pipe',\n timeout: 60_000,\n });\n } catch {\n this.logger.warn('Failed to generate package-lock.json — deploy will fall back to npm install');\n } finally {\n // Restore node_modules so runtime resolution works\n if (movedNodeModules) {\n await rm(nodeModules, { recursive: true, force: true });\n await fsExtra.move(nodeModulesTmp, nodeModules, { overwrite: true });\n }\n }\n }\n\n protected async copyPublic(mastraDir: string, outputDirectory: string) {\n const publicDir = join(mastraDir, 'public');\n\n try {\n await stat(publicDir);\n } catch {\n return;\n }\n\n await copy(publicDir, join(outputDirectory, this.outputDir));\n }\n\n protected async copyDOTNPMRC({\n rootDir = process.cwd(),\n outputDirectory,\n }: {\n rootDir?: string;\n outputDirectory: string;\n }) {\n const sourceDotNpmRcPath = join(rootDir, '.npmrc');\n const targetDotNpmRcPath = join(outputDirectory, this.outputDir, '.npmrc');\n\n try {\n await stat(sourceDotNpmRcPath);\n await copy(sourceDotNpmRcPath, targetDotNpmRcPath);\n } catch {\n return;\n }\n }\n\n /**\n * Writes the `mastra-project.json` deployment marker for Software Factory\n * projects after public assets have been copied. Verifies that the Factory\n * SPA (`factory/index.html`) exists in the output before emitting the marker.\n */\n protected async writeFactoryMarker(outputDirectory: string): Promise<void> {\n const outputDir = join(outputDirectory, this.outputDir);\n const factoryIndex = join(outputDir, 'factory', 'index.html');\n if (!existsSync(factoryIndex)) {\n throw new MastraError({\n id: 'DEPLOYER_BUNDLER_FACTORY_UI_MISSING',\n text: 'Software Factory project detected but factory/index.html was not found after copying the prebuilt Factory UI.',\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.SYSTEM,\n });\n }\n await writeFile(\n join(outputDir, 'mastra-project.json'),\n JSON.stringify({ schemaVersion: 1, projectType: 'factory', assets: { ui: 'factory' } }, null, 2),\n );\n this.logger.info('Wrote mastra-project.json for Software Factory project');\n }\n\n protected async getBundlerOptions(\n serverFile: string,\n mastraEntryFile: string,\n analyzedBundleInfo: Awaited<ReturnType<typeof analyzeBundle>>,\n toolsPaths: (string | string[])[],\n { enableSourcemap, enableEsmShim, externals }: BundlerOptions,\n ) {\n const { workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile });\n const closestPkgJson = pkg.up({ cwd: dirname(mastraEntryFile) });\n const projectRoot = closestPkgJson ? dirname(closestPkgJson) : process.cwd();\n\n const inputOptions: InputOptions = await getInputOptions(\n mastraEntryFile,\n analyzedBundleInfo,\n this.platform,\n {\n 'process.env.NODE_ENV': JSON.stringify('production'),\n },\n { sourcemap: enableSourcemap, workspaceRoot, projectRoot, enableEsmShim, externalsPreset: externals === true },\n );\n const isVirtual = serverFile.includes('\\n') || !existsSync(serverFile);\n const toolsInputOptions = await this.listToolsInputOptions(toolsPaths);\n\n if (isVirtual) {\n inputOptions.input = { index: '#entry', ...toolsInputOptions };\n\n if (Array.isArray(inputOptions.plugins)) {\n inputOptions.plugins.unshift(virtual({ '#entry': serverFile }));\n } else {\n inputOptions.plugins = [virtual({ '#entry': serverFile })];\n }\n } else {\n inputOptions.input = { index: serverFile, ...toolsInputOptions };\n }\n\n return inputOptions;\n }\n\n getAllToolPaths(mastraDir: string, toolsPaths: (string | string[])[] = []): (string | string[])[] {\n // Normalize Windows paths to forward slashes for consistent handling\n const normalizedMastraDir = slash(mastraDir);\n\n // Prepare default tools paths with glob patterns\n const defaultToolsPath = posix.join(normalizedMastraDir, 'tools/**/*.{js,ts}');\n const defaultToolsIgnorePaths = [\n `!${posix.join(normalizedMastraDir, 'tools/**/*.{test,spec}.{js,ts}')}`,\n `!${posix.join(normalizedMastraDir, 'tools/**/__tests__/**')}`,\n ];\n\n // Combine default path with ignore patterns\n const defaultPaths = [defaultToolsPath, ...defaultToolsIgnorePaths];\n\n // If no tools paths provided, use only the default paths\n if (toolsPaths.length === 0) {\n return [defaultPaths];\n }\n\n // If tools paths are provided, add the default paths to ensure standard tools are always included\n return [...toolsPaths, defaultPaths];\n }\n\n async listToolsInputOptions(toolsPaths: (string | string[])[]) {\n const inputs: Record<string, string> = {};\n\n for (const toolPath of toolsPaths) {\n const expandedPaths = await glob(toolPath, {\n absolute: true,\n expandDirectories: false,\n });\n\n for (const path of expandedPaths) {\n if (await fsExtra.pathExists(path)) {\n const fileService = new FileService();\n const entryFile = fileService.getFirstExistingFile([\n join(path, 'index.ts'),\n join(path, 'index.js'),\n path, // if path itself is a file\n ]);\n\n // if it doesn't exist or is a dir skip it. using a dir as a tool will crash the process\n if (!entryFile || (await stat(entryFile)).isDirectory()) {\n this.logger.warn('No entry file found, skipping', { path });\n continue;\n }\n\n const uniqueToolID = crypto.randomUUID();\n // Normalize Windows paths to forward slashes for consistent handling\n const normalizedEntryFile = entryFile.replaceAll('\\\\', '/');\n inputs[`tools/${uniqueToolID}`] = normalizedEntryFile;\n } else {\n this.logger.warn('Tool path does not exist, skipping', { path });\n }\n }\n }\n\n return inputs;\n }\n\n protected async _bundle(\n serverFile: string,\n mastraEntryFile: string,\n {\n projectRoot,\n outputDirectory,\n enableEsmShim = true,\n }: {\n projectRoot: string;\n outputDirectory: string;\n enableEsmShim?: boolean;\n },\n toolsPaths: (string | string[])[] = [],\n bundleLocation: string = join(outputDirectory, this.outputDir),\n ): Promise<void> {\n const analyzeDir = join(outputDirectory, this.analyzeOutputDir);\n\n const bundlerOptions = await this.getUserBundlerOptions(mastraEntryFile, outputDirectory);\n const internalBundlerOptions: BundlerOptions = {\n enableSourcemap: !!bundlerOptions.sourcemap,\n externals: bundlerOptions.externals ?? [],\n enableEsmShim,\n dynamicPackages: bundlerOptions.dynamicPackages,\n };\n\n let analyzedBundleInfo;\n try {\n const resolvedToolsPaths = await this.listToolsInputOptions(toolsPaths);\n analyzedBundleInfo = await analyzeBundle(\n [serverFile, ...Object.values(resolvedToolsPaths)],\n mastraEntryFile,\n {\n outputDir: analyzeDir,\n projectRoot,\n platform: this.platform,\n bundlerOptions: internalBundlerOptions,\n },\n this.logger,\n );\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n\n if (error instanceof MastraError) {\n throw error;\n }\n\n throw new MastraError(\n {\n id: 'DEPLOYER_BUNDLER_ANALYZE_FAILED',\n text: `Failed to analyze Mastra application: ${message}`,\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.SYSTEM,\n },\n error,\n );\n }\n\n const { workspaceRoot } = await getWorkspaceInformation({ dir: projectRoot, mastraEntryFile });\n const sourceDependencyConstraints = await getSourceDependencyConstraints({\n projectRoot,\n mastraEntryFile,\n workspaceRoot,\n });\n const dependenciesToInstall = new Map<string, ExternalDependencyInfo>();\n for (const [dep, depInfo] of analyzedBundleInfo.externalDependencies) {\n if (analyzedBundleInfo.workspaceMap.has(dep) || !isBareModuleSpecifier(dep)) {\n continue;\n }\n\n dependenciesToInstall.set(dep, applySourceDependencyRange(dep, depInfo, sourceDependencyConstraints));\n }\n\n const initialWorkspaceDependencies = new Set<string>();\n for (const dep of analyzedBundleInfo.dependencies.keys()) {\n const pkgName = getPackageName(dep);\n if (pkgName && analyzedBundleInfo.workspaceMap.has(pkgName)) {\n initialWorkspaceDependencies.add(pkgName);\n }\n }\n\n const transitiveWorkspaceDependencies = collectTransitiveWorkspaceDependencies({\n workspaceMap: analyzedBundleInfo.workspaceMap,\n initialDependencies: initialWorkspaceDependencies,\n logger: this.logger,\n });\n\n for (const [dep, packageSpec] of Object.entries(transitiveWorkspaceDependencies.resolutions)) {\n dependenciesToInstall.set(dep, {\n version: analyzedBundleInfo.workspaceMap.get(dep)?.version,\n packageSpec,\n });\n }\n\n try {\n await this.writePackageJson(\n join(outputDirectory, this.outputDir),\n dependenciesToInstall,\n transitiveWorkspaceDependencies.resolutions,\n );\n if (transitiveWorkspaceDependencies.usedWorkspacePackages.size > 0) {\n await packWorkspaceDependencies({\n workspaceMap: analyzedBundleInfo.workspaceMap,\n usedWorkspacePackages: transitiveWorkspaceDependencies.usedWorkspacePackages,\n bundleOutputDir: join(outputDirectory, this.outputDir),\n logger: this.logger,\n });\n }\n\n this.logger.info('Bundling Mastra application');\n\n const inputOptions: InputOptions = await this.getBundlerOptions(\n serverFile,\n mastraEntryFile,\n analyzedBundleInfo,\n toolsPaths,\n internalBundlerOptions,\n );\n\n const bundler = await this.createBundler(\n {\n ...inputOptions,\n logLevel: inputOptions.logLevel === 'silent' ? 'warn' : inputOptions.logLevel,\n onwarn: warning => {\n if (warning.code === 'CIRCULAR_DEPENDENCY') {\n if (warning.ids?.[0]?.includes('node_modules')) {\n return;\n }\n\n this.logger.warn('Circular dependency found', {\n dependency: warning.message.replace('Circular dependency: ', ''),\n });\n }\n },\n },\n {\n dir: bundleLocation,\n manualChunks: {\n mastra: ['#mastra'],\n },\n sourcemap: internalBundlerOptions.enableSourcemap,\n },\n );\n\n await bundler.write();\n const toolImports: string[] = [];\n const toolsExports: string[] = [];\n Array.from(Object.keys(inputOptions.input || {}))\n .filter(key => key.startsWith('tools/'))\n .forEach((key, index) => {\n const toolExport = `tool${index}`;\n toolImports.push(`import * as ${toolExport} from './${key}.mjs';`);\n toolsExports.push(toolExport);\n });\n\n await writeFile(\n join(bundleLocation, 'tools.mjs'),\n `${toolImports.join('\\n')}\n\nexport const tools = [${toolsExports.join(', ')}]`,\n );\n this.logger.info('Bundling Mastra done');\n\n this.logger.info('Copying public files');\n await this.copyPublic(dirname(mastraEntryFile), outputDirectory);\n this.logger.info('Done copying public files');\n\n // For Software Factory projects, write a deterministic deployment marker\n // after public assets (including the SPA) have been copied.\n if (analyzedBundleInfo.projectType === 'factory') {\n await this.writeFactoryMarker(outputDirectory);\n }\n\n this.logger.info('Copying .npmrc file');\n await this.copyDOTNPMRC({ outputDirectory, rootDir: projectRoot });\n\n this.logger.info('Done copying .npmrc file');\n\n this.logger.info('Installing dependencies');\n await this.installDependencies(outputDirectory, projectRoot, transitiveWorkspaceDependencies.resolutions);\n this.logger.info('Done installing dependencies');\n\n if (Object.keys(transitiveWorkspaceDependencies.resolutions).length === 0) {\n this.logger.info('Generating package-lock.json for deploy');\n await this.generateNpmLockfile(join(outputDirectory, this.outputDir));\n this.logger.info('Done generating package-lock.json');\n } else {\n this.logger.warn(\n 'Skipping package-lock.json generation because the output contains packed workspace dependencies',\n );\n }\n } catch (error) {\n if (error instanceof MastraError && error.id === 'DEPLOYER_BUNDLER_FACTORY_UI_MISSING') {\n throw error;\n }\n\n const message = error instanceof Error ? error.message : String(error);\n throw new MastraError(\n {\n id: 'DEPLOYER_BUNDLER_BUNDLE_STAGE_FAILED',\n text: `Failed during bundler bundle stage: ${message}`,\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.SYSTEM,\n },\n error,\n );\n }\n }\n\n async lint(_entryFile: string, _outputDirectory: string, toolsPaths: (string | string[])[]): Promise<void> {\n const toolsInputOptions = await this.listToolsInputOptions(toolsPaths);\n const toolsLength = Object.keys(toolsInputOptions).length;\n if (toolsLength > 0) {\n this.logger.info('Found tools', { count: toolsLength });\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA6BA,MAAa,aAAa,OAAO,YAAY;AAE7C,MAAM,mBAAmB;;AAEzB,MAAM,wBAAwB;AAC9B,MAAM,uBAAuB;AAC7B,MAAM,yBAAyB;;AAE/B,MAAM,2BAA2B;;AAEjC,MAAM,0BAA0B;AAgBhC,MAAM,kBAAkB,UAA2C;CACjE,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAC5D,OAAO,CAAC;CAGV,OAAO,OAAO,YACZ,OAAO,QAAQ,KAAK,CAAC,CAAC,QAAQ,UAAqC,OAAO,MAAM,OAAO,QAAQ,CACjG;AACF;;;;;;;;;;;AAYA,MAAa,yBAAyB,SAA0B;CAC9D,IAAI,yBAAyB,KAAK,IAAI,KAAK,uBAAuB,KAAK,IAAI,GACzE,OAAO;CAGT,IAAI,KAAK,WAAW,gBAAgB,GAAG;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