@mastra/deployer-cloud 0.14.2-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/auth.ts","../src/utils/constants.ts","../src/utils/logger.ts","../src/utils/execa.ts","../src/utils/deps.ts","../src/utils/file.ts","../src/utils/report.ts","../src/index.ts"],"names":["os","createClient","LoggerTransport","resolve","PinoLogger","Transform","execa","fs","join","error","MastraError","FileService","Deployer","dirname","fileURLToPath","copy"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAO,SAAS,iBAAA,GAAoB;AAClC,EAAA,OAAO;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA,6EAAA,EAUsE,OAAA,CAAQ,IAAI,kBAAkB,CAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAAA,CAAA;AAuB7G;AChCO,IAAM,KAAA,GAAQ,OAAA,CAAQ,GAAA,CAAI,KAAA,KAAU,MAAA;AACpC,IAAM,OAAA,GAAkB,OAAA,CAAQ,GAAA,CAAI,OAAA,IAAW,EAAA;AAC/C,IAAM,UAAA,GAAqB,OAAA,CAAQ,GAAA,CAAI,UAAA,IAAc,EAAA;AACrD,IAAM,QAAA,GAAmB,OAAA,CAAQ,GAAA,CAAI,QAAA,IAAY,EAAA;AACjD,IAAM,SAAA,GAAoB,OAAA,CAAQ,GAAA,CAAI,SAAA,IAAa,EAAA;AACnD,IAAM,aAAA,GAAwB,OAAA,CAAQ,GAAA,CAAI,aAAA,IAAiB,wBAAA;AAE3D,IAAM,eAAA,GAA0B,OAAA,CAAQ,GAAA,CAAI,eAAA,IAAmB,EAAA;AAC/D,IAAM,gBAAA,GAA2B,OAAA,CAAQ,GAAA,CAAI,gBAA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mastra/core/server';\n\n class MastraCloudAuth extends MastraAuthProvider {\n constructor (auth) {\n super()\n this.auth = auth\n }\n\n async authenticateToken (...args) {\n if (typeof args[0] === 'string' && args[0].replace('Bearer ', '') === '${process.env.BUSINESS_JWT_TOKEN}') {\n return { id: 'business-api' }\n }\n return this.auth.authenticateToken(...args)\n }\n\n async authorizeUser (...args) {\n if (args[1] && args[1].path === '/api') {\n return true\n }\n if (args[0] && args[0].id === 'business-api') {\n return true\n }\n return this.auth.authorizeUser(...args)\n }\n }\n\n const serverConfig = mastra.getServer()\n if (serverConfig && serverConfig.experimental_auth) {\n const auth = serverConfig.experimental_auth\n serverConfig.experimental_auth = new MastraCloudAuth(auth)\n }\n `;\n}\n","import os from 'os';\n\nexport const LOCAL = process.env.LOCAL === 'true';\nexport const TEAM_ID: string = process.env.TEAM_ID ?? '';\nexport const PROJECT_ID: string = process.env.PROJECT_ID ?? '';\nexport const BUILD_ID: string = process.env.BUILD_ID ?? '';\nexport const BUILD_URL: string = process.env.BUILD_URL ?? '';\nexport const LOG_REDIS_URL: string = process.env.LOG_REDIS_URL ?? 'redis://localhost:6379';\nexport const BUSINESS_JWT_TOKEN: string = process.env.BUSINESS_JWT_TOKEN ?? '';\nexport const USER_IP_ADDRESS: string = process.env.USER_IP_ADDRESS ?? '';\nexport const MASTRA_DIRECTORY: string = process.env.MASTRA_DIRECTORY ?? 'src/mastra';\nexport const PROJECT_ENV_VARS: Record<string, string> = safelyParseJson(process.env.PROJECT_ENV_VARS ?? '{}');\n\nexport const PROJECT_ROOT = LOCAL ? os.tmpdir() + '/project' : (process.env.PROJECT_ROOT ?? '/project');\n\nexport function safelyParseJson(json: string) {\n try {\n return JSON.parse(json);\n } catch {\n return {};\n }\n}\n","import type { TransformCallback } from 'stream';\nimport type { BaseLogMessage, LogLevel } from '@mastra/core/logger';\nimport { LoggerTransport } from '@mastra/core/logger';\nimport { PinoLogger } from '@mastra/loggers';\nimport { createClient } from 'redis';\nimport { BUILD_ID, LOG_REDIS_URL, PROJECT_ID, TEAM_ID } from './constants.js';\n\nconst redisClient = createClient({\n url: LOG_REDIS_URL,\n});\n\nclass RedisTransport extends LoggerTransport {\n _transform(chunk: any, _encoding: string, callback: TransformCallback): void {\n chunk = chunk.toString();\n const logKey = `builder:logs:${TEAM_ID}:${PROJECT_ID}:${BUILD_ID}`;\n const ttl = 2 * 24 * 60 * 60; // 2 days in seconds\n const logData = typeof chunk === 'string' ? chunk : JSON.stringify(chunk);\n\n // Don't block the event loop - process logs asynchronously\n process.nextTick(async () => {\n try {\n // Connect to Redis if not already connected\n if (!redisClient.isOpen) {\n await redisClient.connect().catch(err => {\n console.error('Redis connection error:', err);\n });\n }\n\n // Use pipeline to batch Redis operations\n const pipeline = redisClient.multi();\n pipeline.rPush(logKey, logData);\n pipeline.expire(logKey, ttl);\n await pipeline.exec();\n } catch (err) {\n console.error('Redis logging error:', err);\n }\n });\n\n // Immediately pass through the chunk without waiting\n callback(null, chunk);\n }\n\n _write(chunk: any, encoding?: string, callback?: (error?: Error | null) => void): boolean {\n if (typeof callback === 'function') {\n this._transform(chunk, encoding || 'utf8', callback);\n return true;\n }\n\n this._transform(chunk, encoding || 'utf8', (error: Error | null | undefined) => {\n if (error) console.error('Transform error in write:', error);\n });\n return true;\n }\n\n async _flush(): Promise<void> {\n // // Ensure the pipeline is closed and flushed\n // redisClient.quit().catch(err => {\n // console.error('Redis connection error:', err);\n // });\n // callback();\n await new Promise(resolve => setTimeout(resolve, 10));\n }\n\n async _destroy(err: Error, cb: Function) {\n await closeLogger();\n cb(err);\n }\n\n getLogs(_args: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean;\n page?: number;\n perPage?: number;\n }): Promise<{ logs: BaseLogMessage[]; total: number; page: number; perPage: number; hasMore: boolean }> {\n return Promise.resolve({\n logs: [],\n total: 0,\n page: _args?.page ?? 1,\n perPage: _args?.perPage ?? 100,\n hasMore: false,\n });\n }\n\n getLogsByRunId(_args?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean;\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n return Promise.resolve({\n logs: [],\n total: 0,\n page: _args?.page ?? 1,\n perPage: _args?.perPage ?? 100,\n hasMore: false,\n });\n }\n}\n\nexport const transport = new RedisTransport();\n\nexport const closeLogger = async () => {\n if (redisClient.isOpen) {\n setTimeout(async () => {\n await redisClient.quit();\n }, 10);\n }\n};\n\nexport const logger = new PinoLogger({\n level: 'info',\n transports: {\n redis: transport,\n },\n});\n","import { Transform } from 'stream';\nimport { execa } from 'execa';\nimport { PROJECT_ENV_VARS, PROJECT_ROOT } from './constants.js';\nimport { logger } from './logger.js';\n\nexport const createPinoStream = () => {\n return new Transform({\n transform(chunk, encoding, callback) {\n // Convert Buffer/string to string and trim whitespace\n const line = chunk.toString().trim();\n\n if (line) {\n // Log each line through Pino\n logger.info(line);\n }\n\n // Pass through the original data\n callback(null, chunk);\n },\n });\n};\n\nexport async function runWithExeca({\n cmd,\n args,\n cwd = process.cwd(),\n env = PROJECT_ENV_VARS,\n}: {\n cmd: string;\n args: string[];\n cwd?: string;\n env?: Record<string, string>;\n}): Promise<{ stdout?: string; stderr?: string; success: boolean; error?: Error }> {\n const pinoStream = createPinoStream();\n\n try {\n const subprocess = execa(cmd, args, {\n cwd,\n env: {\n ...process.env,\n ...env,\n },\n });\n\n // Pipe stdout and stderr through the Pino stream\n subprocess.stdout?.pipe(pinoStream);\n subprocess.stderr?.pipe(pinoStream);\n\n const { stdout, stderr, exitCode } = await subprocess;\n return { stdout, stderr, success: exitCode === 0 };\n } catch (error) {\n logger.error(`Process failed: ${error}`);\n return { success: false, error: error instanceof Error ? error : new Error(String(error)) };\n }\n}\n\nexport function runWithChildProcess(cmd: string, args: string[]): { stdout?: string; stderr?: string } {\n const pinoStream = createPinoStream();\n\n try {\n const { stdout, stderr } = require('child_process').spawnSync(cmd, args, {\n cwd: PROJECT_ROOT,\n encoding: 'utf8',\n shell: true,\n env: {\n ...process.env,\n ...PROJECT_ENV_VARS,\n },\n maxBuffer: 1024 * 1024 * 10, // 10MB buffer\n });\n\n if (stdout) {\n pinoStream.write(stdout);\n }\n if (stderr) {\n pinoStream.write(stderr);\n }\n\n pinoStream.end();\n return { stdout, stderr };\n } catch (error) {\n logger.error('Process failed' + error);\n pinoStream.end();\n return {};\n }\n}\n","import * as fs from 'fs';\nimport { join, resolve } from 'path';\n\nimport { MastraError } from '@mastra/core/error';\nimport { runWithExeca } from './execa.js';\nimport { logger } from './logger.js';\n\nconst MEMOIZED = new Map();\n\nfunction findLockFile(dir: string): string | null {\n const lockFiles = ['pnpm-lock.yaml', 'package-lock.json', 'yarn.lock', 'bun.lock'];\n for (const file of lockFiles) {\n if (fs.existsSync(join(dir, file))) {\n return file;\n }\n }\n const parentDir = resolve(dir, '..');\n if (parentDir !== dir) {\n return findLockFile(parentDir);\n }\n return null;\n}\n\nexport function detectPm({ path }: { path: string }): string {\n const cached = MEMOIZED.get(path);\n if (cached) {\n return cached;\n }\n\n const lockFile = findLockFile(path);\n let pm: string = 'npm';\n switch (lockFile) {\n case 'pnpm-lock.yaml':\n pm = 'pnpm';\n break;\n case 'package-lock.json':\n pm = 'npm';\n break;\n case 'yarn.lock':\n pm = 'yarn';\n break;\n case 'bun.lock':\n pm = 'bun';\n break;\n default:\n pm = 'npm';\n }\n\n MEMOIZED.set(path, pm);\n return pm;\n}\n\nexport async function installNodeVersion({ path }: { path: string }) {\n let nvmrcExists = false;\n let nodeVersionExists = false;\n\n try {\n fs.accessSync(join(path, '.nvmrc'));\n nvmrcExists = true;\n } catch {\n // File does not exist\n }\n\n try {\n fs.accessSync(join(path, '.node-version'));\n nodeVersionExists = true;\n } catch {\n // File does not exist\n }\n\n if (nvmrcExists || nodeVersionExists) {\n logger.info('Node version file found, installing specified Node.js version...');\n const { success, error } = await runWithExeca({\n cmd: 'n',\n args: ['auto'],\n cwd: path,\n });\n if (!success) {\n throw new MastraError(\n {\n id: 'NODE_FAIL_INSTALL_SPECIFIED_VERSION',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n }\n}\n\nexport async function installDeps({ path, pm }: { path: string; pm?: string }) {\n pm = pm ?? detectPm({ path });\n logger.info(`Installing dependencies with ${pm} in ${path}`);\n const args = ['install'];\n const { success, error } = await runWithExeca({ cmd: pm, args, cwd: path });\n if (!success) {\n throw new MastraError(\n {\n id: 'FAIL_INSTALL_DEPS',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n}\n\nexport async function runInstallCommand({ path, installCommand }: { path: string; installCommand: string }) {\n logger.info(`Running install command ${installCommand} in workspace with ${path}`);\n const { success, error } = await runWithExeca({ cmd: 'sh', args: ['-c', installCommand], cwd: path });\n if (!success) {\n throw new MastraError(\n {\n id: 'FAIL_CUSTOM_INSTALL_COMMAND',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n}\n\nexport async function runScript({ scriptName, path, args }: { scriptName: string; path: string; args?: string[] }) {\n const pm = detectPm({ path });\n logger.info(`Running script ${scriptName} in workspace with ${pm}`);\n const { success, error } = await runWithExeca({\n cmd: pm,\n args: pm === 'npm' ? ['run', scriptName, ...(args ?? [])] : [scriptName, ...(args ?? [])],\n cwd: path,\n });\n if (!success) {\n throw new MastraError(\n {\n id: 'FAIL_BUILD_SCRIPT',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n}\n\nexport async function runBuildCommand({ command, path }: { command: string; path: string }) {\n logger.info(`Running build command ${command}`);\n const { success, error } = await runWithExeca({ cmd: 'sh', args: ['-c', command], cwd: path });\n if (!success) {\n throw new MastraError(\n {\n id: 'FAIL_BUILD_COMMAND',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n}\n","import { join } from 'path';\nimport { MastraError } from '@mastra/core/error';\nimport { FileService } from '@mastra/deployer';\n\nimport { MASTRA_DIRECTORY } from './constants.js';\n\nexport function getMastraEntryFile(mastraDir: string) {\n try {\n const fileService = new FileService();\n return fileService.getFirstExistingFile([\n join(mastraDir, MASTRA_DIRECTORY, 'index.ts'),\n join(mastraDir, MASTRA_DIRECTORY, 'index.js'),\n ]);\n } catch (error) {\n throw new MastraError(\n {\n id: 'MASTRA_ENTRY_FILE_NOT_FOUND',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n}\n","import { PROJECT_ID, BUILD_ID, BUILD_URL, USER_IP_ADDRESS } from './constants.js';\n\nexport function successEntrypoint() {\n return `\n if (process.env.CI !== 'true' && process.env.REPORTER_API_URL && process.env.REPORTER_API_URL_AUTH_TOKEN) {\n await fetch(process.env.REPORTER_API_URL, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: \\`Bearer \\$\\{process.env.REPORTER_API_URL_AUTH_TOKEN\\}\\`,\n },\n body: JSON.stringify(${JSON.stringify({\n projectId: PROJECT_ID,\n buildId: BUILD_ID,\n status: 'success',\n url: BUILD_URL,\n userIpAddress: USER_IP_ADDRESS,\n })}),\n }).catch(err => {\n console.error('Failed to report build status to monitoring service', {\n error: err,\n });\n })\n }\n `;\n}\n","import { fileURLToPath } from 'node:url';\nimport { join, dirname } from 'path';\nimport { Deployer } from '@mastra/deployer';\nimport { copy } from 'fs-extra';\n\nimport { getAuthEntrypoint } from './utils/auth.js';\nimport { MASTRA_DIRECTORY, BUILD_ID, PROJECT_ID, TEAM_ID } from './utils/constants.js';\nimport { installDeps } from './utils/deps.js';\nimport { getMastraEntryFile } from './utils/file.js';\nimport { successEntrypoint } from './utils/report.js';\n\nexport class CloudDeployer extends Deployer {\n constructor() {\n super({ name: 'cloud' });\n }\n\n async deploy(_outputDirectory: string): Promise<void> {}\n async writeInstrumentationFile(outputDirectory: string) {\n const instrumentationFile = join(outputDirectory, 'instrumentation.mjs');\n const __dirname = dirname(fileURLToPath(import.meta.url));\n\n await copy(join(__dirname, '../templates', 'instrumentation-template.js'), instrumentationFile);\n }\n writePackageJson(outputDirectory: string, dependencies: Map<string, string>) {\n dependencies.set('@mastra/loggers', '0.10.6');\n dependencies.set('@mastra/libsql', '0.13.1');\n dependencies.set('@mastra/cloud', '0.1.7');\n return super.writePackageJson(outputDirectory, dependencies);\n }\n\n async lint() {}\n\n protected async installDependencies(outputDirectory: string, _rootDir = process.cwd()) {\n await installDeps({ path: join(outputDirectory, 'output'), pm: 'npm' });\n }\n\n async bundle(mastraDir: string, outputDirectory: string): Promise<void> {\n const currentCwd = process.cwd();\n process.chdir(mastraDir);\n\n const mastraEntryFile = getMastraEntryFile(mastraDir);\n\n const defaultToolsPath = join(mastraDir, MASTRA_DIRECTORY, 'tools');\n\n await this._bundle(this.getEntry(), mastraEntryFile, outputDirectory, [defaultToolsPath]);\n process.chdir(currentCwd);\n }\n\n getAuthEntrypoint() {\n return getAuthEntrypoint();\n }\n\n private getEntry(): string {\n return `\nimport { createNodeServer, getToolExports } from '#server';\nimport { tools } from '#tools';\nimport { mastra } from '#mastra';\nimport { MultiLogger } from '@mastra/core/logger';\nimport { PinoLogger } from '@mastra/loggers';\nimport { UpstashTransport } from '@mastra/loggers/upstash';\nimport { HttpTransport } from '@mastra/loggers/http';\nimport { evaluate } from '@mastra/core/eval';\nimport { AvailableHooks, registerHook } from '@mastra/core/hooks';\nimport { LibSQLStore, LibSQLVector } from '@mastra/libsql';\n\nconst startTime = process.env.RUNNER_START_TIME ? new Date(process.env.RUNNER_START_TIME).getTime() : Date.now();\nconst createNodeServerStartTime = Date.now();\n\nconsole.log(JSON.stringify({\n message: \"Server starting\",\n operation: 'builder.createNodeServer',\n operation_startTime: createNodeServerStartTime,\n type: \"READINESS\",\n startTime,\n metadata: {\n teamId: \"${TEAM_ID}\",\n projectId: \"${PROJECT_ID}\",\n buildId: \"${BUILD_ID}\",\n },\n}));\n\nconst transports = {}\nif (process.env.CI !== 'true') {\n if (process.env.BUSINESS_API_RUNNER_LOGS_ENDPOINT) {\n transports.default = new HttpTransport({\n url: process.env.BUSINESS_API_RUNNER_LOGS_ENDPOINT,\n headers: {\n Authorization: 'Bearer ' + process.env.BUSINESS_JWT_TOKEN,\n },\n });\n }\n}\n\nconst logger = new PinoLogger({\n name: 'MastraCloud',\n transports,\n level: 'debug',\n});\nconst existingLogger = mastra?.getLogger();\nconst combinedLogger = existingLogger ? new MultiLogger([logger, existingLogger]) : logger;\n\nmastra.setLogger({ logger: combinedLogger });\n\nif (mastra?.storage) {\n mastra.storage.init()\n}\n\nif (process.env.MASTRA_STORAGE_URL && process.env.MASTRA_STORAGE_AUTH_TOKEN) {\n const { MastraStorage } = await import('@mastra/core/storage');\n logger.info('Using Mastra Cloud Storage: ' + process.env.MASTRA_STORAGE_URL)\n const storage = new LibSQLStore({\n url: process.env.MASTRA_STORAGE_URL,\n authToken: process.env.MASTRA_STORAGE_AUTH_TOKEN,\n })\n const vector = new LibSQLVector({\n connectionUrl: process.env.MASTRA_STORAGE_URL,\n authToken: process.env.MASTRA_STORAGE_AUTH_TOKEN,\n })\n\n await storage.init()\n mastra?.setStorage(storage)\n\n mastra?.memory?.setStorage(storage)\n mastra?.memory?.setVector(vector)\n\n registerHook(AvailableHooks.ON_GENERATION, ({ input, output, metric, runId, agentName, instructions }) => {\n evaluate({\n agentName,\n input,\n metric,\n output,\n runId,\n globalRunId: runId,\n instructions,\n });\n });\n registerHook(AvailableHooks.ON_EVALUATION, async traceObject => {\n if (mastra?.storage) {\n await mastra.storage.insert({\n tableName: MastraStorage.TABLE_EVALS,\n record: {\n input: traceObject.input,\n output: traceObject.output,\n result: JSON.stringify(traceObject.result),\n agent_name: traceObject.agentName,\n metric_name: traceObject.metricName,\n instructions: traceObject.instructions,\n test_info: null,\n global_run_id: traceObject.globalRunId,\n run_id: traceObject.runId,\n created_at: new Date().toISOString(),\n },\n });\n }\n });\n}\n\n${getAuthEntrypoint()}\n\nawait createNodeServer(mastra, { playground: false, swaggerUI: false, tools: getToolExports(tools) });\n\n${successEntrypoint()}\n\nconsole.log(JSON.stringify({\n message: \"Server started\",\n operation: 'builder.createNodeServer',\n operation_startTime: createNodeServerStartTime,\n operation_durationMs: Date.now() - createNodeServerStartTime,\n type: \"READINESS\",\n startTime,\n metadata: {\n teamId: \"${TEAM_ID}\",\n projectId: \"${PROJECT_ID}\",\n buildId: \"${BUILD_ID}\",\n },\n}));\n\n\nconsole.log(JSON.stringify({\n message: \"Runner Initialized\",\n type: \"READINESS\",\n startTime,\n durationMs: Date.now() - startTime,\n metadata: {\n teamId: \"${TEAM_ID}\",\n projectId: \"${PROJECT_ID}\",\n buildId: \"${BUILD_ID}\",\n },\n}));\n`;\n }\n}\n"]}
@@ -0,0 +1,13 @@
1
+ import { Deployer } from '@mastra/deployer';
2
+ export declare class CloudDeployer extends Deployer {
3
+ constructor();
4
+ deploy(_outputDirectory: string): Promise<void>;
5
+ writeInstrumentationFile(outputDirectory: string): Promise<void>;
6
+ writePackageJson(outputDirectory: string, dependencies: Map<string, string>): Promise<void>;
7
+ lint(): Promise<void>;
8
+ protected installDependencies(outputDirectory: string, _rootDir?: string): Promise<void>;
9
+ bundle(mastraDir: string, outputDirectory: string): Promise<void>;
10
+ getAuthEntrypoint(): string;
11
+ private getEntry;
12
+ }
13
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAS5C,qBAAa,aAAc,SAAQ,QAAQ;;IAKnC,MAAM,CAAC,gBAAgB,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAC/C,wBAAwB,CAAC,eAAe,EAAE,MAAM;IAMtD,gBAAgB,CAAC,eAAe,EAAE,MAAM,EAAE,YAAY,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC;IAOrE,IAAI;cAEM,mBAAmB,CAAC,eAAe,EAAE,MAAM,EAAE,QAAQ,SAAgB;IAI/E,MAAM,CAAC,SAAS,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAYvE,iBAAiB;IAIjB,OAAO,CAAC,QAAQ;CA2IjB"}
package/dist/index.js ADDED
@@ -0,0 +1,462 @@
1
+ import { fileURLToPath } from 'url';
2
+ import { join, dirname, resolve } from 'path';
3
+ import { Deployer, FileService } from '@mastra/deployer';
4
+ import { copy } from 'fs-extra';
5
+ import os from 'os';
6
+ import * as fs from 'fs';
7
+ import { MastraError } from '@mastra/core/error';
8
+ import { Transform } from 'stream';
9
+ import { execa } from 'execa';
10
+ import { LoggerTransport } from '@mastra/core/logger';
11
+ import { PinoLogger } from '@mastra/loggers';
12
+ import { createClient } from 'redis';
13
+
14
+ // src/index.ts
15
+
16
+ // src/utils/auth.ts
17
+ function getAuthEntrypoint() {
18
+ return `
19
+ import { MastraAuthProvider } from '@mastra/core/server';
20
+
21
+ class MastraCloudAuth extends MastraAuthProvider {
22
+ constructor (auth) {
23
+ super()
24
+ this.auth = auth
25
+ }
26
+
27
+ async authenticateToken (...args) {
28
+ if (typeof args[0] === 'string' && args[0].replace('Bearer ', '') === '${process.env.BUSINESS_JWT_TOKEN}') {
29
+ return { id: 'business-api' }
30
+ }
31
+ return this.auth.authenticateToken(...args)
32
+ }
33
+
34
+ async authorizeUser (...args) {
35
+ if (args[1] && args[1].path === '/api') {
36
+ return true
37
+ }
38
+ if (args[0] && args[0].id === 'business-api') {
39
+ return true
40
+ }
41
+ return this.auth.authorizeUser(...args)
42
+ }
43
+ }
44
+
45
+ const serverConfig = mastra.getServer()
46
+ if (serverConfig && serverConfig.experimental_auth) {
47
+ const auth = serverConfig.experimental_auth
48
+ serverConfig.experimental_auth = new MastraCloudAuth(auth)
49
+ }
50
+ `;
51
+ }
52
+ var LOCAL = process.env.LOCAL === "true";
53
+ var TEAM_ID = process.env.TEAM_ID ?? "";
54
+ var PROJECT_ID = process.env.PROJECT_ID ?? "";
55
+ var BUILD_ID = process.env.BUILD_ID ?? "";
56
+ var BUILD_URL = process.env.BUILD_URL ?? "";
57
+ var LOG_REDIS_URL = process.env.LOG_REDIS_URL ?? "redis://localhost:6379";
58
+ var USER_IP_ADDRESS = process.env.USER_IP_ADDRESS ?? "";
59
+ var MASTRA_DIRECTORY = process.env.MASTRA_DIRECTORY ?? "src/mastra";
60
+ var PROJECT_ENV_VARS = safelyParseJson(process.env.PROJECT_ENV_VARS ?? "{}");
61
+ LOCAL ? os.tmpdir() + "/project" : process.env.PROJECT_ROOT ?? "/project";
62
+ function safelyParseJson(json) {
63
+ try {
64
+ return JSON.parse(json);
65
+ } catch {
66
+ return {};
67
+ }
68
+ }
69
+ var redisClient = createClient({
70
+ url: LOG_REDIS_URL
71
+ });
72
+ var RedisTransport = class extends LoggerTransport {
73
+ _transform(chunk, _encoding, callback) {
74
+ chunk = chunk.toString();
75
+ const logKey = `builder:logs:${TEAM_ID}:${PROJECT_ID}:${BUILD_ID}`;
76
+ const ttl = 2 * 24 * 60 * 60;
77
+ const logData = typeof chunk === "string" ? chunk : JSON.stringify(chunk);
78
+ process.nextTick(async () => {
79
+ try {
80
+ if (!redisClient.isOpen) {
81
+ await redisClient.connect().catch((err) => {
82
+ console.error("Redis connection error:", err);
83
+ });
84
+ }
85
+ const pipeline = redisClient.multi();
86
+ pipeline.rPush(logKey, logData);
87
+ pipeline.expire(logKey, ttl);
88
+ await pipeline.exec();
89
+ } catch (err) {
90
+ console.error("Redis logging error:", err);
91
+ }
92
+ });
93
+ callback(null, chunk);
94
+ }
95
+ _write(chunk, encoding, callback) {
96
+ if (typeof callback === "function") {
97
+ this._transform(chunk, encoding || "utf8", callback);
98
+ return true;
99
+ }
100
+ this._transform(chunk, encoding || "utf8", (error) => {
101
+ if (error) console.error("Transform error in write:", error);
102
+ });
103
+ return true;
104
+ }
105
+ async _flush() {
106
+ await new Promise((resolve2) => setTimeout(resolve2, 10));
107
+ }
108
+ async _destroy(err, cb) {
109
+ await closeLogger();
110
+ cb(err);
111
+ }
112
+ getLogs(_args) {
113
+ return Promise.resolve({
114
+ logs: [],
115
+ total: 0,
116
+ page: _args?.page ?? 1,
117
+ perPage: _args?.perPage ?? 100,
118
+ hasMore: false
119
+ });
120
+ }
121
+ getLogsByRunId(_args) {
122
+ return Promise.resolve({
123
+ logs: [],
124
+ total: 0,
125
+ page: _args?.page ?? 1,
126
+ perPage: _args?.perPage ?? 100,
127
+ hasMore: false
128
+ });
129
+ }
130
+ };
131
+ var transport = new RedisTransport();
132
+ var closeLogger = async () => {
133
+ if (redisClient.isOpen) {
134
+ setTimeout(async () => {
135
+ await redisClient.quit();
136
+ }, 10);
137
+ }
138
+ };
139
+ var logger = new PinoLogger({
140
+ level: "info",
141
+ transports: {
142
+ redis: transport
143
+ }
144
+ });
145
+
146
+ // src/utils/execa.ts
147
+ var createPinoStream = () => {
148
+ return new Transform({
149
+ transform(chunk, encoding, callback) {
150
+ const line = chunk.toString().trim();
151
+ if (line) {
152
+ logger.info(line);
153
+ }
154
+ callback(null, chunk);
155
+ }
156
+ });
157
+ };
158
+ async function runWithExeca({
159
+ cmd,
160
+ args,
161
+ cwd = process.cwd(),
162
+ env = PROJECT_ENV_VARS
163
+ }) {
164
+ const pinoStream = createPinoStream();
165
+ try {
166
+ const subprocess = execa(cmd, args, {
167
+ cwd,
168
+ env: {
169
+ ...process.env,
170
+ ...env
171
+ }
172
+ });
173
+ subprocess.stdout?.pipe(pinoStream);
174
+ subprocess.stderr?.pipe(pinoStream);
175
+ const { stdout, stderr, exitCode } = await subprocess;
176
+ return { stdout, stderr, success: exitCode === 0 };
177
+ } catch (error) {
178
+ logger.error(`Process failed: ${error}`);
179
+ return { success: false, error: error instanceof Error ? error : new Error(String(error)) };
180
+ }
181
+ }
182
+
183
+ // src/utils/deps.ts
184
+ var MEMOIZED = /* @__PURE__ */ new Map();
185
+ function findLockFile(dir) {
186
+ const lockFiles = ["pnpm-lock.yaml", "package-lock.json", "yarn.lock", "bun.lock"];
187
+ for (const file of lockFiles) {
188
+ if (fs.existsSync(join(dir, file))) {
189
+ return file;
190
+ }
191
+ }
192
+ const parentDir = resolve(dir, "..");
193
+ if (parentDir !== dir) {
194
+ return findLockFile(parentDir);
195
+ }
196
+ return null;
197
+ }
198
+ function detectPm({ path }) {
199
+ const cached = MEMOIZED.get(path);
200
+ if (cached) {
201
+ return cached;
202
+ }
203
+ const lockFile = findLockFile(path);
204
+ let pm = "npm";
205
+ switch (lockFile) {
206
+ case "pnpm-lock.yaml":
207
+ pm = "pnpm";
208
+ break;
209
+ case "package-lock.json":
210
+ pm = "npm";
211
+ break;
212
+ case "yarn.lock":
213
+ pm = "yarn";
214
+ break;
215
+ case "bun.lock":
216
+ pm = "bun";
217
+ break;
218
+ default:
219
+ pm = "npm";
220
+ }
221
+ MEMOIZED.set(path, pm);
222
+ return pm;
223
+ }
224
+ async function installDeps({ path, pm }) {
225
+ pm = pm ?? detectPm({ path });
226
+ logger.info(`Installing dependencies with ${pm} in ${path}`);
227
+ const args = ["install"];
228
+ const { success, error } = await runWithExeca({ cmd: pm, args, cwd: path });
229
+ if (!success) {
230
+ throw new MastraError(
231
+ {
232
+ id: "FAIL_INSTALL_DEPS",
233
+ category: "USER",
234
+ domain: "DEPLOYER"
235
+ },
236
+ error
237
+ );
238
+ }
239
+ }
240
+ function getMastraEntryFile(mastraDir) {
241
+ try {
242
+ const fileService = new FileService();
243
+ return fileService.getFirstExistingFile([
244
+ join(mastraDir, MASTRA_DIRECTORY, "index.ts"),
245
+ join(mastraDir, MASTRA_DIRECTORY, "index.js")
246
+ ]);
247
+ } catch (error) {
248
+ throw new MastraError(
249
+ {
250
+ id: "MASTRA_ENTRY_FILE_NOT_FOUND",
251
+ category: "USER",
252
+ domain: "DEPLOYER"
253
+ },
254
+ error
255
+ );
256
+ }
257
+ }
258
+
259
+ // src/utils/report.ts
260
+ function successEntrypoint() {
261
+ return `
262
+ if (process.env.CI !== 'true' && process.env.REPORTER_API_URL && process.env.REPORTER_API_URL_AUTH_TOKEN) {
263
+ await fetch(process.env.REPORTER_API_URL, {
264
+ method: 'POST',
265
+ headers: {
266
+ 'Content-Type': 'application/json',
267
+ Authorization: \`Bearer \${process.env.REPORTER_API_URL_AUTH_TOKEN}\`,
268
+ },
269
+ body: JSON.stringify(${JSON.stringify({
270
+ projectId: PROJECT_ID,
271
+ buildId: BUILD_ID,
272
+ status: "success",
273
+ url: BUILD_URL,
274
+ userIpAddress: USER_IP_ADDRESS
275
+ })}),
276
+ }).catch(err => {
277
+ console.error('Failed to report build status to monitoring service', {
278
+ error: err,
279
+ });
280
+ })
281
+ }
282
+ `;
283
+ }
284
+
285
+ // src/index.ts
286
+ var CloudDeployer = class extends Deployer {
287
+ constructor() {
288
+ super({ name: "cloud" });
289
+ }
290
+ async deploy(_outputDirectory) {
291
+ }
292
+ async writeInstrumentationFile(outputDirectory) {
293
+ const instrumentationFile = join(outputDirectory, "instrumentation.mjs");
294
+ const __dirname = dirname(fileURLToPath(import.meta.url));
295
+ await copy(join(__dirname, "../templates", "instrumentation-template.js"), instrumentationFile);
296
+ }
297
+ writePackageJson(outputDirectory, dependencies) {
298
+ dependencies.set("@mastra/loggers", "0.10.6");
299
+ dependencies.set("@mastra/libsql", "0.13.1");
300
+ dependencies.set("@mastra/cloud", "0.1.7");
301
+ return super.writePackageJson(outputDirectory, dependencies);
302
+ }
303
+ async lint() {
304
+ }
305
+ async installDependencies(outputDirectory, _rootDir = process.cwd()) {
306
+ await installDeps({ path: join(outputDirectory, "output"), pm: "npm" });
307
+ }
308
+ async bundle(mastraDir, outputDirectory) {
309
+ const currentCwd = process.cwd();
310
+ process.chdir(mastraDir);
311
+ const mastraEntryFile = getMastraEntryFile(mastraDir);
312
+ const defaultToolsPath = join(mastraDir, MASTRA_DIRECTORY, "tools");
313
+ await this._bundle(this.getEntry(), mastraEntryFile, outputDirectory, [defaultToolsPath]);
314
+ process.chdir(currentCwd);
315
+ }
316
+ getAuthEntrypoint() {
317
+ return getAuthEntrypoint();
318
+ }
319
+ getEntry() {
320
+ return `
321
+ import { createNodeServer, getToolExports } from '#server';
322
+ import { tools } from '#tools';
323
+ import { mastra } from '#mastra';
324
+ import { MultiLogger } from '@mastra/core/logger';
325
+ import { PinoLogger } from '@mastra/loggers';
326
+ import { UpstashTransport } from '@mastra/loggers/upstash';
327
+ import { HttpTransport } from '@mastra/loggers/http';
328
+ import { evaluate } from '@mastra/core/eval';
329
+ import { AvailableHooks, registerHook } from '@mastra/core/hooks';
330
+ import { LibSQLStore, LibSQLVector } from '@mastra/libsql';
331
+
332
+ const startTime = process.env.RUNNER_START_TIME ? new Date(process.env.RUNNER_START_TIME).getTime() : Date.now();
333
+ const createNodeServerStartTime = Date.now();
334
+
335
+ console.log(JSON.stringify({
336
+ message: "Server starting",
337
+ operation: 'builder.createNodeServer',
338
+ operation_startTime: createNodeServerStartTime,
339
+ type: "READINESS",
340
+ startTime,
341
+ metadata: {
342
+ teamId: "${TEAM_ID}",
343
+ projectId: "${PROJECT_ID}",
344
+ buildId: "${BUILD_ID}",
345
+ },
346
+ }));
347
+
348
+ const transports = {}
349
+ if (process.env.CI !== 'true') {
350
+ if (process.env.BUSINESS_API_RUNNER_LOGS_ENDPOINT) {
351
+ transports.default = new HttpTransport({
352
+ url: process.env.BUSINESS_API_RUNNER_LOGS_ENDPOINT,
353
+ headers: {
354
+ Authorization: 'Bearer ' + process.env.BUSINESS_JWT_TOKEN,
355
+ },
356
+ });
357
+ }
358
+ }
359
+
360
+ const logger = new PinoLogger({
361
+ name: 'MastraCloud',
362
+ transports,
363
+ level: 'debug',
364
+ });
365
+ const existingLogger = mastra?.getLogger();
366
+ const combinedLogger = existingLogger ? new MultiLogger([logger, existingLogger]) : logger;
367
+
368
+ mastra.setLogger({ logger: combinedLogger });
369
+
370
+ if (mastra?.storage) {
371
+ mastra.storage.init()
372
+ }
373
+
374
+ if (process.env.MASTRA_STORAGE_URL && process.env.MASTRA_STORAGE_AUTH_TOKEN) {
375
+ const { MastraStorage } = await import('@mastra/core/storage');
376
+ logger.info('Using Mastra Cloud Storage: ' + process.env.MASTRA_STORAGE_URL)
377
+ const storage = new LibSQLStore({
378
+ url: process.env.MASTRA_STORAGE_URL,
379
+ authToken: process.env.MASTRA_STORAGE_AUTH_TOKEN,
380
+ })
381
+ const vector = new LibSQLVector({
382
+ connectionUrl: process.env.MASTRA_STORAGE_URL,
383
+ authToken: process.env.MASTRA_STORAGE_AUTH_TOKEN,
384
+ })
385
+
386
+ await storage.init()
387
+ mastra?.setStorage(storage)
388
+
389
+ mastra?.memory?.setStorage(storage)
390
+ mastra?.memory?.setVector(vector)
391
+
392
+ registerHook(AvailableHooks.ON_GENERATION, ({ input, output, metric, runId, agentName, instructions }) => {
393
+ evaluate({
394
+ agentName,
395
+ input,
396
+ metric,
397
+ output,
398
+ runId,
399
+ globalRunId: runId,
400
+ instructions,
401
+ });
402
+ });
403
+ registerHook(AvailableHooks.ON_EVALUATION, async traceObject => {
404
+ if (mastra?.storage) {
405
+ await mastra.storage.insert({
406
+ tableName: MastraStorage.TABLE_EVALS,
407
+ record: {
408
+ input: traceObject.input,
409
+ output: traceObject.output,
410
+ result: JSON.stringify(traceObject.result),
411
+ agent_name: traceObject.agentName,
412
+ metric_name: traceObject.metricName,
413
+ instructions: traceObject.instructions,
414
+ test_info: null,
415
+ global_run_id: traceObject.globalRunId,
416
+ run_id: traceObject.runId,
417
+ created_at: new Date().toISOString(),
418
+ },
419
+ });
420
+ }
421
+ });
422
+ }
423
+
424
+ ${getAuthEntrypoint()}
425
+
426
+ await createNodeServer(mastra, { playground: false, swaggerUI: false, tools: getToolExports(tools) });
427
+
428
+ ${successEntrypoint()}
429
+
430
+ console.log(JSON.stringify({
431
+ message: "Server started",
432
+ operation: 'builder.createNodeServer',
433
+ operation_startTime: createNodeServerStartTime,
434
+ operation_durationMs: Date.now() - createNodeServerStartTime,
435
+ type: "READINESS",
436
+ startTime,
437
+ metadata: {
438
+ teamId: "${TEAM_ID}",
439
+ projectId: "${PROJECT_ID}",
440
+ buildId: "${BUILD_ID}",
441
+ },
442
+ }));
443
+
444
+
445
+ console.log(JSON.stringify({
446
+ message: "Runner Initialized",
447
+ type: "READINESS",
448
+ startTime,
449
+ durationMs: Date.now() - startTime,
450
+ metadata: {
451
+ teamId: "${TEAM_ID}",
452
+ projectId: "${PROJECT_ID}",
453
+ buildId: "${BUILD_ID}",
454
+ },
455
+ }));
456
+ `;
457
+ }
458
+ };
459
+
460
+ export { CloudDeployer };
461
+ //# sourceMappingURL=index.js.map
462
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/auth.ts","../src/utils/constants.ts","../src/utils/logger.ts","../src/utils/execa.ts","../src/utils/deps.ts","../src/utils/file.ts","../src/utils/report.ts","../src/index.ts"],"names":["resolve","join","MastraError"],"mappings":";;;;;;;;;;;;;;;;AAAO,SAAS,iBAAA,GAAoB;AAClC,EAAA,OAAO;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA,6EAAA,EAUsE,OAAA,CAAQ,IAAI,kBAAkB,CAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAAA,CAAA;AAuB7G;AChCO,IAAM,KAAA,GAAQ,OAAA,CAAQ,GAAA,CAAI,KAAA,KAAU,MAAA;AACpC,IAAM,OAAA,GAAkB,OAAA,CAAQ,GAAA,CAAI,OAAA,IAAW,EAAA;AAC/C,IAAM,UAAA,GAAqB,OAAA,CAAQ,GAAA,CAAI,UAAA,IAAc,EAAA;AACrD,IAAM,QAAA,GAAmB,OAAA,CAAQ,GAAA,CAAI,QAAA,IAAY,EAAA;AACjD,IAAM,SAAA,GAAoB,OAAA,CAAQ,GAAA,CAAI,SAAA,IAAa,EAAA;AACnD,IAAM,aAAA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O,CAAA;AAAA,gBAAA,EACJ,UAAU,CAAA;AAAA,cAAA,EACZ,QAAQ,CAAA;AAAA;AAAA;AAAA,CAAA;AAAA,EAItB;AACF","file":"index.js","sourcesContent":["export function getAuthEntrypoint() {\n return `\n import { MastraAuthProvider } from '@mastra/core/server';\n\n class MastraCloudAuth extends MastraAuthProvider {\n constructor (auth) {\n super()\n this.auth = auth\n }\n\n async authenticateToken (...args) {\n if (typeof args[0] === 'string' && args[0].replace('Bearer ', '') === '${process.env.BUSINESS_JWT_TOKEN}') {\n return { id: 'business-api' }\n }\n return this.auth.authenticateToken(...args)\n }\n\n async authorizeUser (...args) {\n if (args[1] && args[1].path === '/api') {\n return true\n }\n if (args[0] && args[0].id === 'business-api') {\n return true\n }\n return this.auth.authorizeUser(...args)\n }\n }\n\n const serverConfig = mastra.getServer()\n if (serverConfig && serverConfig.experimental_auth) {\n const auth = serverConfig.experimental_auth\n serverConfig.experimental_auth = new MastraCloudAuth(auth)\n }\n `;\n}\n","import os from 'os';\n\nexport const LOCAL = process.env.LOCAL === 'true';\nexport const TEAM_ID: string = process.env.TEAM_ID ?? '';\nexport const PROJECT_ID: string = process.env.PROJECT_ID ?? '';\nexport const BUILD_ID: string = process.env.BUILD_ID ?? '';\nexport const BUILD_URL: string = process.env.BUILD_URL ?? '';\nexport const LOG_REDIS_URL: string = process.env.LOG_REDIS_URL ?? 'redis://localhost:6379';\nexport const BUSINESS_JWT_TOKEN: string = process.env.BUSINESS_JWT_TOKEN ?? '';\nexport const USER_IP_ADDRESS: string = process.env.USER_IP_ADDRESS ?? '';\nexport const MASTRA_DIRECTORY: string = process.env.MASTRA_DIRECTORY ?? 'src/mastra';\nexport const PROJECT_ENV_VARS: Record<string, string> = safelyParseJson(process.env.PROJECT_ENV_VARS ?? '{}');\n\nexport const PROJECT_ROOT = LOCAL ? os.tmpdir() + '/project' : (process.env.PROJECT_ROOT ?? '/project');\n\nexport function safelyParseJson(json: string) {\n try {\n return JSON.parse(json);\n } catch {\n return {};\n }\n}\n","import type { TransformCallback } from 'stream';\nimport type { BaseLogMessage, LogLevel } from '@mastra/core/logger';\nimport { LoggerTransport } from '@mastra/core/logger';\nimport { PinoLogger } from '@mastra/loggers';\nimport { createClient } from 'redis';\nimport { BUILD_ID, LOG_REDIS_URL, PROJECT_ID, TEAM_ID } from './constants.js';\n\nconst redisClient = createClient({\n url: LOG_REDIS_URL,\n});\n\nclass RedisTransport extends LoggerTransport {\n _transform(chunk: any, _encoding: string, callback: TransformCallback): void {\n chunk = chunk.toString();\n const logKey = `builder:logs:${TEAM_ID}:${PROJECT_ID}:${BUILD_ID}`;\n const ttl = 2 * 24 * 60 * 60; // 2 days in seconds\n const logData = typeof chunk === 'string' ? chunk : JSON.stringify(chunk);\n\n // Don't block the event loop - process logs asynchronously\n process.nextTick(async () => {\n try {\n // Connect to Redis if not already connected\n if (!redisClient.isOpen) {\n await redisClient.connect().catch(err => {\n console.error('Redis connection error:', err);\n });\n }\n\n // Use pipeline to batch Redis operations\n const pipeline = redisClient.multi();\n pipeline.rPush(logKey, logData);\n pipeline.expire(logKey, ttl);\n await pipeline.exec();\n } catch (err) {\n console.error('Redis logging error:', err);\n }\n });\n\n // Immediately pass through the chunk without waiting\n callback(null, chunk);\n }\n\n _write(chunk: any, encoding?: string, callback?: (error?: Error | null) => void): boolean {\n if (typeof callback === 'function') {\n this._transform(chunk, encoding || 'utf8', callback);\n return true;\n }\n\n this._transform(chunk, encoding || 'utf8', (error: Error | null | undefined) => {\n if (error) console.error('Transform error in write:', error);\n });\n return true;\n }\n\n async _flush(): Promise<void> {\n // // Ensure the pipeline is closed and flushed\n // redisClient.quit().catch(err => {\n // console.error('Redis connection error:', err);\n // });\n // callback();\n await new Promise(resolve => setTimeout(resolve, 10));\n }\n\n async _destroy(err: Error, cb: Function) {\n await closeLogger();\n cb(err);\n }\n\n getLogs(_args: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean;\n page?: number;\n perPage?: number;\n }): Promise<{ logs: BaseLogMessage[]; total: number; page: number; perPage: number; hasMore: boolean }> {\n return Promise.resolve({\n logs: [],\n total: 0,\n page: _args?.page ?? 1,\n perPage: _args?.perPage ?? 100,\n hasMore: false,\n });\n }\n\n getLogsByRunId(_args?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean;\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n return Promise.resolve({\n logs: [],\n total: 0,\n page: _args?.page ?? 1,\n perPage: _args?.perPage ?? 100,\n hasMore: false,\n });\n }\n}\n\nexport const transport = new RedisTransport();\n\nexport const closeLogger = async () => {\n if (redisClient.isOpen) {\n setTimeout(async () => {\n await redisClient.quit();\n }, 10);\n }\n};\n\nexport const logger = new PinoLogger({\n level: 'info',\n transports: {\n redis: transport,\n },\n});\n","import { Transform } from 'stream';\nimport { execa } from 'execa';\nimport { PROJECT_ENV_VARS, PROJECT_ROOT } from './constants.js';\nimport { logger } from './logger.js';\n\nexport const createPinoStream = () => {\n return new Transform({\n transform(chunk, encoding, callback) {\n // Convert Buffer/string to string and trim whitespace\n const line = chunk.toString().trim();\n\n if (line) {\n // Log each line through Pino\n logger.info(line);\n }\n\n // Pass through the original data\n callback(null, chunk);\n },\n });\n};\n\nexport async function runWithExeca({\n cmd,\n args,\n cwd = process.cwd(),\n env = PROJECT_ENV_VARS,\n}: {\n cmd: string;\n args: string[];\n cwd?: string;\n env?: Record<string, string>;\n}): Promise<{ stdout?: string; stderr?: string; success: boolean; error?: Error }> {\n const pinoStream = createPinoStream();\n\n try {\n const subprocess = execa(cmd, args, {\n cwd,\n env: {\n ...process.env,\n ...env,\n },\n });\n\n // Pipe stdout and stderr through the Pino stream\n subprocess.stdout?.pipe(pinoStream);\n subprocess.stderr?.pipe(pinoStream);\n\n const { stdout, stderr, exitCode } = await subprocess;\n return { stdout, stderr, success: exitCode === 0 };\n } catch (error) {\n logger.error(`Process failed: ${error}`);\n return { success: false, error: error instanceof Error ? error : new Error(String(error)) };\n }\n}\n\nexport function runWithChildProcess(cmd: string, args: string[]): { stdout?: string; stderr?: string } {\n const pinoStream = createPinoStream();\n\n try {\n const { stdout, stderr } = require('child_process').spawnSync(cmd, args, {\n cwd: PROJECT_ROOT,\n encoding: 'utf8',\n shell: true,\n env: {\n ...process.env,\n ...PROJECT_ENV_VARS,\n },\n maxBuffer: 1024 * 1024 * 10, // 10MB buffer\n });\n\n if (stdout) {\n pinoStream.write(stdout);\n }\n if (stderr) {\n pinoStream.write(stderr);\n }\n\n pinoStream.end();\n return { stdout, stderr };\n } catch (error) {\n logger.error('Process failed' + error);\n pinoStream.end();\n return {};\n }\n}\n","import * as fs from 'fs';\nimport { join, resolve } from 'path';\n\nimport { MastraError } from '@mastra/core/error';\nimport { runWithExeca } from './execa.js';\nimport { logger } from './logger.js';\n\nconst MEMOIZED = new Map();\n\nfunction findLockFile(dir: string): string | null {\n const lockFiles = ['pnpm-lock.yaml', 'package-lock.json', 'yarn.lock', 'bun.lock'];\n for (const file of lockFiles) {\n if (fs.existsSync(join(dir, file))) {\n return file;\n }\n }\n const parentDir = resolve(dir, '..');\n if (parentDir !== dir) {\n return findLockFile(parentDir);\n }\n return null;\n}\n\nexport function detectPm({ path }: { path: string }): string {\n const cached = MEMOIZED.get(path);\n if (cached) {\n return cached;\n }\n\n const lockFile = findLockFile(path);\n let pm: string = 'npm';\n switch (lockFile) {\n case 'pnpm-lock.yaml':\n pm = 'pnpm';\n break;\n case 'package-lock.json':\n pm = 'npm';\n break;\n case 'yarn.lock':\n pm = 'yarn';\n break;\n case 'bun.lock':\n pm = 'bun';\n break;\n default:\n pm = 'npm';\n }\n\n MEMOIZED.set(path, pm);\n return pm;\n}\n\nexport async function installNodeVersion({ path }: { path: string }) {\n let nvmrcExists = false;\n let nodeVersionExists = false;\n\n try {\n fs.accessSync(join(path, '.nvmrc'));\n nvmrcExists = true;\n } catch {\n // File does not exist\n }\n\n try {\n fs.accessSync(join(path, '.node-version'));\n nodeVersionExists = true;\n } catch {\n // File does not exist\n }\n\n if (nvmrcExists || nodeVersionExists) {\n logger.info('Node version file found, installing specified Node.js version...');\n const { success, error } = await runWithExeca({\n cmd: 'n',\n args: ['auto'],\n cwd: path,\n });\n if (!success) {\n throw new MastraError(\n {\n id: 'NODE_FAIL_INSTALL_SPECIFIED_VERSION',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n }\n}\n\nexport async function installDeps({ path, pm }: { path: string; pm?: string }) {\n pm = pm ?? detectPm({ path });\n logger.info(`Installing dependencies with ${pm} in ${path}`);\n const args = ['install'];\n const { success, error } = await runWithExeca({ cmd: pm, args, cwd: path });\n if (!success) {\n throw new MastraError(\n {\n id: 'FAIL_INSTALL_DEPS',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n}\n\nexport async function runInstallCommand({ path, installCommand }: { path: string; installCommand: string }) {\n logger.info(`Running install command ${installCommand} in workspace with ${path}`);\n const { success, error } = await runWithExeca({ cmd: 'sh', args: ['-c', installCommand], cwd: path });\n if (!success) {\n throw new MastraError(\n {\n id: 'FAIL_CUSTOM_INSTALL_COMMAND',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n}\n\nexport async function runScript({ scriptName, path, args }: { scriptName: string; path: string; args?: string[] }) {\n const pm = detectPm({ path });\n logger.info(`Running script ${scriptName} in workspace with ${pm}`);\n const { success, error } = await runWithExeca({\n cmd: pm,\n args: pm === 'npm' ? ['run', scriptName, ...(args ?? [])] : [scriptName, ...(args ?? [])],\n cwd: path,\n });\n if (!success) {\n throw new MastraError(\n {\n id: 'FAIL_BUILD_SCRIPT',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n}\n\nexport async function runBuildCommand({ command, path }: { command: string; path: string }) {\n logger.info(`Running build command ${command}`);\n const { success, error } = await runWithExeca({ cmd: 'sh', args: ['-c', command], cwd: path });\n if (!success) {\n throw new MastraError(\n {\n id: 'FAIL_BUILD_COMMAND',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n}\n","import { join } from 'path';\nimport { MastraError } from '@mastra/core/error';\nimport { FileService } from '@mastra/deployer';\n\nimport { MASTRA_DIRECTORY } from './constants.js';\n\nexport function getMastraEntryFile(mastraDir: string) {\n try {\n const fileService = new FileService();\n return fileService.getFirstExistingFile([\n join(mastraDir, MASTRA_DIRECTORY, 'index.ts'),\n join(mastraDir, MASTRA_DIRECTORY, 'index.js'),\n ]);\n } catch (error) {\n throw new MastraError(\n {\n id: 'MASTRA_ENTRY_FILE_NOT_FOUND',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n}\n","import { PROJECT_ID, BUILD_ID, BUILD_URL, USER_IP_ADDRESS } from './constants.js';\n\nexport function successEntrypoint() {\n return `\n if (process.env.CI !== 'true' && process.env.REPORTER_API_URL && process.env.REPORTER_API_URL_AUTH_TOKEN) {\n await fetch(process.env.REPORTER_API_URL, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: \\`Bearer \\$\\{process.env.REPORTER_API_URL_AUTH_TOKEN\\}\\`,\n },\n body: JSON.stringify(${JSON.stringify({\n projectId: PROJECT_ID,\n buildId: BUILD_ID,\n status: 'success',\n url: BUILD_URL,\n userIpAddress: USER_IP_ADDRESS,\n })}),\n }).catch(err => {\n console.error('Failed to report build status to monitoring service', {\n error: err,\n });\n })\n }\n `;\n}\n","import { fileURLToPath } from 'node:url';\nimport { join, dirname } from 'path';\nimport { Deployer } from '@mastra/deployer';\nimport { copy } from 'fs-extra';\n\nimport { getAuthEntrypoint } from './utils/auth.js';\nimport { MASTRA_DIRECTORY, BUILD_ID, PROJECT_ID, TEAM_ID } from './utils/constants.js';\nimport { installDeps } from './utils/deps.js';\nimport { getMastraEntryFile } from './utils/file.js';\nimport { successEntrypoint } from './utils/report.js';\n\nexport class CloudDeployer extends Deployer {\n constructor() {\n super({ name: 'cloud' });\n }\n\n async deploy(_outputDirectory: string): Promise<void> {}\n async writeInstrumentationFile(outputDirectory: string) {\n const instrumentationFile = join(outputDirectory, 'instrumentation.mjs');\n const __dirname = dirname(fileURLToPath(import.meta.url));\n\n await copy(join(__dirname, '../templates', 'instrumentation-template.js'), instrumentationFile);\n }\n writePackageJson(outputDirectory: string, dependencies: Map<string, string>) {\n dependencies.set('@mastra/loggers', '0.10.6');\n dependencies.set('@mastra/libsql', '0.13.1');\n dependencies.set('@mastra/cloud', '0.1.7');\n return super.writePackageJson(outputDirectory, dependencies);\n }\n\n async lint() {}\n\n protected async installDependencies(outputDirectory: string, _rootDir = process.cwd()) {\n await installDeps({ path: join(outputDirectory, 'output'), pm: 'npm' });\n }\n\n async bundle(mastraDir: string, outputDirectory: string): Promise<void> {\n const currentCwd = process.cwd();\n process.chdir(mastraDir);\n\n const mastraEntryFile = getMastraEntryFile(mastraDir);\n\n const defaultToolsPath = join(mastraDir, MASTRA_DIRECTORY, 'tools');\n\n await this._bundle(this.getEntry(), mastraEntryFile, outputDirectory, [defaultToolsPath]);\n process.chdir(currentCwd);\n }\n\n getAuthEntrypoint() {\n return getAuthEntrypoint();\n }\n\n private getEntry(): string {\n return `\nimport { createNodeServer, getToolExports } from '#server';\nimport { tools } from '#tools';\nimport { mastra } from '#mastra';\nimport { MultiLogger } from '@mastra/core/logger';\nimport { PinoLogger } from '@mastra/loggers';\nimport { UpstashTransport } from '@mastra/loggers/upstash';\nimport { HttpTransport } from '@mastra/loggers/http';\nimport { evaluate } from '@mastra/core/eval';\nimport { AvailableHooks, registerHook } from '@mastra/core/hooks';\nimport { LibSQLStore, LibSQLVector } from '@mastra/libsql';\n\nconst startTime = process.env.RUNNER_START_TIME ? new Date(process.env.RUNNER_START_TIME).getTime() : Date.now();\nconst createNodeServerStartTime = Date.now();\n\nconsole.log(JSON.stringify({\n message: \"Server starting\",\n operation: 'builder.createNodeServer',\n operation_startTime: createNodeServerStartTime,\n type: \"READINESS\",\n startTime,\n metadata: {\n teamId: \"${TEAM_ID}\",\n projectId: \"${PROJECT_ID}\",\n buildId: \"${BUILD_ID}\",\n },\n}));\n\nconst transports = {}\nif (process.env.CI !== 'true') {\n if (process.env.BUSINESS_API_RUNNER_LOGS_ENDPOINT) {\n transports.default = new HttpTransport({\n url: process.env.BUSINESS_API_RUNNER_LOGS_ENDPOINT,\n headers: {\n Authorization: 'Bearer ' + process.env.BUSINESS_JWT_TOKEN,\n },\n });\n }\n}\n\nconst logger = new PinoLogger({\n name: 'MastraCloud',\n transports,\n level: 'debug',\n});\nconst existingLogger = mastra?.getLogger();\nconst combinedLogger = existingLogger ? new MultiLogger([logger, existingLogger]) : logger;\n\nmastra.setLogger({ logger: combinedLogger });\n\nif (mastra?.storage) {\n mastra.storage.init()\n}\n\nif (process.env.MASTRA_STORAGE_URL && process.env.MASTRA_STORAGE_AUTH_TOKEN) {\n const { MastraStorage } = await import('@mastra/core/storage');\n logger.info('Using Mastra Cloud Storage: ' + process.env.MASTRA_STORAGE_URL)\n const storage = new LibSQLStore({\n url: process.env.MASTRA_STORAGE_URL,\n authToken: process.env.MASTRA_STORAGE_AUTH_TOKEN,\n })\n const vector = new LibSQLVector({\n connectionUrl: process.env.MASTRA_STORAGE_URL,\n authToken: process.env.MASTRA_STORAGE_AUTH_TOKEN,\n })\n\n await storage.init()\n mastra?.setStorage(storage)\n\n mastra?.memory?.setStorage(storage)\n mastra?.memory?.setVector(vector)\n\n registerHook(AvailableHooks.ON_GENERATION, ({ input, output, metric, runId, agentName, instructions }) => {\n evaluate({\n agentName,\n input,\n metric,\n output,\n runId,\n globalRunId: runId,\n instructions,\n });\n });\n registerHook(AvailableHooks.ON_EVALUATION, async traceObject => {\n if (mastra?.storage) {\n await mastra.storage.insert({\n tableName: MastraStorage.TABLE_EVALS,\n record: {\n input: traceObject.input,\n output: traceObject.output,\n result: JSON.stringify(traceObject.result),\n agent_name: traceObject.agentName,\n metric_name: traceObject.metricName,\n instructions: traceObject.instructions,\n test_info: null,\n global_run_id: traceObject.globalRunId,\n run_id: traceObject.runId,\n created_at: new Date().toISOString(),\n },\n });\n }\n });\n}\n\n${getAuthEntrypoint()}\n\nawait createNodeServer(mastra, { playground: false, swaggerUI: false, tools: getToolExports(tools) });\n\n${successEntrypoint()}\n\nconsole.log(JSON.stringify({\n message: \"Server started\",\n operation: 'builder.createNodeServer',\n operation_startTime: createNodeServerStartTime,\n operation_durationMs: Date.now() - createNodeServerStartTime,\n type: \"READINESS\",\n startTime,\n metadata: {\n teamId: \"${TEAM_ID}\",\n projectId: \"${PROJECT_ID}\",\n buildId: \"${BUILD_ID}\",\n },\n}));\n\n\nconsole.log(JSON.stringify({\n message: \"Runner Initialized\",\n type: \"READINESS\",\n startTime,\n durationMs: Date.now() - startTime,\n metadata: {\n teamId: \"${TEAM_ID}\",\n projectId: \"${PROJECT_ID}\",\n buildId: \"${BUILD_ID}\",\n },\n}));\n`;\n }\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export declare function getAuthEntrypoint(): string;
2
+ //# sourceMappingURL=auth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../src/utils/auth.ts"],"names":[],"mappings":"AAAA,wBAAgB,iBAAiB,WAkChC"}
@@ -0,0 +1,13 @@
1
+ export declare const LOCAL: boolean;
2
+ export declare const TEAM_ID: string;
3
+ export declare const PROJECT_ID: string;
4
+ export declare const BUILD_ID: string;
5
+ export declare const BUILD_URL: string;
6
+ export declare const LOG_REDIS_URL: string;
7
+ export declare const BUSINESS_JWT_TOKEN: string;
8
+ export declare const USER_IP_ADDRESS: string;
9
+ export declare const MASTRA_DIRECTORY: string;
10
+ export declare const PROJECT_ENV_VARS: Record<string, string>;
11
+ export declare const PROJECT_ROOT: string;
12
+ export declare function safelyParseJson(json: string): any;
13
+ //# sourceMappingURL=constants.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../src/utils/constants.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,KAAK,SAA+B,CAAC;AAClD,eAAO,MAAM,OAAO,EAAE,MAAkC,CAAC;AACzD,eAAO,MAAM,UAAU,EAAE,MAAqC,CAAC;AAC/D,eAAO,MAAM,QAAQ,EAAE,MAAmC,CAAC;AAC3D,eAAO,MAAM,SAAS,EAAE,MAAoC,CAAC;AAC7D,eAAO,MAAM,aAAa,EAAE,MAA8D,CAAC;AAC3F,eAAO,MAAM,kBAAkB,EAAE,MAA6C,CAAC;AAC/E,eAAO,MAAM,eAAe,EAAE,MAA0C,CAAC;AACzE,eAAO,MAAM,gBAAgB,EAAE,MAAqD,CAAC;AACrF,eAAO,MAAM,gBAAgB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAyD,CAAC;AAE9G,eAAO,MAAM,YAAY,QAA8E,CAAC;AAExG,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,OAM3C"}