@mastra/deployer 1.82.0-alpha.1 → 1.82.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/_types/{@internal_deployer → @internal_deployer@0.0.0}/dist/bundler.d.ts +1 -1
  2. package/dist/{analyze-HiY86ees.js → analyze-CW9fEusV.js} +2 -2
  3. package/dist/{analyze-HiY86ees.js.map → analyze-CW9fEusV.js.map} +1 -1
  4. package/dist/{analyze-DLPJyolh.cjs → analyze-DNnGuzqf.cjs} +2 -2
  5. package/dist/{analyze-DLPJyolh.cjs.map → analyze-DNnGuzqf.cjs.map} +1 -1
  6. package/dist/build/analyze/analyzeEntry.d.ts +1 -1
  7. package/dist/build/analyze.cjs +1 -1
  8. package/dist/build/analyze.d.ts +1 -1
  9. package/dist/build/analyze.js +1 -1
  10. package/dist/build/babel/remove-all-options-except.d.ts +1 -1
  11. package/dist/build/bundlerOptions.d.ts +2 -2
  12. package/dist/build/deployer.d.ts +2 -2
  13. package/dist/build/index.cjs +3 -3
  14. package/dist/build/index.js +3 -3
  15. package/dist/build/plugins/remove-all-except.d.ts +1 -1
  16. package/dist/build/serverOptions.d.ts +1 -1
  17. package/dist/build/shared/extract-mastra-option.d.ts +1 -1
  18. package/dist/build/watcher.d.ts +2 -1
  19. package/dist/build/watcher.d.ts.map +1 -1
  20. package/dist/{build-D8q_n1TB.cjs → build-Cc9X11g7.cjs} +5 -5
  21. package/dist/build-Cc9X11g7.cjs.map +1 -0
  22. package/dist/{build-UJ6VAhJQ.js → build-PqRB5M-E.js} +5 -5
  23. package/dist/build-PqRB5M-E.js.map +1 -0
  24. package/dist/bundler/index.cjs +1 -1
  25. package/dist/bundler/index.d.ts +2 -2
  26. package/dist/bundler/index.d.ts.map +1 -1
  27. package/dist/bundler/index.js +1 -1
  28. package/dist/bundler/workspaceDependencies.d.ts +1 -1
  29. package/dist/{bundler-DIit40UT.cjs → bundler-8GO8sXwa.cjs} +4 -4
  30. package/dist/{bundler-DIit40UT.cjs.map → bundler-8GO8sXwa.cjs.map} +1 -1
  31. package/dist/{bundler-9D5zGgBR.js → bundler-DRlNM9-F.js} +4 -4
  32. package/dist/{bundler-9D5zGgBR.js.map → bundler-DRlNM9-F.js.map} +1 -1
  33. package/dist/deploy/base.d.ts +1 -1
  34. package/dist/deploy/log.d.ts +1 -1
  35. package/dist/docs/SKILL.md +1 -1
  36. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  37. package/dist/index.cjs +3 -3
  38. package/dist/index.js +3 -3
  39. package/dist/server/index.d.ts +2 -2
  40. package/dist/services/deps.d.ts +12 -2
  41. package/dist/services/deps.d.ts.map +1 -1
  42. package/dist/services/index.cjs +1 -1
  43. package/dist/services/index.js +1 -1
  44. package/dist/{services-CtVt5CJq.cjs → services-DbgqQ_yI.cjs} +164 -9
  45. package/dist/services-DbgqQ_yI.cjs.map +1 -0
  46. package/dist/{services-CXZJN9er.js → services-PA2YqqQJ.js} +165 -10
  47. package/dist/services-PA2YqqQJ.js.map +1 -0
  48. package/package.json +9 -9
  49. package/dist/build-D8q_n1TB.cjs.map +0 -1
  50. package/dist/build-UJ6VAhJQ.js.map +0 -1
  51. package/dist/services-CXZJN9er.js.map +0 -1
  52. package/dist/services-CtVt5CJq.cjs.map +0 -1
  53. /package/dist/_types/{@hono_node-server → @hono_node-server@2.1.5}/dist/index.d.mts +0 -0
  54. /package/dist/_types/{@hono_node-server → @hono_node-server@2.1.5}/package.json +0 -0
  55. /package/dist/_types/{@internal_core → @internal_core@0.1.4}/dist/base/index.d.ts +0 -0
  56. /package/dist/_types/{@internal_core → @internal_core@0.1.4}/dist/index-Diz1p9N7.d.ts +0 -0
  57. /package/dist/_types/{@internal_core → @internal_core@0.1.4}/dist/logger/index.d.ts +0 -0
  58. /package/dist/_types/{@internal_core → @internal_core@0.1.4}/package.json +0 -0
  59. /package/dist/_types/{@internal_deployer/dist/_types/@internal_core → @internal_deployer@0.0.0/dist/_types/@internal_core@0.1.4}/dist/index-Diz1p9N7.d.ts +0 -0
  60. /package/dist/_types/{@internal_deployer/dist/_types/@internal_core → @internal_deployer@0.0.0/dist/_types/@internal_core@0.1.4}/dist/logger/index.d.ts +0 -0
  61. /package/dist/_types/{@internal_deployer → @internal_deployer@0.0.0}/dist/deployer.d.ts +0 -0
  62. /package/dist/_types/{@internal_deployer → @internal_deployer@0.0.0}/dist/index.d.ts +0 -0
  63. /package/dist/_types/{@internal_deployer → @internal_deployer@0.0.0}/package.json +0 -0
  64. /package/dist/_types/{@mastra_hono → @mastra_hono@1.7.24-alpha.3}/dist/auth-middleware.d.ts +0 -0
  65. /package/dist/_types/{@mastra_hono → @mastra_hono@1.7.24-alpha.3}/dist/browser-stream/index.d.ts +0 -0
  66. /package/dist/_types/{@mastra_hono → @mastra_hono@1.7.24-alpha.3}/dist/index.d.ts +0 -0
  67. /package/dist/_types/{@mastra_hono → @mastra_hono@1.7.24-alpha.3}/package.json +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"services-PA2YqqQJ.js","names":[],"sources":["../../_internal-core/dist/logger/index.js","../../_internal-core/dist/base/index.js","../src/deploy/log.ts","../src/services/deps.ts","../src/services/env.ts","../src/services/fs.ts"],"sourcesContent":["import { Transform } from \"stream\";\n// src/logger/adapter.ts\nfunction isAdaptableLogger(logger) {\n\treturn typeof logger.__attachObservability === \"function\";\n}\n/**\n* Export a tracked exception through the adapter sink, mirroring the\n* DualLogger dual-write shape (`errorId`/`domain`/`category`/`details`/`cause`\n* when present on a MastraError-like value). Never throws into the caller.\n*/\nfunction exportTrackedException(ctx, error, metadata) {\n\tif (!ctx?.options.export) return;\n\ttry {\n\t\tconst mastraError = error;\n\t\tctx.getLogSink()?.error(error.message, {\n\t\t\t...mastraError.id !== void 0 ? { errorId: mastraError.id } : {},\n\t\t\t...mastraError.domain !== void 0 ? { domain: mastraError.domain } : {},\n\t\t\t...mastraError.category !== void 0 ? { category: mastraError.category } : {},\n\t\t\t...mastraError.details !== void 0 ? { details: mastraError.details } : {},\n\t\t\t...error.cause instanceof Error ? { cause: error.cause.message } : {},\n\t\t\t...metadata\n\t\t});\n\t} catch {}\n}\n/**\n* Adapt IMastraLogger's variadic args into the structured `data` payload of\n* an exported log record. Extracts the first plain object as data,\n* serializes an Error arg, and collects remaining primitives under `args`\n* so the derived record preserves all context from the native call.\n*/\nfunction buildLogRecordData(args) {\n\tconst objectData = args.find((arg) => arg !== null && typeof arg === \"object\" && !Array.isArray(arg) && !(arg instanceof Error));\n\tconst errorArg = args.find((arg) => arg instanceof Error);\n\tconst extraArgs = args.filter((arg) => arg !== objectData && arg !== errorArg);\n\tif (!objectData && !errorArg && extraArgs.length === 0) return void 0;\n\treturn {\n\t\t...objectData ?? {},\n\t\t...errorArg ? { error: {\n\t\t\tname: errorArg.name,\n\t\t\tmessage: errorArg.message,\n\t\t\tstack: errorArg.stack\n\t\t} } : {},\n\t\t...extraArgs.length > 0 ? { args: extraArgs } : {}\n\t};\n}\n// src/logger/noop-logger.ts\nconst noopLogger = {\n\tdebug: () => {},\n\tinfo: () => {},\n\twarn: () => {},\n\terror: () => {},\n\tcleanup: async () => {},\n\tgetTransports: () => /* @__PURE__ */ new Map(),\n\ttrackException: () => {},\n\tlistLogs: async () => ({\n\t\tlogs: [],\n\t\ttotal: 0,\n\t\tpage: 1,\n\t\tperPage: 100,\n\t\thasMore: false\n\t}),\n\tlistLogsByRunId: async () => ({\n\t\tlogs: [],\n\t\ttotal: 0,\n\t\tpage: 1,\n\t\tperPage: 100,\n\t\thasMore: false\n\t})\n};\n// src/logger/index.ts\nconst RegisteredLogger = {\n\tAGENT: \"AGENT\",\n\tOBSERVABILITY: \"OBSERVABILITY\",\n\tAUTH: \"AUTH\",\n\tBROWSER: \"BROWSER\",\n\tNETWORK: \"NETWORK\",\n\tWORKFLOW: \"WORKFLOW\",\n\tLLM: \"LLM\",\n\tTTS: \"TTS\",\n\tVOICE: \"VOICE\",\n\tVECTOR: \"VECTOR\",\n\tBUNDLER: \"BUNDLER\",\n\tDEPLOYER: \"DEPLOYER\",\n\tMEMORY: \"MEMORY\",\n\tSTORAGE: \"STORAGE\",\n\tEMBEDDINGS: \"EMBEDDINGS\",\n\tMCP_SERVER: \"MCP_SERVER\",\n\tSERVER_CACHE: \"SERVER_CACHE\",\n\tSERVER: \"SERVER\",\n\tWORKSPACE: \"WORKSPACE\",\n\tCHANNEL: \"CHANNEL\"\n};\nconst LogLevel = {\n\tDEBUG: \"debug\",\n\tINFO: \"info\",\n\tWARN: \"warn\",\n\tERROR: \"error\",\n\tNONE: \"silent\"\n};\nvar LoggerTransport = class extends Transform {\n\tconstructor(opts = {}) {\n\t\tsuper({\n\t\t\t...opts,\n\t\t\tobjectMode: true\n\t\t});\n\t}\n\tasync listLogsByRunId(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args?.page ?? 1,\n\t\t\tperPage: _args?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogs(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args?.page ?? 1,\n\t\t\tperPage: _args?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\nconst createCustomTransport = (stream, listLogs, listLogsByRunId) => {\n\tlet transport = stream;\n\tif (listLogs) transport.listLogs = listLogs;\n\tif (listLogsByRunId) transport.listLogsByRunId = listLogsByRunId;\n\treturn transport;\n};\nvar MastraLogger = class {\n\tname;\n\tlevel;\n\ttransports;\n\tconstructor(options = {}) {\n\t\tthis.name = options.name || \"Mastra\";\n\t\tthis.level = options.level || LogLevel.ERROR;\n\t\tthis.transports = new Map(Object.entries(options.transports || {}));\n\t}\n\tgetTransports() {\n\t\treturn this.transports;\n\t}\n\ttrackException(_error, _metadata) {}\n\tasync listLogs(transportId, params) {\n\t\tif (!transportId || !this.transports.has(transportId)) return {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: params?.page ?? 1,\n\t\t\tperPage: params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t\treturn this.transports.get(transportId).listLogs?.(params) ?? {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: params?.page ?? 1,\n\t\t\tperPage: params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogsByRunId({ transportId, runId, fromDate, toDate, logLevel, filters, page, perPage }) {\n\t\tif (!transportId || !this.transports.has(transportId) || !runId) return {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: page ?? 1,\n\t\t\tperPage: perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t\treturn this.transports.get(transportId).listLogsByRunId?.({\n\t\t\trunId,\n\t\t\tfromDate,\n\t\t\ttoDate,\n\t\t\tlogLevel,\n\t\t\tfilters,\n\t\t\tpage,\n\t\t\tperPage\n\t\t}) ?? {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: page ?? 1,\n\t\t\tperPage: perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\nvar ConsoleLogger = class ConsoleLogger extends MastraLogger {\n\tcomponent;\n\tfilter;\n\t#adapterContext;\n\tconstructor(options = {}) {\n\t\tsuper(options);\n\t\tthis.component = options.component;\n\t\tthis.filter = options.filter;\n\t}\n\t/**\n\t* Adapter hook (see `AdaptableLogger`): enables native trace correlation\n\t* (trace_id/span_id appended to console output) and observability export\n\t* derived from the same record. Called by Mastra during setup.\n\t*/\n\t__attachObservability(ctx) {\n\t\tthis.#adapterContext = ctx;\n\t}\n\tchild(componentOrBindings) {\n\t\tconst component = typeof componentOrBindings === \"string\" ? componentOrBindings : componentOrBindings?.component ?? this.component;\n\t\tconst child = new ConsoleLogger({\n\t\t\tname: this.name,\n\t\t\tlevel: this.level,\n\t\t\tcomponent,\n\t\t\tfilter: this.filter\n\t\t});\n\t\tif (this.#adapterContext) child.__attachObservability(this.#adapterContext);\n\t\treturn child;\n\t}\n\t/**\n\t* Native-record correlation: when a span is active, append the trace\n\t* fields object to the console args so every destination sees them.\n\t*/\n\t#correlate(args) {\n\t\tconst ctx = this.#adapterContext;\n\t\tif (!ctx?.options.correlation) return args;\n\t\ttry {\n\t\t\tconst fields = ctx.resolveTraceFields();\n\t\t\treturn fields ? [...args, fields] : args;\n\t\t} catch {\n\t\t\treturn args;\n\t\t}\n\t}\n\t/**\n\t* Export the record derived from the same native call to observability.\n\t* Mirrors DualLogger semantics: export is independent of the console\n\t* level filter, and never throws into the caller.\n\t*/\n\t#export(level, message, args) {\n\t\tconst ctx = this.#adapterContext;\n\t\tif (!ctx?.options.export) return;\n\t\ttry {\n\t\t\tctx.getLogSink()?.[level](message, buildLogRecordData(args));\n\t\t} catch {}\n\t}\n\tshouldLog(level, message, args) {\n\t\tif (!this.filter) return true;\n\t\ttry {\n\t\t\treturn this.filter({\n\t\t\t\tcomponent: this.component,\n\t\t\t\tlevel,\n\t\t\t\tmessage,\n\t\t\t\targs\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tconsole.error(`[Logger] Filter error for component=${this.component} level=${level}:`, e);\n\t\t\treturn true;\n\t\t}\n\t}\n\tprefix() {\n\t\treturn this.component ? `[${this.component}] ` : \"\";\n\t}\n\tdebug(message, ...args) {\n\t\tif (this.level === LogLevel.DEBUG && this.shouldLog(LogLevel.DEBUG, message, args)) console.info(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"debug\", message, args);\n\t}\n\tinfo(message, ...args) {\n\t\tif ((this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.INFO, message, args)) console.info(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"info\", message, args);\n\t}\n\twarn(message, ...args) {\n\t\tif ((this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.WARN, message, args)) console.warn(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"warn\", message, args);\n\t}\n\terror(message, ...args) {\n\t\tif ((this.level === LogLevel.ERROR || this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.ERROR, message, args)) console.error(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"error\", message, args);\n\t}\n\ttrackException(error, metadata) {\n\t\texportTrackedException(this.#adapterContext, error, metadata);\n\t}\n\tasync listLogs(_transportId, _params) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _params?.page ?? 1,\n\t\t\tperPage: _params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogsByRunId(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args.page ?? 1,\n\t\t\tperPage: _args.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\nexport { ConsoleLogger, LogLevel, LoggerTransport, MastraLogger, RegisteredLogger, buildLogRecordData, createCustomTransport, exportTrackedException, isAdaptableLogger, noopLogger };\n\n//# sourceMappingURL=index.js.map","import { ConsoleLogger, RegisteredLogger } from \"../logger/index.js\";\n// src/base/MastraBase.ts\nvar MastraBase = class {\n\tcomponent = RegisteredLogger.LLM;\n\tlogger;\n\tname;\n\t#rawConfig;\n\tconstructor({ component, name, rawConfig }) {\n\t\tthis.component = component || RegisteredLogger.LLM;\n\t\tthis.name = name;\n\t\tthis.#rawConfig = rawConfig;\n\t\tthis.logger = new ConsoleLogger({ name: `${this.component} - ${this.name}` });\n\t}\n\t/**\n\t* Returns the raw storage configuration this primitive was created from,\n\t* or undefined if it was created from code.\n\t*/\n\ttoRawConfig() {\n\t\treturn this.#rawConfig;\n\t}\n\t/**\n\t* Sets the raw storage configuration for this primitive.\n\t* @internal\n\t*/\n\t__setRawConfig(rawConfig) {\n\t\tthis.#rawConfig = rawConfig;\n\t}\n\t/**\n\t* Set the logger for the agent\n\t* @param logger\n\t*/\n\t__setLogger(logger) {\n\t\tthis.logger = \"child\" in logger && typeof logger.child === \"function\" ? logger.child({ component: this.component }) : logger;\n\t}\n};\nexport { MastraBase };\n\n//# sourceMappingURL=index.js.map","import { spawn } from 'node:child_process';\nimport { Writable } from 'node:stream';\nimport type { IMastraLogger } from '@internal/core/logger';\n\nexport const createPinoStream = (logger: IMastraLogger) => {\n return new Writable({\n write(chunk, _encoding, callback) {\n // Convert Buffer/string to string and trim whitespace\n const line = chunk.toString().trim();\n\n if (line) {\n console.info(line);\n // Log each line through Pino\n logger.info(line);\n }\n\n callback();\n },\n });\n};\n\n/**\n * Args are joined into a shell command (`shell: true` is required for package\n * manager shims on Windows), so only allow characters that appear in package\n * specifiers and CLI flags — never shell metacharacters (CodeQL\n * js/shell-command-constructed-from-input).\n */\nconst SAFE_SHELL_ARG = /^[\\w@%+=:,./^~-]*$/;\n\nexport function createChildProcessLogger({ logger, root }: { logger: IMastraLogger; root: string }) {\n const pinoStream = createPinoStream(logger);\n return async ({ cmd, args, env }: { cmd: string; args: string[]; env: Record<string, string> }) => {\n try {\n for (const arg of args) {\n if (!SAFE_SHELL_ARG.test(arg)) {\n throw new Error(`Refusing to pass unsafe argument to shell command: ${JSON.stringify(arg)}`);\n }\n }\n const subprocess = spawn(cmd, args, {\n cwd: root,\n shell: true,\n env,\n // No stdin for the child process — it doesn't need interactive input\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n\n let stdout = '';\n let stderr = '';\n subprocess.stdout?.on('data', chunk => {\n stdout += chunk.toString();\n });\n subprocess.stderr?.on('data', chunk => {\n stderr += chunk.toString();\n });\n\n // Pipe stdout and stderr through the logging stream.\n // { end: false } prevents the first stream to close from ending pinoStream\n // while the other may still be writing.\n subprocess.stdout?.pipe(pinoStream, { end: false });\n subprocess.stderr?.pipe(pinoStream, { end: false });\n\n // Wait for the process to complete\n return new Promise((resolve, reject) => {\n subprocess.on('close', code => {\n pinoStream.end();\n if (code === 0) {\n resolve({ success: true, stdout, stderr });\n } else {\n reject(Object.assign(new Error(`Process exited with code ${code}`), { stdout, stderr }));\n }\n });\n\n subprocess.on('error', error => {\n pinoStream.end();\n logger.error('Process failed', { error });\n reject(error);\n });\n });\n } catch (error) {\n console.error(error);\n logger.error('Process failed', { error });\n pinoStream.end();\n return { success: false, error };\n }\n };\n}\n","import fs from 'node:fs';\nimport fsPromises from 'node:fs/promises';\nimport path, { dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { MastraBase } from '@internal/core/base';\nimport { ErrorCategory, ErrorDomain, MastraError } from '@internal/core/error';\nimport type { BundlerConfig } from '@internal/deployer';\nimport { readJSON, writeJSON, ensureFile } from 'fs-extra/esm';\nimport type { PackageJson } from 'type-fest';\nimport { parse, parseAllDocuments, stringify } from 'yaml';\n\nimport { createChildProcessLogger } from '../deploy/log.js';\n\ntype PackageManager = 'npm' | 'yarn' | 'pnpm' | 'bun';\n\n/** Version used to pack private workspace packages whose package.json has no `version`. */\nexport const WORKSPACE_PLACEHOLDER_VERSION = '0.0.0';\n\n// Write via temp file + rename so an interrupted write never leaves a truncated manifest.\nasync function writeManifestAtomically(manifestPath: string, contents: string, inFlight?: Set<string>) {\n const tmpPath = `${manifestPath}.${process.pid}.${Date.now()}.tmp`;\n inFlight?.add(tmpPath);\n try {\n const { mode } = await fsPromises.stat(manifestPath);\n await fsPromises.writeFile(tmpPath, contents, { mode });\n await fsPromises.chmod(tmpPath, mode);\n await fsPromises.rename(tmpPath, manifestPath);\n } catch (error) {\n await fsPromises.rm(tmpPath, { force: true });\n throw error;\n } finally {\n inFlight?.delete(tmpPath);\n }\n}\n\n/**\n * Package managers refuse to pack a manifest without a version, and pnpm/bun also\n * resolve `workspace:` ranges from the dependency's manifest. So every versionless\n * package in `dirs` gets the placeholder version for the whole of `operation`, and\n * the original manifests are restored afterwards — also on SIGINT/SIGTERM.\n */\nexport async function withPlaceholderVersions<T>(dirs: string[], operation: () => Promise<T>): Promise<T> {\n const acquired: string[] = [];\n try {\n for (const dir of new Set(dirs.map(dir => path.resolve(dir)))) {\n const manifestPath = path.join(dir, 'package.json');\n let lease = placeholderLeases.get(manifestPath);\n // A lease whose last owner is restoring it can't be joined; wait and start a fresh one.\n while (lease?.releasing) {\n await lease.releasing.catch(() => {});\n lease = placeholderLeases.get(manifestPath);\n }\n if (lease) {\n lease.refs++;\n } else {\n lease = { refs: 1, injected: false, ready: Promise.resolve() };\n lease.ready = injectPlaceholderVersion(manifestPath, lease);\n placeholderLeases.set(manifestPath, lease);\n installSignalHandlers();\n }\n acquired.push(manifestPath);\n await lease.ready;\n }\n return await operation();\n } finally {\n try {\n for (const manifestPath of acquired) {\n await releasePlaceholderVersion(manifestPath);\n }\n } finally {\n if (placeholderLeases.size === 0) {\n removeSignalHandlers();\n }\n }\n }\n}\n\ninterface PlaceholderLease {\n refs: number;\n original?: string;\n injected: boolean;\n ready: Promise<void>;\n releasing?: Promise<void>;\n}\n\n// Shared across calls so one bundle can't restore a manifest another is still packing.\nconst placeholderLeases = new Map<string, PlaceholderLease>();\nconst inFlightTmpPaths = new Set<string>();\n\nasync function injectPlaceholderVersion(manifestPath: string, lease: PlaceholderLease) {\n const original = await fsPromises.readFile(manifestPath, 'utf-8').catch(() => undefined);\n if (original === undefined) return;\n let manifest: PackageJson;\n try {\n manifest = JSON.parse(original) as PackageJson;\n } catch (error) {\n throw new Error(`Failed to parse ${manifestPath}: ${(error as Error).message}`, { cause: error });\n }\n if (manifest.version) return;\n lease.original = original;\n // Mark before writing so a signal mid-write still restores this manifest.\n lease.injected = true;\n await writeManifestAtomically(\n manifestPath,\n JSON.stringify({ ...manifest, version: WORKSPACE_PLACEHOLDER_VERSION }, null, 2) + '\\n',\n inFlightTmpPaths,\n );\n}\n\nasync function releasePlaceholderVersion(manifestPath: string) {\n const lease = placeholderLeases.get(manifestPath)!;\n if (--lease.refs > 0) return;\n lease.releasing = (async () => {\n await lease.ready.catch(() => {});\n try {\n if (lease.injected) {\n await writeManifestAtomically(manifestPath, lease.original!, inFlightTmpPaths);\n lease.injected = false;\n }\n } finally {\n placeholderLeases.delete(manifestPath);\n }\n })();\n await lease.releasing;\n}\n\nfunction restorePlaceholderVersionsSync() {\n // Removing in-flight temp files keeps them out of later tarballs and makes any\n // pending rename fail instead of overwriting the restored manifest.\n for (const tmpPath of inFlightTmpPaths) {\n fs.rmSync(tmpPath, { force: true });\n }\n inFlightTmpPaths.clear();\n for (const [manifestPath, lease] of placeholderLeases) {\n if (lease.injected) {\n fs.writeFileSync(manifestPath, lease.original!);\n lease.injected = false;\n }\n }\n}\n\nfunction onPlaceholderSignal(signal: NodeJS.Signals) {\n restorePlaceholderVersionsSync();\n removeSignalHandlers();\n process.kill(process.pid, signal);\n}\n\nfunction installSignalHandlers() {\n if (process.listeners('SIGINT').includes(onPlaceholderSignal)) return;\n process.once('SIGINT', onPlaceholderSignal);\n process.once('SIGTERM', onPlaceholderSignal);\n}\n\nfunction removeSignalHandlers() {\n process.off('SIGINT', onPlaceholderSignal);\n process.off('SIGTERM', onPlaceholderSignal);\n}\n\ninterface LockFileInfo {\n path: string;\n filename: string;\n packageManager: PackageManager;\n}\n\ninterface ArchitectureOptions {\n os?: string[];\n cpu?: string[];\n libc?: string[];\n}\n\ninterface InstallOptions extends ArchitectureOptions {\n pnpmWorkspaceSettings?: BundlerConfig['pnpmWorkspaceSettings'];\n pnpmOverrides?: Record<string, string>;\n pnpmNodeLinker?: 'hoisted';\n /** Patch key -> path relative to the output directory. */\n patchedDependencies?: Record<string, string>;\n /** Source settings that change which packages get installed, already checked to work outside the source workspace. */\n pnpmResolutionSettings?: Record<string, unknown>;\n /** The `pnpm` field of the source root package.json, set only when the project runs pnpm 10 or older. */\n pnpmManifestSettings?: Record<string, unknown>;\n}\n\nconst PNPM_PATCHES_DIR = 'pnpm-patches';\nconst BUN_PATCHES_DIR = 'bun-patches';\n\nconst PNPM_CONFIG_KEYS_TO_COPY = new Set([\n 'allowBuilds',\n 'onlyBuiltDependencies',\n 'ignoredBuiltDependencies',\n 'neverBuiltDependencies',\n 'minimumReleaseAge',\n 'minimumReleaseAgeExclude',\n 'trustPolicy',\n 'trustPolicyExclude',\n 'trustPolicyIgnoreAfter',\n 'supportedArchitectures',\n]);\n\n// Specs resolved against the source workspace, which the output directory can't install.\nconst SOURCE_WORKSPACE_SPEC = /^(?:file:|link:|portal:|workspace:|catalog:|\\.{1,2}(?:[/\\\\]|$)|[/\\\\]|~[/\\\\])/;\n\n// supportedArchitectures is generated from deployer architecture targets, so it can't be set explicitly.\n// neverBuiltDependencies switches pnpm 10 into deny-list mode, which runs every build script it doesn't name.\nconst PNPM_EXPLICIT_SETTING_KEYS = new Set(\n [...PNPM_CONFIG_KEYS_TO_COPY, 'blockExoticSubdeps'].filter(\n key => key !== 'supportedArchitectures' && key !== 'neverBuiltDependencies',\n ),\n);\n\nfunction serializePnpmWorkspaceSettings(settings: BundlerConfig['pnpmWorkspaceSettings']) {\n // Untyped JS configs can pass undefined; treat it as omitted so the copied source setting survives.\n const definedSettings = Object.entries(settings ?? {}).filter(([, value]) => value !== undefined);\n return definedSettings.map(([key, value]) => {\n if (!PNPM_EXPLICIT_SETTING_KEYS.has(key)) {\n throw new MastraError({\n id: 'DEPLOYER_INVALID_PNPM_WORKSPACE_SETTING',\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.USER,\n text: `pnpm workspace setting ${JSON.stringify(key)} isn't supported in bundler.pnpmWorkspaceSettings. Supported settings: ${[...PNPM_EXPLICIT_SETTING_KEYS].join(', ')}.`,\n });\n }\n const block = stringify({ [key]: value }).trimEnd();\n validatePnpmBuildApprovals(key, block);\n return block;\n });\n}\n\n// Every unindented line starts a new top-level entry, except comments and sequence items, which YAML allows at\n// column 0 under the key above them. Treating any other line as a continuation would copy it with the previous\n// block, such as an auth token after a copied key.\nfunction isTopLevelEntry(line: string) {\n return /^[^\\s#-]/.test(line);\n}\n\nfunction getTopLevelYamlKey(line: string) {\n const match = /^(?:\"([\\w-]+)\"|'([\\w-]+)'|([\\w-]+))\\s*:/.exec(line);\n return match?.[1] ?? match?.[2] ?? match?.[3];\n}\n\nconst PNPM_IGNORED_BUILDS_ERROR = 'ERR_PNPM_IGNORED_BUILDS';\n\nexport function getPnpmIgnoredBuildPackages(output: string): string[] {\n const match = new RegExp(`\\\\[?${PNPM_IGNORED_BUILDS_ERROR}\\\\]?[^\\\\n]*Ignored build scripts:\\\\s*([^\\\\n]+)`).exec(\n output,\n );\n if (!match?.[1]) return [];\n\n return match[1]\n .split(',')\n .map(specifier => specifier.trim())\n .filter(Boolean)\n .map(specifier => {\n if (specifier.startsWith('@')) {\n const versionSeparator = specifier.indexOf('@', 1);\n return versionSeparator === -1 ? specifier : specifier.slice(0, versionSeparator);\n }\n return specifier.split('@', 1)[0]!;\n });\n}\n\nfunction validatePnpmBuildApprovals(key: string, block: string): void {\n if (key !== 'allowBuilds' && key !== 'onlyBuiltDependencies') return;\n\n let value: unknown;\n try {\n value = (parse(block) as Record<string, unknown>)[key];\n } catch (error) {\n throw new MastraError(\n {\n id: 'DEPLOYER_INVALID_PNPM_BUILD_APPROVAL_CONFIG',\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.USER,\n details: { key },\n text: `Invalid pnpm ${key} configuration`,\n },\n error,\n );\n }\n\n const invalidEntries =\n key === 'allowBuilds'\n ? value && typeof value === 'object' && !Array.isArray(value)\n ? Object.entries(value).filter(\n ([dependency, approval]) => dependency.trim().length === 0 || typeof approval !== 'boolean',\n )\n : [[key, value]]\n : Array.isArray(value) &&\n value.every(dependency => typeof dependency === 'string' && dependency.trim().length > 0)\n ? []\n : [[key, value]];\n\n if (invalidEntries.length === 0) return;\n const invalidEntryNames = invalidEntries.map(([entry]) => entry).join(', ');\n\n throw new MastraError({\n id: 'DEPLOYER_INVALID_PNPM_BUILD_APPROVAL_CONFIG',\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.USER,\n details: { key, invalidEntries: invalidEntryNames },\n text: `Invalid pnpm ${key} entries: ${invalidEntryNames}`,\n });\n}\n\n/**\n * Reads the `patchedDependencies` map from a pnpm workspace file. Paths are returned as declared,\n * i.e. relative to the workspace root. Returns an empty map for absent or unusable declarations.\n */\nexport function parsePnpmPatchedDependencies(source: string): Record<string, string> {\n let parsed: unknown;\n try {\n parsed = parse(source);\n } catch {\n return {};\n }\n\n const patched = (parsed as { patchedDependencies?: unknown } | null)?.patchedDependencies;\n if (!patched || typeof patched !== 'object' || Array.isArray(patched)) {\n return {};\n }\n\n const result: Record<string, string> = {};\n for (const [key, value] of Object.entries(patched as Record<string, unknown>)) {\n if (typeof value === 'string' && value.trim() && key.trim()) {\n result[key] = value.trim();\n }\n }\n\n return result;\n}\n\nexport function copyPnpmWorkspaceSettings(source: string, options: InstallOptions = {}) {\n const hasArchitecture = Boolean(options.os?.length || options.cpu?.length || options.libc?.length);\n const lines = source.split(/\\r?\\n/);\n const customBlocks = serializePnpmWorkspaceSettings(options.pnpmWorkspaceSettings);\n const blocks: string[] = [];\n const copiedKeys = new Set<string>();\n const shouldCopy = (key: string) =>\n PNPM_CONFIG_KEYS_TO_COPY.has(key) &&\n options.pnpmWorkspaceSettings?.[key] === undefined &&\n !(key === 'supportedArchitectures' && hasArchitecture);\n\n for (let index = 0; index < lines.length;) {\n if (!isTopLevelEntry(lines[index] ?? '')) {\n index += 1;\n continue;\n }\n\n const key = getTopLevelYamlKey(lines[index] ?? '');\n const start = index;\n index += 1;\n while (index < lines.length && !isTopLevelEntry(lines[index] ?? '')) {\n index += 1;\n }\n\n if (!key || !shouldCopy(key)) {\n continue;\n }\n\n const block = lines.slice(start, index).join('\\n').trimEnd();\n if (block) {\n validatePnpmBuildApprovals(key, block);\n blocks.push(block);\n copiedKeys.add(key);\n }\n }\n\n // The scanner keeps the source formatting but can't name every key, such as YAML explicit `? key` entries.\n // Those settings are copied from the parsed file instead.\n let parsedSource: Record<string, unknown> = {};\n try {\n const parsed = parse(source);\n parsedSource = isRecord(parsed) ? parsed : {};\n } catch {\n // An unparsable workspace file falls back to the keys the scanner copied.\n }\n\n // pnpm 10 also reads these keys from the `pnpm` field of package.json. The workspace file wins when both set one.\n const sourceSettings = [\n ...Object.entries(parsedSource),\n ...Object.entries(options.pnpmManifestSettings ?? {}).filter(([key]) => !Object.hasOwn(parsedSource, key)),\n ];\n for (const [key, value] of sourceSettings) {\n if (copiedKeys.has(key) || !shouldCopy(key) || value === undefined) continue;\n const block = stringify({ [key]: value }).trimEnd();\n validatePnpmBuildApprovals(key, block);\n blocks.push(block);\n copiedKeys.add(key);\n }\n\n if (hasArchitecture) {\n const architectureBlock = ['supportedArchitectures:'];\n if (options.os?.length) {\n architectureBlock.push(` os: ${JSON.stringify(options.os)}`);\n }\n if (options.cpu?.length) {\n architectureBlock.push(` cpu: ${JSON.stringify(options.cpu)}`);\n }\n if (options.libc?.length) {\n architectureBlock.push(` libc: ${JSON.stringify(options.libc)}`);\n }\n blocks.push(architectureBlock.join('\\n'));\n }\n\n for (const [key, value] of Object.entries(options.pnpmResolutionSettings ?? {})) {\n blocks.push(stringify({ [key]: value }).trimEnd());\n }\n\n if (options.pnpmOverrides && Object.keys(options.pnpmOverrides).length > 0) {\n blocks.push(\n [\n 'overrides:',\n ...Object.entries(options.pnpmOverrides).map(\n ([key, value]) => ` ${JSON.stringify(key)}: ${JSON.stringify(value)}`,\n ),\n ].join('\\n'),\n );\n }\n\n if (options.patchedDependencies && Object.keys(options.patchedDependencies).length > 0) {\n blocks.push(\n [\n 'patchedDependencies:',\n ...Object.entries(options.patchedDependencies).map(\n ([key, value]) => ` ${JSON.stringify(key)}: ${JSON.stringify(value)}`,\n ),\n ].join('\\n'),\n );\n // The bundled output only installs runtime dependencies, so patches declared for\n // dev-only or bundled-away packages are legitimately unused here.\n blocks.push('allowUnusedPatches: true');\n }\n\n if (options.pnpmNodeLinker) {\n blocks.push(`nodeLinker: ${options.pnpmNodeLinker}`);\n }\n\n return [\"packages:\\n - '.'\", ...blocks, ...customBlocks].join('\\n\\n') + '\\n';\n}\n\n// Semver characters only; versions are interpolated into a shell command.\nconst SAFE_PACKAGE_VERSION = /^[0-9A-Za-z.+-]+$/;\n\n/**\n * Yarn classic writes `# yarn lockfile v1` within the first two lines; Berry lockfiles never contain it.\n * Only the head of the file is read so large monorepo lockfiles are never loaded into memory.\n */\nasync function isYarnClassicLockfile(lockfilePath: string): Promise<boolean> {\n const handle = await fsPromises.open(lockfilePath, 'r');\n try {\n const buffer = Buffer.alloc(512);\n const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);\n return /^# yarn lockfile v1\\r?$/m.test(buffer.toString('utf-8', 0, bytesRead));\n } finally {\n await handle.close();\n }\n}\n\n/**\n * Removes overridden packages from every importer of a copied pnpm lockfile. When the Mastra app is the\n * workspace root, the root importer still resolves its workspace dependencies to `link:` versions. pnpm\n * keeps those versions although the output overrides them with packed tarballs, so the tarball is never\n * installed and the dependency symlink dangles. Without the entries, pnpm resolves them from the overrides.\n */\nasync function dropPnpmImporterDependencies(lockfilePath: string, packageNames: string[]): Promise<void> {\n const { leadingDocuments, project } = parsePnpmLockfile(await fsPromises.readFile(lockfilePath, 'utf-8'));\n const lockfile = project as {\n importers?: Record<string, Record<string, Record<string, unknown> | undefined> | undefined>;\n } | null;\n let changed = false;\n for (const importer of Object.values(lockfile?.importers ?? {})) {\n for (const field of ['dependencies', 'devDependencies', 'optionalDependencies']) {\n const dependencies = importer?.[field];\n for (const name of packageNames) {\n if (dependencies && name in dependencies) {\n delete dependencies[name];\n changed = true;\n }\n }\n }\n }\n if (changed) {\n const projectDocument = stringify(lockfile, { lineWidth: 0 });\n await fsPromises.writeFile(\n lockfilePath,\n leadingDocuments ? `${leadingDocuments}---\\n${projectDocument}` : projectDocument,\n );\n }\n}\n\n/**\n * Splits a pnpm lockfile into its project document and the documents before it. pnpm 11+ writes an\n * environment document first when `packageManager` or `configDependencies` is set.\n */\nfunction parsePnpmLockfile(source: string): { leadingDocuments: string; project: unknown } {\n const documents = parseAllDocuments(source);\n const project = documents.at(-1);\n if (project?.errors.length) {\n throw project.errors[0];\n }\n return {\n leadingDocuments: documents\n .slice(0, -1)\n .map(document => document.toString({ lineWidth: 0 }))\n .join(''),\n project: project ? project.toJS() : null,\n };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Reads the overrides the source install applied. The lockfile records them with `catalog:` and `$name`\n * references resolved, wherever they were declared (`pnpm-workspace.yaml`, or the `pnpm` field of\n * `package.json` on pnpm 10).\n */\nasync function readPnpmLockfileOverrides(\n lockfilePath: string,\n warn: (message: string) => void,\n): Promise<Record<string, string>> {\n let lockfile: unknown;\n try {\n lockfile = parsePnpmLockfile(await fsPromises.readFile(lockfilePath, 'utf-8')).project;\n } catch {\n return {};\n }\n\n const overrides = isRecord(lockfile) ? lockfile.overrides : undefined;\n if (!isRecord(overrides)) return {};\n\n const portable: Record<string, string> = {};\n for (const [selector, spec] of Object.entries(overrides)) {\n if (typeof spec !== 'string') continue;\n if (SOURCE_WORKSPACE_SPEC.test(spec)) {\n warn(`Skipping pnpm override \"${selector}\": \"${spec}\" can only be resolved from the source workspace.`);\n continue;\n }\n portable[selector] = spec;\n }\n return portable;\n}\n\n// `catalog:` reads the top-level `catalog`, or `catalogs.default` when that is where it is declared.\nfunction resolveCatalogSpec(workspace: Record<string, unknown>, name: string, spec: string): unknown {\n const catalogName = spec.slice('catalog:'.length) || 'default';\n const catalogs = isRecord(workspace.catalogs) ? workspace.catalogs : {};\n const catalog = catalogName === 'default' && isRecord(workspace.catalog) ? workspace.catalog : catalogs[catalogName];\n return isRecord(catalog) ? catalog[name] : undefined;\n}\n\n/** Returns the extension with catalog specs resolved, or the first spec the output directory can't install. */\nfunction resolvePackageExtension(\n workspace: Record<string, unknown>,\n extension: Record<string, unknown>,\n): { extension: Record<string, unknown> } | { name: string; spec: unknown } {\n const resolvedExtension: Record<string, unknown> = { ...extension };\n for (const field of ['dependencies', 'optionalDependencies', 'peerDependencies']) {\n const deps = extension[field];\n if (!isRecord(deps)) continue;\n const resolvedDeps: Record<string, string> = {};\n for (const [name, spec] of Object.entries(deps)) {\n const resolved =\n typeof spec === 'string' && spec.startsWith('catalog:') ? resolveCatalogSpec(workspace, name, spec) : spec;\n if (typeof resolved !== 'string' || SOURCE_WORKSPACE_SPEC.test(resolved)) {\n return { name, spec };\n }\n resolvedDeps[name] = resolved;\n }\n resolvedExtension[field] = resolvedDeps;\n }\n return { extension: resolvedExtension };\n}\n\n/**\n * Reads the source settings that change which packages get installed. They are copied from the source\n * workspace only and stay out of `bundler.pnpmWorkspaceSettings`, which accepts install-policy keys only.\n */\nfunction getPnpmResolutionSettings(\n sourceWorkspaceYaml: string,\n manifestSettings: Record<string, unknown>,\n warn: (message: string) => void,\n) {\n let parsed: unknown;\n try {\n parsed = parse(sourceWorkspaceYaml);\n } catch {\n parsed = {};\n }\n const workspace = { ...manifestSettings, ...(isRecord(parsed) ? parsed : {}) };\n\n const settings: Record<string, unknown> = {};\n\n const ignoredOptional = workspace.ignoredOptionalDependencies;\n if (Array.isArray(ignoredOptional) && ignoredOptional.every(name => typeof name === 'string')) {\n settings.ignoredOptionalDependencies = ignoredOptional;\n }\n\n if (isRecord(workspace.packageExtensions)) {\n const extensions: Record<string, unknown> = {};\n for (const [selector, extension] of Object.entries(workspace.packageExtensions)) {\n if (!isRecord(extension)) continue;\n const result = resolvePackageExtension(workspace, extension);\n if ('extension' in result) {\n extensions[selector] = result.extension;\n } else {\n warn(\n `Skipping pnpm packageExtensions \"${selector}\": ${JSON.stringify(result.spec)} for \"${result.name}\" can only be resolved from the source workspace.`,\n );\n }\n }\n if (Object.keys(extensions).length > 0) {\n settings.packageExtensions = extensions;\n }\n }\n\n return settings;\n}\n\nexport class Deps extends MastraBase {\n private packageManager: PackageManager;\n private rootDir: string;\n private lockFile: LockFileInfo | null;\n\n constructor(rootDir = process.cwd()) {\n super({ component: 'DEPLOYER', name: 'DEPS' });\n\n this.rootDir = rootDir;\n this.lockFile = this.findLockFile(rootDir);\n this.packageManager = this.lockFile?.packageManager ?? 'npm';\n }\n\n private findLockFile(dir: string): LockFileInfo | null {\n const lockFiles: Array<{ filename: string; packageManager: PackageManager }> = [\n { filename: 'pnpm-lock.yaml', packageManager: 'pnpm' },\n { filename: 'package-lock.json', packageManager: 'npm' },\n { filename: 'yarn.lock', packageManager: 'yarn' },\n { filename: 'bun.lock', packageManager: 'bun' },\n ];\n for (const lockFile of lockFiles) {\n const lockFilePath = path.join(dir, lockFile.filename);\n if (fs.existsSync(lockFilePath)) {\n return { ...lockFile, path: lockFilePath };\n }\n }\n const parentDir = path.resolve(dir, '..');\n if (parentDir !== dir) {\n return this.findLockFile(parentDir);\n }\n return null;\n }\n\n public getWorkspaceDependencyPath({ pkgName, version }: { pkgName: string; version: string }) {\n return `file:./workspace-module/${pkgName}-${version}.tgz`;\n }\n\n public async pack({\n dir,\n destination,\n sanitizedName,\n version,\n }: {\n dir: string;\n destination: string;\n sanitizedName: string;\n version: string;\n }) {\n const cpLogger = createChildProcessLogger({\n logger: this.logger,\n root: dir,\n });\n\n let packCmd = 'pack';\n let destinationFlag = `--pack-destination ${destination}`;\n if (this.packageManager === 'yarn') {\n if (this.lockFile && (await isYarnClassicLockfile(this.lockFile.path))) {\n if (!SAFE_PACKAGE_VERSION.test(version)) {\n throw new MastraError({\n id: 'DEPLOYER_INVALID_WORKSPACE_PACKAGE_VERSION',\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.USER,\n details: { dir, version: String(version) },\n text: `Invalid version ${JSON.stringify(version)} in workspace package at ${dir}`,\n });\n }\n // Yarn classic has no --out/%v; --filename takes the full output path.\n destinationFlag = `--filename ${destination}/${sanitizedName}-${version}.tgz`;\n } else {\n // %s includes an '@' at the start of packages names with an '@'\n // so we need to use our sanitizedName instead.\n destinationFlag = `--out ${destination}/${sanitizedName}-%v.tgz`;\n }\n }\n if (this.packageManager === 'bun') {\n // bun uses `pm pack` instead of `pack`\n packCmd = 'pm pack';\n // bun uses --destination instead of --pack-destination\n destinationFlag = `--destination ${destination}`;\n }\n\n return cpLogger({\n cmd: `${this.packageManager} ${packCmd} ${destinationFlag}`,\n args: [],\n env: {\n PATH: process.env.PATH!,\n },\n });\n }\n\n private findPnpmWorkspaceFile(dir: string): string | null {\n const workspaceYamlPath = path.join(dir, 'pnpm-workspace.yaml');\n if (fs.existsSync(workspaceYamlPath)) {\n return workspaceYamlPath;\n }\n\n const parentDir = path.resolve(dir, '..');\n if (parentDir !== dir) {\n return this.findPnpmWorkspaceFile(parentDir);\n }\n\n return null;\n }\n\n private async writePnpmConfig(dir: string, options: InstallOptions = {}) {\n const sourceWorkspaceYamlPath = this.findPnpmWorkspaceFile(this.rootDir);\n const sourceWorkspaceYaml = sourceWorkspaceYamlPath\n ? await fsPromises.readFile(sourceWorkspaceYamlPath, 'utf-8')\n : '';\n\n const patchedDependencies = sourceWorkspaceYamlPath\n ? await this.copyPnpmPatches(sourceWorkspaceYaml, path.dirname(sourceWorkspaceYamlPath), dir)\n : undefined;\n\n const warn = (message: string) => this.logger.warn(message);\n const sourceOverrides =\n this.lockFile?.packageManager === 'pnpm' ? await readPnpmLockfileOverrides(this.lockFile.path, warn) : {};\n const pnpmManifestSettings = await this.readPnpm10ManifestSettings(\n this.lockFile\n ? path.dirname(this.lockFile.path)\n : sourceWorkspaceYamlPath && path.dirname(sourceWorkspaceYamlPath),\n );\n\n await fsPromises.writeFile(\n path.join(dir, 'pnpm-workspace.yaml'),\n copyPnpmWorkspaceSettings(sourceWorkspaceYaml, {\n ...options,\n patchedDependencies,\n pnpmManifestSettings,\n pnpmResolutionSettings: getPnpmResolutionSettings(sourceWorkspaceYaml, pnpmManifestSettings, warn),\n // Packed workspace tarballs must win over any source override for the same package.\n pnpmOverrides: { ...sourceOverrides, ...options.pnpmOverrides },\n }),\n 'utf-8',\n );\n }\n\n /**\n * Returns the `pnpm` field of the workspace root package.json when the project declares pnpm 10 or older.\n * pnpm 11 stopped reading that field, so copying it for a newer or unknown pnpm could approve build scripts\n * the project's own install never ran.\n */\n private async readPnpm10ManifestSettings(rootDir: string | null | undefined): Promise<Record<string, unknown>> {\n if (!rootDir) return {};\n\n let manifest: unknown;\n try {\n manifest = await readJSON(path.join(rootDir, 'package.json'));\n } catch {\n return {};\n }\n if (!isRecord(manifest) || !isRecord(manifest.pnpm) || Object.keys(manifest.pnpm).length === 0) return {};\n\n const pnpmMajor = /^pnpm@(\\d+)\\./.exec(String(manifest.packageManager ?? ''))?.[1];\n if (pnpmMajor && Number(pnpmMajor) <= 10) {\n return manifest.pnpm;\n }\n const skippedKeys = Object.keys(manifest.pnpm).filter(\n key => PNPM_CONFIG_KEYS_TO_COPY.has(key) || key === 'packageExtensions' || key === 'ignoredOptionalDependencies',\n );\n if (!pnpmMajor && skippedKeys.length > 0) {\n this.logger.warn(\n `Not copying ${skippedKeys.join(', ')} from the \"pnpm\" field of package.json into the build output because the pnpm version is unknown. Set \"packageManager\" to the pnpm version you use, or move these settings to pnpm-workspace.yaml.`,\n );\n }\n return {};\n }\n\n /**\n * Resolves a declared patch path against the source workspace and verifies that, once symlinks\n * are followed, it still resolves inside the workspace. Returns the real path to copy from, or\n * `undefined` when the patch escapes the workspace or its file cannot be resolved.\n */\n private async resolvePatchSource(\n resolvedWorkspaceRoot: string,\n declaredPath: string,\n { key, label }: { key: string; label: string },\n ): Promise<string | undefined> {\n const sourcePath = path.resolve(resolvedWorkspaceRoot, declaredPath);\n if (!sourcePath.startsWith(`${resolvedWorkspaceRoot}${path.sep}`)) {\n this.logger.warn(`Skipping ${label} patch for \"${key}\": patch file is outside the workspace at ${sourcePath}`);\n return undefined;\n }\n\n // A patch path can stay lexically under the workspace while traversing a symlink whose target\n // lives outside it. copyFile follows symlinks, so compare the resolved real paths before copying.\n let realWorkspaceRoot: string;\n let realSourcePath: string;\n try {\n [realWorkspaceRoot, realSourcePath] = await Promise.all([\n fsPromises.realpath(resolvedWorkspaceRoot),\n fsPromises.realpath(sourcePath),\n ]);\n } catch {\n this.logger.warn(`Skipping ${label} patch for \"${key}\": patch file not found at ${sourcePath}`);\n return undefined;\n }\n\n if (!realSourcePath.startsWith(`${realWorkspaceRoot}${path.sep}`)) {\n this.logger.warn(\n `Skipping ${label} patch for \"${key}\": patch file is outside the workspace at ${realSourcePath}`,\n );\n return undefined;\n }\n\n return realSourcePath;\n }\n\n /**\n * Copies the patch files declared by the source workspace into the output directory and returns\n * the patch map rewritten to output-relative paths, so the patches survive the output install.\n */\n private async copyPnpmPatches(\n sourceWorkspaceYaml: string,\n sourceWorkspaceRoot: string,\n dir: string,\n ): Promise<Record<string, string>> {\n const declared = parsePnpmPatchedDependencies(sourceWorkspaceYaml);\n const rewritten: Record<string, string> = {};\n const usedFileNames = new Set<string>();\n const resolvedWorkspaceRoot = path.resolve(sourceWorkspaceRoot);\n\n for (const [key, declaredPath] of Object.entries(declared)) {\n const sourcePath = await this.resolvePatchSource(resolvedWorkspaceRoot, declaredPath, {\n key,\n label: 'pnpm',\n });\n if (!sourcePath) continue;\n\n let fileName = path.basename(sourcePath);\n if (usedFileNames.has(fileName)) {\n fileName = `${key.replace(/[^a-zA-Z0-9._-]/g, '_')}-${fileName}`;\n }\n usedFileNames.add(fileName);\n\n await fsPromises.mkdir(path.join(dir, PNPM_PATCHES_DIR), { recursive: true });\n await fsPromises.copyFile(sourcePath, path.join(dir, PNPM_PATCHES_DIR, fileName));\n rewritten[key] = `${PNPM_PATCHES_DIR}/${fileName}`;\n }\n\n return rewritten;\n }\n\n /**\n * Writes the `.yarnrc.yml` for the bundled output, recording the supported architectures so the\n * output install only resolves optional native binaries that match the deployment target.\n */\n private async writeYarnConfig(dir: string, options: ArchitectureOptions) {\n const yarnrcPath = path.join(dir, '.yarnrc.yml');\n const config = {\n supportedArchitectures: {\n cpu: options.cpu || [],\n os: options.os || [],\n libc: options.libc || [],\n },\n };\n\n await fsPromises.writeFile(\n yarnrcPath,\n `supportedArchitectures:\\n${Object.entries(config.supportedArchitectures)\n .map(([key, value]) => ` ${key}: ${JSON.stringify(value)}`)\n .join('\\n')}`,\n );\n }\n\n /**\n * Copies the source workspace's `.yarn/patches/` directory (Yarn Berry) into the output\n * directory so patches survive the output install. Yarn auto-discovers patches from this\n * directory and applies them per the lockfile references.\n */\n private async copyYarnPatches(dir: string): Promise<void> {\n const sourcePatchesDir = path.join(this.rootDir, '.yarn', 'patches');\n if (!fs.existsSync(sourcePatchesDir)) return;\n\n const outputPatchesDir = path.join(dir, '.yarn', 'patches');\n await fsPromises.cp(sourcePatchesDir, outputPatchesDir, { recursive: true, errorOnExist: false });\n }\n\n /**\n * Copies the patch files referenced by the source workspace's `patchedDependencies` in\n * package.json into the output directory and returns the map rewritten to output-relative\n * paths, so bun patches survive the output install.\n */\n private async copyBunPatches(\n declared: Record<string, string>,\n sourceRoot: string,\n dir: string,\n ): Promise<Record<string, string>> {\n const rewritten: Record<string, string> = {};\n const usedFileNames = new Set<string>();\n const resolvedRoot = path.resolve(sourceRoot);\n\n for (const [key, declaredPath] of Object.entries(declared)) {\n const sourcePath = await this.resolvePatchSource(resolvedRoot, declaredPath, {\n key,\n label: 'bun',\n });\n if (!sourcePath) continue;\n\n let fileName = path.basename(sourcePath);\n if (usedFileNames.has(fileName)) {\n fileName = `${key.replace(/[^a-zA-Z0-9._-]/g, '_')}-${fileName}`;\n }\n usedFileNames.add(fileName);\n\n await fsPromises.mkdir(path.join(dir, BUN_PATCHES_DIR), { recursive: true });\n await fsPromises.copyFile(sourcePath, path.join(dir, BUN_PATCHES_DIR, fileName));\n rewritten[key] = `${BUN_PATCHES_DIR}/${fileName}`;\n }\n\n return rewritten;\n }\n\n /**\n * Reads `patchedDependencies` from the source package.json, copies the referenced patch\n * files into the output directory, and writes the output-relative patch map into the\n * output's package.json so `bun install` preserves patches in the bundled output.\n */\n private async copyBunPatchesToOutput(dir: string): Promise<void> {\n const sourcePackageJsonPath = path.join(this.rootDir, 'package.json');\n if (!fs.existsSync(sourcePackageJsonPath)) return;\n\n const sourcePkg = await readJSON(sourcePackageJsonPath);\n const patchedDeps = sourcePkg.patchedDependencies as Record<string, string> | undefined;\n if (!patchedDeps || Object.keys(patchedDeps).length === 0) return;\n\n const rewritten = await this.copyBunPatches(patchedDeps, this.rootDir, dir);\n if (Object.keys(rewritten).length === 0) return;\n\n const outputPackageJsonPath = path.join(dir, 'package.json');\n let outputPkg: Record<string, unknown>;\n try {\n outputPkg = (await readJSON(outputPackageJsonPath)) as Record<string, unknown>;\n } catch {\n outputPkg = {};\n }\n outputPkg.patchedDependencies = rewritten;\n await writeJSON(outputPackageJsonPath, outputPkg, { spaces: 2 });\n }\n\n private getNpmArgs(options: ArchitectureOptions): string[] {\n const args: string[] = [];\n if (options.cpu) args.push(`--cpu=${options.cpu.join(',')}`);\n if (options.os) args.push(`--os=${options.os.join(',')}`);\n if (options.libc) args.push(`--libc=${options.libc.join(',')}`);\n return args;\n }\n\n /**\n * Depending on whether we want to install or add a package, this function returns the appropriate commands.\n * All package managers support both commands (e.g. npm install has an alias on \"add\")\n */\n private getPackageManagerCommand(\n pm: PackageManager,\n type: 'install' | 'add',\n { yarnClassic = false }: { yarnClassic?: boolean } = {},\n ): string {\n const cmd = type === 'install' ? 'install' : 'add';\n\n switch (pm) {\n case 'npm':\n return `${cmd} --audit=false --fund=false --loglevel=error --progress=false --update-notifier=false`;\n case 'yarn':\n return type === 'install' && !yarnClassic ? `${cmd} --no-immutable` : cmd;\n case 'pnpm':\n return type === 'install' ? `${cmd} --no-frozen-lockfile --loglevel=error` : `${cmd} --loglevel=error`;\n default:\n return cmd;\n }\n }\n\n public async install({\n dir = this.rootDir,\n architecture,\n pnpmOverrides,\n pnpmNodeLinker,\n pnpmWorkspaceSettings,\n }: {\n dir?: string;\n architecture?: ArchitectureOptions;\n pnpmOverrides?: Record<string, string>;\n pnpmNodeLinker?: 'hoisted';\n pnpmWorkspaceSettings?: BundlerConfig['pnpmWorkspaceSettings'];\n } = {}) {\n const pm = this.packageManager;\n let yarnClassic = false;\n if (this.lockFile) {\n const destination = path.join(dir, this.lockFile.filename);\n if (path.resolve(this.lockFile.path) !== path.resolve(destination)) {\n const packedBunWorkspaces =\n pm === 'bun' &&\n fs.existsSync(path.join(dir, 'package.json')) &&\n Object.values(\n ((await readJSON(path.join(dir, 'package.json'))) as { resolutions?: Record<string, string> })\n .resolutions ?? {},\n ).some(spec => spec.startsWith('file:./workspace-module/'));\n\n if (packedBunWorkspaces) {\n // Bun cannot reuse the source workspace lockfile with packed tarballs; removing its workspace entries\n // makes Bun ignore it and regenerate the lockfile anyway. Start with a clean lockfile instead.\n await fsPromises.rm(destination, { force: true });\n } else {\n await fsPromises.copyFile(this.lockFile.path, destination);\n if (pm === 'pnpm' && pnpmOverrides && Object.keys(pnpmOverrides).length > 0) {\n await dropPnpmImporterDependencies(destination, Object.keys(pnpmOverrides));\n }\n }\n }\n\n if (pm === 'yarn') {\n yarnClassic = await isYarnClassicLockfile(destination);\n }\n }\n\n const installCommand = this.getPackageManagerCommand(pm, 'install', { yarnClassic });\n let args: string[] = [];\n\n switch (pm) {\n case 'pnpm':\n await this.writePnpmConfig(dir, { ...architecture, pnpmOverrides, pnpmNodeLinker, pnpmWorkspaceSettings });\n break;\n case 'yarn':\n // similar to --ignore-workspace but for yarn\n await ensureFile(path.join(dir, 'yarn.lock'));\n if (architecture) {\n await this.writeYarnConfig(dir, architecture);\n }\n await this.copyYarnPatches(dir);\n break;\n case 'bun':\n await this.copyBunPatchesToOutput(dir);\n break;\n case 'npm':\n if (architecture) {\n args = this.getNpmArgs(architecture);\n }\n break;\n default:\n // Do nothing\n }\n\n const cpLogger = createChildProcessLogger({\n logger: this.logger,\n root: dir,\n });\n\n try {\n return await cpLogger({\n cmd: `${pm} ${installCommand}`,\n args,\n env: process.env as Record<string, string>,\n });\n } catch (error) {\n if (pm !== 'pnpm') throw error;\n\n const processOutput =\n error && typeof error === 'object'\n ? `${'stdout' in error ? String(error.stdout) : ''}\\n${'stderr' in error ? String(error.stderr) : ''}`\n : '';\n const ignoredPackages = getPnpmIgnoredBuildPackages(processOutput);\n if (ignoredPackages.length === 0) throw error;\n\n throw new MastraError(\n {\n id: 'DEPLOYER_PNPM_IGNORED_BUILDS',\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.USER,\n details: { packageNames: ignoredPackages.join(', ') },\n text: `pnpm blocked build scripts for: ${ignoredPackages.join(', ')}. Add these packages to allowBuilds in pnpm-workspace.yaml and retry the build.`,\n },\n error,\n );\n }\n }\n\n public async installPackages(packages: string[]) {\n const pm = this.packageManager;\n const installCommand = this.getPackageManagerCommand(pm, 'add');\n\n const env: Record<string, string> = {\n PATH: process.env.PATH!,\n };\n\n if (process.env.npm_config_registry) {\n env.npm_config_registry = process.env.npm_config_registry;\n }\n\n const cpLogger = createChildProcessLogger({\n logger: this.logger,\n root: '',\n });\n\n return cpLogger({\n cmd: `${pm} ${installCommand}`,\n args: packages,\n env,\n });\n }\n\n public async checkDependencies(dependencies: string[]): Promise<string> {\n try {\n const packageJsonPath = path.join(this.rootDir, 'package.json');\n\n try {\n await fsPromises.access(packageJsonPath);\n } catch {\n return 'No package.json file found in the current directory';\n }\n\n const packageJson = await readJSON(packageJsonPath);\n for (const dependency of dependencies) {\n if (!packageJson.dependencies || !packageJson.dependencies[dependency]) {\n return `Please install ${dependency} before running this command (${this.packageManager} install ${dependency})`;\n }\n }\n\n return 'ok';\n } catch (err) {\n console.error(err);\n return 'Could not check dependencies';\n }\n }\n\n public async getProjectName() {\n const packageJsonPath = path.join(this.rootDir, 'package.json');\n const pkg = await readJSON(packageJsonPath);\n return pkg.name;\n }\n\n public async getPackageVersion() {\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = dirname(__filename);\n const pkgJsonPath = path.join(__dirname, '..', '..', 'package.json');\n\n const content = (await readJSON(pkgJsonPath)) as PackageJson;\n return content.version;\n }\n\n public async addScriptsToPackageJson(scripts: Record<string, string>) {\n const packageJson = await readJSON('package.json');\n packageJson.scripts = {\n ...packageJson.scripts,\n ...scripts,\n };\n await writeJSON('package.json', packageJson, { spaces: 2 });\n }\n}\n\nexport class DepsService extends Deps {}\n","import * as fs from 'node:fs';\n\nexport abstract class EnvService {\n abstract getEnvValue(key: string): Promise<string | null>;\n abstract setEnvValue(key: string, value: string): Promise<void>;\n}\n\nexport class FileEnvService extends EnvService {\n private filePath: string;\n\n constructor(filePath: string) {\n super();\n this.filePath = filePath;\n }\n\n private readFile(filePath: string): Promise<string> {\n return new Promise((resolve, reject) => {\n fs.readFile(filePath, 'utf8', (err: NodeJS.ErrnoException | null, data: string) => {\n if (err) reject(err);\n else resolve(data);\n });\n });\n }\n\n private writeFile({ filePath, data }: { filePath: string; data: string }): Promise<void> {\n return new Promise((resolve, reject) => {\n fs.writeFile(filePath, data, 'utf8', (err: NodeJS.ErrnoException | null) => {\n if (err) reject(err);\n else resolve();\n });\n });\n }\n\n private async updateEnvData({\n key,\n value,\n filePath = this.filePath,\n data,\n }: {\n key: string;\n value: string;\n filePath?: string;\n data: string;\n }): Promise<string> {\n const regex = new RegExp(`^${key}=.*$`, 'm');\n if (data.match(regex)) {\n // Use a replacement function so `$` sequences in the value (e.g. `$&`,\n // `$$`) are written literally instead of being interpreted as\n // String.prototype.replace special patterns.\n data = data.replace(regex, () => `${key}=${value}`);\n } else {\n data += `\\n${key}=${value}`;\n }\n await this.writeFile({ filePath, data });\n console.info(`${key} set to ${value} in ENV file.`);\n return data;\n }\n\n async getEnvValue(key: string): Promise<string | null> {\n try {\n const data = await this.readFile(this.filePath);\n const regex = new RegExp(`^${key}=(.*)$`, 'm');\n const match = data.match(regex);\n return match?.[1] || null;\n } catch (err) {\n console.error(`Error reading ENV value: ${err}`);\n return null;\n }\n }\n\n async setEnvValue(key: string, value: string): Promise<void> {\n try {\n const data = await this.readFile(this.filePath);\n await this.updateEnvData({ key, value, data });\n } catch (err) {\n console.error(`Error writing ENV value: ${err}`);\n }\n }\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport fsExtra from 'fs-extra/esm';\n\nimport { FileEnvService } from './env.js';\n\nexport class FileService {\n /**\n *\n * @param inputFile the file in the starter files directory to copy\n * @param outputFilePath the destination path\n * @param replaceIfExists flag to replace if it exists\n * @returns\n */\n public async copyStarterFile(inputFile: string, outputFilePath: string, replaceIfExists?: boolean) {\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = path.dirname(__filename);\n const filePath = path.resolve(__dirname, '..', 'starter-files', inputFile);\n const fileString = fs.readFileSync(filePath, 'utf8');\n\n if (fs.existsSync(outputFilePath) && !replaceIfExists) {\n console.info(`${outputFilePath} already exists`);\n return false;\n }\n\n await fsExtra.outputFile(outputFilePath, fileString);\n\n return true;\n }\n\n public async setupEnvFile({ dbUrl }: { dbUrl: string }) {\n const envPath = path.join(process.cwd(), '.env.development');\n\n await fsExtra.ensureFile(envPath);\n\n const fileEnvService = new FileEnvService(envPath);\n await fileEnvService.setEnvValue('DB_URL', dbUrl);\n }\n\n public getFirstExistingFile(files: string[]): string {\n for (const f of files) {\n if (fs.existsSync(f)) {\n return f;\n }\n }\n\n throw new Error('Missing required file, checked the following paths: ' + files.join(', '));\n }\n\n /**\n * Returns every existing file from the provided array in the same order.\n * Callers supply files from the lowest to highest precedence so later dotenv\n * files override earlier values when the bundler loads them.\n */\n public getExistingFiles(files: string[]): string[] {\n return files.filter(file => fs.existsSync(file));\n }\n\n /**\n * Returns the first existing file from the provided array, or undefined if none exist\n * @param files array of file paths to check\n * @returns the first existing file path or undefined\n */\n public getFirstExistingFileOrUndefined(files: string[]): string | undefined {\n for (const f of files) {\n if (fs.existsSync(f)) {\n return f;\n }\n }\n\n return undefined;\n }\n\n public replaceValuesInFile({\n filePath,\n replacements,\n }: {\n filePath: string;\n replacements: { search: string; replace: string }[];\n }) {\n let fileContent = fs.readFileSync(filePath, 'utf8');\n replacements.forEach(({ search, replace }) => {\n fileContent = fileContent.replaceAll(search, replace);\n });\n\n fs.writeFileSync(filePath, fileContent);\n }\n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pha.3",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "files": [
@@ -111,7 +111,7 @@
111
111
  "tinyglobby": "^0.2.17",
112
112
  "ws": "^8.22.0",
113
113
  "yaml": "^2.9.1",
114
- "@mastra/server": "1.82.0-alpha.1"
114
+ "@mastra/server": "1.82.0-alpha.3"
115
115
  },
116
116
  "devDependencies": {
117
117
  "@hono/node-server": "^2.1.3",
@@ -119,8 +119,8 @@
119
119
  "@hono/swagger-ui": "^0.5.3",
120
120
  "@types/fs-extra": "^11.0.4",
121
121
  "@types/node": "22.19.15",
122
- "@vitest/coverage-v8": "4.1.12",
123
- "@vitest/ui": "4.1.12",
122
+ "@vitest/coverage-v8": "5.1.0",
123
+ "@vitest/ui": "5.1.0",
124
124
  "fetch-to-node": "^2.1.0",
125
125
  "hono-openapi": "^1.5.0",
126
126
  "stacktrace-parser": "^0.1.11",
@@ -128,7 +128,7 @@
128
128
  "tsx": "^4.23.15",
129
129
  "type-fest": "^5.10.0",
130
130
  "typescript": "^6.0.3",
131
- "vitest": "4.1.12",
131
+ "vitest": "5.1.0",
132
132
  "zod": "^4.6.7",
133
133
  "@internal/core": "0.1.4",
134
134
  "@internal/deployer": "0.0.0",
@@ -136,10 +136,10 @@
136
136
  "@internal/lint": "0.0.147",
137
137
  "@internal/types-builder": "0.0.122",
138
138
  "@mastra/agent-browser": "0.6.0",
139
- "@mastra/core": "1.82.0-alpha.1",
140
- "@mastra/hono": "1.7.24-alpha.1",
141
- "@mastra/mcp": "^2.8.0-alpha.0",
142
- "@mastra/server": "1.82.0-alpha.1"
139
+ "@mastra/core": "1.82.0-alpha.3",
140
+ "@mastra/hono": "1.7.24-alpha.3",
141
+ "@mastra/mcp": "^2.8.0-alpha.2",
142
+ "@mastra/server": "1.82.0-alpha.3"
143
143
  },
144
144
  "peerDependencies": {
145
145
  "@mastra/core": ">=1.81.0-0 <2.0.0-0"
@@ -1 +0,0 @@
1
- {"version":3,"file":"build-D8q_n1TB.cjs","names":["resolve","normalizeExternals","bundleExternals","slash","getPackageName","glob","existsSync","stat","pkg","dirname","slash","getWorkspaceInformation","posix","analyzeBundle","noopLogger","getPackageName","getBundlerInputOptions","tsConfigPaths","aliasHono","nodeModulesExtensionResolver","watch","readFile","transformAsync","checkConfigExport","extractMastraOption","parse","lstat","slash","join","readdir","path","readFile","readFile","slash","join","posix","mkdir","dirname","writeFile","lstat","join","mkdir","cp"],"sources":["../src/build/plugins/workspace-deps-watcher.ts","../src/build/watcher.ts","../src/build/analyzeEntryProjectType.ts","../src/build/serverOptions.ts","../../_internal-core/dist/frontmatter/index.js","../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 { normalizeExternals } from '../analyze/externals';\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 const { externalsPreset, mergedExternals } = normalizeExternals(bundlerOptions?.externals ?? true);\n\n await bundleExternals(depsCopy, outputDir, {\n bundlerOptions: {\n externalsPreset,\n mergedExternals,\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 '@internal/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 // `mastra dev` never minifies — readable output matters more than size here.\n enableMinify: 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 env,\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 '@internal/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 { parse, stringify } from \"yaml\";\n// src/frontmatter/index.ts\nconst OPEN = \"---\";\nconst CLOSE = \"\\n---\";\n/**\n* Split a markdown document into YAML frontmatter and body.\n*\n* A frontmatter block starts with `---` on the first line and ends at the next\n* line that is exactly `---` (a longer dash run or `--- !tag` is not a delimiter). An optional language tag may follow the opening\n* delimiter (`---yaml`); only YAML and JSON are accepted, and a `js`/`javascript`\n* tag throws instead of being evaluated. Documents that do not start with `---`\n* are returned unchanged with empty data.\n*\n* Throws when the frontmatter is not valid YAML or is not a mapping.\n*/\nfunction parseFrontmatter(input) {\n\tconst str = input.charCodeAt(0) === 65279 ? input.slice(1) : input;\n\tif (!str.startsWith(OPEN) || str.charAt(3) === \"-\") return {\n\t\tdata: {},\n\t\tcontent: str\n\t};\n\tlet rest = str.slice(3);\n\tconst firstLineEnd = rest.indexOf(\"\\n\");\n\tconst language = (firstLineEnd === -1 ? rest : rest.slice(0, firstLineEnd)).trim().toLowerCase();\n\tif (language) rest = firstLineEnd === -1 ? \"\" : rest.slice(firstLineEnd);\n\tlet closeIndex = rest.indexOf(CLOSE);\n\tlet closeEnd = -1;\n\twhile (closeIndex !== -1) {\n\t\tcloseEnd = closeIndex + 4;\n\t\twhile (rest[closeEnd] === \" \" || rest[closeEnd] === \"\t\") closeEnd++;\n\t\tconst after = rest.charAt(closeEnd);\n\t\tif (after === \"\" || after === \"\\n\" || after === \"\\r\") break;\n\t\tcloseIndex = rest.indexOf(CLOSE, closeIndex + 1);\n\t}\n\tconst block = (closeIndex === -1 ? rest : rest.slice(0, closeIndex)).replace(/\\r(?=\\n|$)/g, \"\");\n\tlet content = closeIndex === -1 ? \"\" : rest.slice(closeEnd);\n\tif (content.startsWith(\"\\r\")) content = content.slice(1);\n\tif (content.startsWith(\"\\n\")) content = content.slice(1);\n\treturn {\n\t\tdata: parseBlock(block, language),\n\t\tcontent\n\t};\n}\nfunction parseBlock(block, language) {\n\tif (block.replace(/^\\s*#[^\\n]*/gm, \"\").trim() === \"\") return {};\n\tlet data;\n\tswitch (language) {\n\t\tcase \"\":\n\t\tcase \"yaml\":\n\t\tcase \"yml\":\n\t\t\tdata = parse(block);\n\t\t\tbreak;\n\t\tcase \"json\":\n\t\t\tdata = JSON.parse(block);\n\t\t\tbreak;\n\t\tcase \"js\":\n\t\tcase \"javascript\": throw new Error(\"JavaScript frontmatter is not supported\");\n\t\tdefault: throw new Error(`Frontmatter language \"${language}\" is not supported`);\n\t}\n\tif (data === null || data === void 0) return {};\n\tif (typeof data !== \"object\" || Array.isArray(data)) throw new Error(\"Frontmatter must be a mapping of fields\");\n\treturn data;\n}\n/**\n* Serialize `data` as a YAML frontmatter block followed by `content`.\n* The block is omitted when `data` has no fields. The result always ends with a newline.\n*/\nfunction stringifyFrontmatter(content, data) {\n\tconst body = content.endsWith(\"\\n\") ? content : `${content}\\n`;\n\tif (Object.keys(data).length === 0) return body;\n\tconst block = stringify(data, { lineWidth: 0 }).trimEnd();\n\treturn `${OPEN}\\n${block}\\n${OPEN}\\n${body}`;\n}\nexport { parseFrontmatter, stringifyFrontmatter };\n\n//# sourceMappingURL=index.js.map","import { lstat, readdir, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { parseFrontmatter } from '@internal/core/frontmatter';\nimport { MAX_FS_SUBAGENT_DEPTH } from '@internal/core/fs-routing';\nimport type { AgentSchedulePromptDefinition } from '@mastra/core/schedules';\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 /**\n * Absolute path to `instructions.ts`/`instructions.js`, if present. Unlike\n * `instructions.md` (whose contents are inlined at build time), this module is\n * imported by the generated wrapper, so it can compute its prompt or export a\n * runtime-resolved function.\n */\n instructionsModulePath?: 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 INSTRUCTIONS_MODULE_BASENAMES = ['instructions.ts', 'instructions.js'];\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`/\n * `instructions.ts`/`workspace.ts`/`memory.ts` is never inlined or imported\n * 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 = parseFrontmatter(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 parseFrontmatter>;\n try {\n parsed = parseFrontmatter(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;\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)`, no\n * `instructions.md`, and no `instructions.(ts|js)`).\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 const instructionsModulePath = await firstExisting(dir, INSTRUCTIONS_MODULE_BASENAMES);\n\n // Not an agent directory unless it has a config or instructions file.\n if (!configPath && !instructionsPath && !instructionsModulePath) {\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 instructionsModulePath,\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)`, an\n * `instructions.md`, or an `instructions.(ts|js)`; other directories are\n * ignored. Each agent may declare `subagents/` up to `MAX_FS_SUBAGENT_DEPTH`\n * levels deep. Returns descriptors with absolute, slash-normalized paths ready\n * for codegen. Performs no module 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 // `instructions.ts` is imported rather than inlined, so it can compute its\n // prompt or export a runtime-resolved function. That also puts it in the\n // bundler's module graph, which is what makes dev hot reload work without the\n // watcher tracking it explicitly (unlike `instructions.md`).\n let instructionsIdent: string | undefined;\n if (agent.instructionsModulePath) {\n instructionsIdent = sanitizeIdentifier(`${agent.name}_instructions`, 'instructions', idPath);\n lines.push(`import ${instructionsIdent} from ${JSON.stringify(agent.instructionsModulePath)};`);\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 (instructionsIdent) {\n entryFields.push(`instructions: ${instructionsIdent}`);\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`, `instructions.ts`, `tools/*.ts`,\n * `skills/*.ts` (`createSkill(...)` modules), `workspace.ts`, and\n * `memory.ts`, inlining 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. `instructions.ts` is\n * imported instead, so the bundler already tracks it through the module graph.\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":";;;;;;;;;;;;;;;;AAYA,MAAM,eAAe,CAAC,mCAAmC;A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