@mastra/deployer-sandbox 0.1.4-alpha.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +60 -0
- package/README.md +35 -3
- package/dist/engine.d.ts +15 -0
- package/dist/engine.d.ts.map +1 -1
- package/dist/index.cjs +441 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +444 -4
- package/dist/index.js.map +1 -1
- package/dist/studio/assets/{core-DBMTExoC.js → core--7ykYG3U.js} +1 -1
- package/dist/studio/assets/{index-BWUrnwYU.js → index-C5anT3qx.js} +2 -2
- package/dist/studio/assets/{main-BNh36EOV.js → main-DomdLuyE.js} +203 -203
- package/dist/studio/assets/style-BP65E3ZK.css +1 -0
- package/dist/studio/index.html +2 -2
- package/dist/types.d.ts +125 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/worker.d.ts +3 -0
- package/dist/worker.d.ts.map +1 -0
- package/package.json +6 -6
- package/dist/studio/assets/style-CCIqdv0s.css +0 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["execFile","DEFAULT_PORT","resolveRemoteDir","runInSandbox","shellQuote","killPreviousServer","INSTALL_MARKER","SERVER_SCRIPT","launchServer","waitForHealthy","tailServerLog","getInfoSafe","SERVER_PIDFILE","SERVER_LOGFILE","Deployer"],"sources":["../src/alias.ts","../src/engine.ts","../src/manifest.ts","../src/deployer.ts"],"sourcesContent":["import type { SandboxAliasOptions } from './types';\n\n/**\n * Upsert a Vercel Edge Config item so a stable key always points at the\n * current sandbox URL. Used for Tier 3 routing: apps read the key from Edge\n * Config (e.g. in middleware) instead of hardcoding the rotating sandbox URL.\n */\nexport async function updateEdgeConfigAlias(options: SandboxAliasOptions & { url: string }): Promise<void> {\n const { token, teamId } = options;\n if (!token) {\n throw new Error('Updating the Edge Config alias requires a Vercel API token. Pass `alias.token`.');\n }\n\n const endpoint = new URL(`https://api.vercel.com/v1/edge-config/${options.edgeConfigId}/items`);\n if (teamId) {\n endpoint.searchParams.set('teamId', teamId);\n }\n\n const res = await fetch(endpoint, {\n method: 'PATCH',\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n items: [{ operation: 'upsert', key: options.key, value: options.url }],\n }),\n // Bounded so a hung Vercel API request can't keep `mastra build` open\n // after the sandbox itself is already deployed.\n signal: AbortSignal.timeout(30_000),\n });\n\n if (!res.ok) {\n const body = await res.text().catch(() => '');\n throw new Error(`Failed to update Edge Config alias \"${options.key}\" (${res.status}): ${body}`);\n }\n}\n","import { execFile } from 'node:child_process';\nimport { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { mkdtemp, readFile, rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { promisify } from 'node:util';\nimport { supportsNetworking } from '@mastra/core/workspace';\nimport type { WorkspaceSandbox } from '@mastra/core/workspace';\nimport {\n DEFAULT_PORT,\n INSTALL_MARKER,\n SERVER_LOGFILE,\n SERVER_PIDFILE,\n SERVER_SCRIPT,\n getInfoSafe,\n killPreviousServer,\n launchServer,\n resolveRemoteDir,\n runInSandbox,\n shellQuote,\n tailServerLog,\n waitForHealthy,\n} from './shared';\nimport type { DeployToSandboxOptions, SandboxDeployLogger, SandboxDeployment } from './types';\n\nconst execFileAsync = promisify(execFile);\n\nconst noopLogger: SandboxDeployLogger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n};\n\n/** Max shell-command payload per chunk for the base64 upload fallback. */\nconst UPLOAD_CHUNK_SIZE = 96_000;\n\n/**\n * Deploy a prebuilt Mastra server directory into any workspace sandbox that\n * supports networking. Provider-agnostic: only uses the core WorkspaceSandbox\n * contract (`executeCommand` + `networking`, with `writeFiles` / `processes`\n * as fast paths).\n */\nexport async function deployToSandbox(options: DeployToSandboxOptions): Promise<SandboxDeployment> {\n const {\n sandbox,\n dir,\n port = DEFAULT_PORT,\n env = {},\n studio = false,\n healthCheckPath = '/api',\n healthCheckTimeoutMs = 60_000,\n healthCheckIntervalMs = 1_000,\n installCommand = 'npm install --omit=dev',\n logger = noopLogger,\n } = options;\n\n if (!existsSync(join(dir, 'index.mjs'))) {\n throw new Error(`No index.mjs found in \"${dir}\" — did the build succeed?`);\n }\n\n // 1. Start (providers handle create-or-resume by identity, e.g. sandbox name).\n logger.info(`Starting ${sandbox.provider} sandbox...`);\n await sandbox.start?.();\n\n if (!supportsNetworking(sandbox)) {\n throw new Error(\n `Sandbox provider \"${sandbox.provider}\" does not support networking (public port URLs), ` +\n `which is required for sandbox deploys.`,\n );\n }\n if (!sandbox.executeCommand) {\n throw new Error(\n `Sandbox provider \"${sandbox.provider}\" does not support executeCommand, which is required for sandbox deploys.`,\n );\n }\n\n const url = await sandbox.networking.getPortUrl(port);\n if (!url) {\n throw new Error(\n `Sandbox provider \"${sandbox.provider}\" did not expose a public URL for port ${port}. ` +\n `Make sure the port is declared when constructing the sandbox (e.g. \\`ports: [${port}]\\`).`,\n );\n }\n\n // Default the remote dir to $HOME/mastra-app — home directories persist\n // across snapshot stop/resume (unlike /tmp), so wakes find the app intact.\n const remoteDir = await resolveRemoteDir(sandbox, options.remoteDir);\n\n const mergedEnv = { ...env };\n if (studio && mergedEnv.MASTRA_STUDIO_PATH === undefined) {\n mergedEnv.MASTRA_STUDIO_PATH = `${remoteDir}/studio`;\n }\n\n // 2. Upload the build output as a tarball and extract it in the sandbox.\n logger.info(`Uploading build output from ${dir}...`);\n const tarball = await createTarball(dir);\n logger.debug(`Tarball size: ${(tarball.length / 1024 / 1024).toFixed(2)} MB`);\n\n const remoteTarball = `${remoteDir}/.deploy.tgz`;\n await runInSandbox(sandbox, `mkdir -p ${shellQuote(remoteDir)}`);\n await uploadFile(sandbox, remoteTarball, tarball);\n\n // Stop the previous server BEFORE extracting over the live directory so it\n // can never serve a mix of old and new files while the release lands.\n await killPreviousServer(sandbox, remoteDir);\n\n await runInSandbox(sandbox, `cd ${shellQuote(remoteDir)} && tar -xzf .deploy.tgz && rm -f .deploy.tgz`, {\n timeout: 120_000,\n });\n\n // 3. Install dependencies, skipped when the install inputs (package.json,\n // bundled lockfiles, and the install command itself) are unchanged since\n // the last completed install.\n const installHash = await hashInstallInputs(dir, installCommand);\n const marker = `${remoteDir}/${INSTALL_MARKER}`;\n const markerCheck = await runInSandbox(sandbox, `cat ${shellQuote(marker)} 2>/dev/null || true`, {\n allowFailure: true,\n });\n\n if (installHash && markerCheck.stdout.trim() === installHash) {\n logger.info('Dependencies unchanged — skipping install.');\n } else {\n logger.info(`Installing dependencies (${installCommand})...`);\n await runInSandbox(sandbox, `cd ${shellQuote(remoteDir)} && ${installCommand}`, {\n timeout: 600_000,\n label: `install dependencies (${installCommand})`,\n });\n if (installHash) {\n await runInSandbox(sandbox, `printf '%s' ${shellQuote(installHash)} > ${shellQuote(marker)}`);\n }\n }\n\n // 4. Write the launch script and start the new server (the previous one was\n // stopped before extraction).\n const launchScript = buildLaunchScript({ remoteDir, port, env: mergedEnv });\n await uploadFile(sandbox, `${remoteDir}/${SERVER_SCRIPT}`, Buffer.from(launchScript));\n await runInSandbox(sandbox, `chmod 700 ${shellQuote(`${remoteDir}/${SERVER_SCRIPT}`)}`);\n\n logger.info('Starting Mastra server...');\n await launchServer(sandbox, remoteDir);\n\n // 5. Wait for the server to answer on its public URL.\n const healthy = await waitForHealthy(url, {\n path: healthCheckPath,\n timeoutMs: healthCheckTimeoutMs,\n intervalMs: healthCheckIntervalMs,\n });\n if (!healthy) {\n const log = await tailServerLog(sandbox, remoteDir).catch(() => '');\n throw new Error(\n `Mastra server did not become healthy at ${url}${healthCheckPath} within ${healthCheckTimeoutMs}ms.` +\n (log ? `\\n\\nServer log:\\n${log}` : '\\n\\n(no server log output captured)'),\n );\n }\n\n const info = await getInfoSafe(sandbox);\n\n return {\n url,\n sandboxId: info?.id ?? sandbox.id,\n expiresAt: info?.timeoutAt,\n stop: async () => {\n await sandbox.stop?.();\n },\n destroy: async () => {\n await sandbox.destroy?.();\n },\n logs: (lines?: number) => tailServerLog(sandbox, remoteDir, lines),\n };\n}\n\n/**\n * Build the POSIX launch script. Re-running the script restarts the server —\n * the wake path uses this after a snapshot resume (which restores the\n * filesystem but not processes).\n */\nexport function buildLaunchScript(opts: { remoteDir: string; port: number; env: Record<string, string> }): string {\n const lines = ['#!/bin/sh', `cd ${shellQuote(opts.remoteDir)}`];\n\n // MASTRA_AUTO_DETECT_URL so Studio connects to the sandbox's public URL\n // (same origin) instead of localhost:4111 — overridable. PORT and\n // MASTRA_HOST are applied AFTER custom env: networking (`getPortUrl`) and\n // health checks target the configured port, and the server must bind\n // 0.0.0.0 to be reachable through the public port proxy. Change the port\n // via the deploy `port` option, not env.\n const env: Record<string, string> = {\n MASTRA_AUTO_DETECT_URL: 'true',\n ...opts.env,\n PORT: String(opts.port),\n MASTRA_HOST: '0.0.0.0',\n };\n for (const [key, value] of Object.entries(env)) {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) {\n throw new Error(`Invalid environment variable name: \"${key}\"`);\n }\n lines.push(`export ${key}=${shellQuote(value)}`);\n }\n\n lines.push(`echo $$ > ${shellQuote(SERVER_PIDFILE)}`);\n lines.push(`exec node index.mjs >> ${shellQuote(SERVER_LOGFILE)} 2>&1`);\n return lines.join('\\n') + '\\n';\n}\n\n/** Create a gzipped tarball of the directory contents (excluding node_modules). */\nasync function createTarball(dir: string): Promise<Buffer> {\n const tmp = await mkdtemp(join(tmpdir(), 'mastra-sandbox-'));\n const tarPath = join(tmp, 'deploy.tgz');\n try {\n await execFileAsync('tar', ['-czf', tarPath, '--exclude=node_modules', '-C', dir, '.']);\n return await readFile(tarPath);\n } finally {\n await rm(tmp, { recursive: true, force: true });\n }\n}\n\n/**\n * Upload a file into the sandbox. Uses the provider's native `writeFiles` fast\n * path when available, otherwise falls back to base64 chunks over\n * `executeCommand` — so `executeCommand` + `networking` is the minimum contract.\n */\nasync function uploadFile(sandbox: WorkspaceSandbox, remotePath: string, content: Buffer): Promise<void> {\n if (sandbox.writeFiles) {\n await sandbox.writeFiles([{ path: remotePath, content }]);\n return;\n }\n\n const b64 = content.toString('base64');\n const tmpPath = `${remotePath}.b64`;\n await runInSandbox(sandbox, `rm -f ${shellQuote(tmpPath)}`);\n for (let i = 0; i < b64.length; i += UPLOAD_CHUNK_SIZE) {\n const chunk = b64.slice(i, i + UPLOAD_CHUNK_SIZE);\n await runInSandbox(sandbox, `printf '%s' ${shellQuote(chunk)} >> ${shellQuote(tmpPath)}`, {\n label: `upload chunk to ${remotePath}`,\n });\n }\n await runInSandbox(\n sandbox,\n `base64 -d ${shellQuote(tmpPath)} > ${shellQuote(remotePath)} && rm -f ${shellQuote(tmpPath)}`,\n { label: `decode upload at ${remotePath}` },\n );\n}\n\n/** Lockfiles that, when present in the build output, participate in the install-skip hash. */\nconst LOCKFILES = ['package-lock.json', 'npm-shrinkwrap.json', 'pnpm-lock.yaml', 'yarn.lock', 'bun.lock'];\n\n/**\n * Hash everything that determines the outcome of a dependency install:\n * package.json, any bundled lockfile, and the install command itself. A\n * matching hash means the previous `node_modules` can be reused.\n */\nasync function hashInstallInputs(dir: string, installCommand: string): Promise<string | null> {\n const hash = createHash('sha256');\n try {\n hash.update(await readFile(join(dir, 'package.json')));\n } catch {\n return null;\n }\n for (const lockfile of LOCKFILES) {\n let content: Buffer;\n try {\n content = await readFile(join(dir, lockfile));\n } catch {\n // Lockfile not part of the build output.\n continue;\n }\n hash.update(lockfile).update(content);\n }\n hash.update(installCommand);\n return hash.digest('hex');\n}\n","import { readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { SandboxDeploymentManifest } from './types';\n\nexport const MANIFEST_FILENAME = 'sandbox-deployment.json';\n\n/** Write `sandbox-deployment.json` into the build output directory. */\nexport async function writeDeploymentManifest(outputDir: string, manifest: SandboxDeploymentManifest): Promise<void> {\n await writeFile(join(outputDir, MANIFEST_FILENAME), JSON.stringify(manifest, null, 2));\n}\n\n/** Read `sandbox-deployment.json` from the build output directory, or null when absent. */\nexport async function readDeploymentManifest(outputDir: string): Promise<SandboxDeploymentManifest | null> {\n let raw: string;\n try {\n raw = await readFile(join(outputDir, MANIFEST_FILENAME), 'utf-8');\n } catch (error) {\n // Only \"no manifest\" maps to null — anything else (permissions, a\n // corrupted file, malformed JSON below) should surface, not be hidden.\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return null;\n }\n throw error;\n }\n return JSON.parse(raw) as SandboxDeploymentManifest;\n}\n","import { access } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { Config } from '@mastra/core/mastra';\nimport type { WorkspaceSandbox } from '@mastra/core/workspace';\nimport { Deployer } from '@mastra/deployer';\nimport { copy } from 'fs-extra/esm';\nimport { updateEdgeConfigAlias } from './alias';\nimport { deployToSandbox } from './engine';\nimport { writeDeploymentManifest } from './manifest';\nimport { DEFAULT_PORT } from './shared';\nimport type { SandboxDeployerOptions } from './types';\n\n/**\n * Deploy a full Mastra server into any workspace sandbox that supports\n * networking (Vercel Sandbox, E2B, ...) and get a live public URL.\n *\n * Positioning: ephemeral environments — instant previews, PR/CI smoke deploys,\n * agent-built-app verification. Not production hosting.\n *\n * @example\n * ```typescript\n * import { SandboxDeployer } from '@mastra/deployer-sandbox';\n * import { VercelSandbox } from '@mastra/vercel';\n *\n * export const mastra = new Mastra({\n * deployer: new SandboxDeployer({\n * sandbox: new VercelSandbox({ sandboxName: 'my-preview', timeout: 3_600_000, ports: [4111] }),\n * }),\n * });\n * ```\n */\nexport class SandboxDeployer extends Deployer {\n /** Sandbox deploys are push-style: `mastra build` runs `deploy()` after bundling. */\n readonly deployOnBuild = true;\n readonly sandbox: WorkspaceSandbox;\n readonly port: number;\n readonly studio: boolean;\n /** Explicit remote dir, when configured. The engine defaults to `$HOME/mastra-app` inside the sandbox. */\n readonly remoteDir?: string;\n private readonly env: Record<string, string>;\n private readonly alias?: SandboxDeployerOptions['alias'];\n private readonly healthCheckTimeoutMs?: number;\n\n constructor(options: SandboxDeployerOptions) {\n super({ name: 'SANDBOX' });\n\n this.sandbox = options.sandbox;\n this.port = options.port ?? DEFAULT_PORT;\n this.studio = options.studio ?? true;\n this.remoteDir = options.remoteDir;\n this.env = options.env ?? {};\n this.alias = options.alias;\n this.healthCheckTimeoutMs = options.healthCheckTimeoutMs;\n }\n\n /**\n * Merge all existing env files instead of only the first one (base behavior).\n * Later files win in `loadEnvVars()`, so order least → most specific: a\n * `.env.local` written by `vercel env pull` shouldn't shadow the `.env` that\n * holds the app's own keys.\n */\n override async getEnvFiles(): Promise<string[]> {\n const candidates = ['.env', '.env.production', '.env.local'];\n const existing: string[] = [];\n for (const file of candidates) {\n try {\n await access(file);\n existing.push(file);\n } catch {\n // skip missing files\n }\n }\n return existing;\n }\n\n protected async getUserBundlerOptions(\n mastraEntryFile: string,\n outputDirectory: string,\n ): Promise<NonNullable<Config['bundler']>> {\n const bundlerOptions = await super.getUserBundlerOptions(mastraEntryFile, outputDirectory);\n\n // Dependencies are installed inside the sandbox, so keep them external.\n return {\n ...bundlerOptions,\n externals: true,\n };\n }\n\n protected getEntry(): string {\n return `\n // @ts-expect-error\n import { scoreTracesWorkflow } from '@mastra/core/evals/scoreTraces';\n import { mastra } from '#mastra';\n import { createNodeServer, getToolExports } from '#server';\n import { tools } from '#tools';\n\n // @ts-expect-error\n await createNodeServer(mastra, { tools: getToolExports(tools), studio: ${this.studio} });\n\n const storage = mastra.getStorage();\n if (storage) {\n if (!storage.disableInit) {\n storage.init();\n }\n mastra.__registerInternalWorkflow(scoreTracesWorkflow);\n }\n `;\n }\n\n async prepare(outputDirectory: string): Promise<void> {\n await super.prepare(outputDirectory);\n\n if (this.studio) {\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = dirname(__filename);\n\n const studioSource = join(dirname(__dirname), 'dist', 'studio');\n const studioServePath = join(outputDirectory, this.outputDir, 'studio');\n\n try {\n await copy(studioSource, studioServePath, { overwrite: true });\n } catch (err) {\n throw new Error(\n `Failed to copy studio assets from \"${studioSource}\" to \"${studioServePath}\": ${err instanceof Error ? err.message : err}`,\n );\n }\n }\n }\n\n async bundle(\n entryFile: string,\n outputDirectory: string,\n { toolsPaths, projectRoot }: { toolsPaths: (string | string[])[]; projectRoot: string },\n ): Promise<void> {\n return this._bundle(this.getEntry(), entryFile, { outputDirectory, projectRoot }, toolsPaths);\n }\n\n /**\n * Deploy the built output into the sandbox and wait for the server to come\n * up on its public URL. Writes `sandbox-deployment.json` into the output\n * directory and updates the Edge Config alias when configured.\n */\n async deploy(outputDirectory: string): Promise<void> {\n const dir = join(outputDirectory, this.outputDir);\n\n // Merge .env file vars under explicitly configured env.\n const envVars = await this.loadEnvVars();\n const env: Record<string, string> = { ...Object.fromEntries(envVars), ...this.env };\n if (envVars.size > 0) {\n this.logger.warn(\n 'Environment variables from your .env file are injected into the remote sandbox. ' +\n 'Anyone with access to the sandbox can read them.',\n );\n }\n\n const deployment = await deployToSandbox({\n sandbox: this.sandbox,\n dir,\n port: this.port,\n env,\n studio: this.studio,\n remoteDir: this.remoteDir,\n healthCheckTimeoutMs: this.healthCheckTimeoutMs,\n logger: this.logger,\n });\n\n await writeDeploymentManifest(dir, {\n provider: this.sandbox.provider,\n sandboxId: deployment.sandboxId,\n url: deployment.url,\n port: this.port,\n deployedAt: new Date().toISOString(),\n expiresAt: deployment.expiresAt?.toISOString(),\n });\n\n if (this.alias) {\n await updateEdgeConfigAlias({ ...this.alias, url: deployment.url });\n this.logger.info(`Edge Config alias \"${this.alias.key}\" now points at ${deployment.url}`);\n }\n\n this.logger.info(`Mastra server deployed: ${deployment.url}/api`);\n if (this.studio) {\n this.logger.info(`Studio: ${deployment.url}`);\n }\n if (deployment.expiresAt) {\n this.logger.warn(`Sandbox expires at ${deployment.expiresAt.toISOString()} (provider runtime cap).`);\n }\n }\n}\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K,2BAA2B,WAAW,IAAI,KAAK;EAChE,IAAI,KAAK,QACP,KAAK,OAAO,KAAK,WAAW,WAAW,KAAK;EAE9C,IAAI,WAAW,WACb,KAAK,OAAO,KAAK,sBAAsB,WAAW,UAAU,YAAY,EAAE,yBAAyB;CAEvG;AACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["execFile","DEFAULT_PORT","resolveRemoteDir","runInSandbox","shellQuote","killPreviousServer","INSTALL_MARKER","SERVER_SCRIPT","launchServer","waitForHealthy","tailServerLog","getInfoSafe","SERVER_PIDFILE","SERVER_LOGFILE","Deployer","resolveRemoteDir","runInSandbox","shellQuote","posix","getInfoSafe","path"],"sources":["../src/alias.ts","../src/engine.ts","../src/manifest.ts","../src/deployer.ts","../src/worker.ts"],"sourcesContent":["import type { SandboxAliasOptions } from './types';\n\n/**\n * Upsert a Vercel Edge Config item so a stable key always points at the\n * current sandbox URL. Used for Tier 3 routing: apps read the key from Edge\n * Config (e.g. in middleware) instead of hardcoding the rotating sandbox URL.\n */\nexport async function updateEdgeConfigAlias(options: SandboxAliasOptions & { url: string }): Promise<void> {\n const { token, teamId } = options;\n if (!token) {\n throw new Error('Updating the Edge Config alias requires a Vercel API token. Pass `alias.token`.');\n }\n\n const endpoint = new URL(`https://api.vercel.com/v1/edge-config/${options.edgeConfigId}/items`);\n if (teamId) {\n endpoint.searchParams.set('teamId', teamId);\n }\n\n const res = await fetch(endpoint, {\n method: 'PATCH',\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n items: [{ operation: 'upsert', key: options.key, value: options.url }],\n }),\n // Bounded so a hung Vercel API request can't keep `mastra build` open\n // after the sandbox itself is already deployed.\n signal: AbortSignal.timeout(30_000),\n });\n\n if (!res.ok) {\n const body = await res.text().catch(() => '');\n throw new Error(`Failed to update Edge Config alias \"${options.key}\" (${res.status}): ${body}`);\n }\n}\n","import { execFile } from 'node:child_process';\nimport { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { mkdtemp, readFile, rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { promisify } from 'node:util';\nimport { supportsNetworking } from '@mastra/core/workspace';\nimport type { WorkspaceSandbox } from '@mastra/core/workspace';\nimport {\n DEFAULT_PORT,\n INSTALL_MARKER,\n SERVER_LOGFILE,\n SERVER_PIDFILE,\n SERVER_SCRIPT,\n getInfoSafe,\n killPreviousServer,\n launchServer,\n resolveRemoteDir,\n runInSandbox,\n shellQuote,\n tailServerLog,\n waitForHealthy,\n} from './shared';\nimport type { DeployToSandboxOptions, SandboxDeployLogger, SandboxDeployment } from './types';\n\nconst execFileAsync = promisify(execFile);\n\nconst noopLogger: SandboxDeployLogger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n};\n\n/** Max shell-command payload per chunk for the base64 upload fallback. */\nconst UPLOAD_CHUNK_SIZE = 96_000;\n\n/**\n * Deploy a prebuilt Mastra server directory into any workspace sandbox that\n * supports networking. Provider-agnostic: only uses the core WorkspaceSandbox\n * contract (`executeCommand` + `networking`, with `writeFiles` / `processes`\n * as fast paths).\n */\nexport async function deployToSandbox(options: DeployToSandboxOptions): Promise<SandboxDeployment> {\n const {\n sandbox,\n dir,\n port = DEFAULT_PORT,\n env = {},\n studio = false,\n healthCheckPath = '/api',\n healthCheckTimeoutMs = 60_000,\n healthCheckIntervalMs = 1_000,\n installCommand = 'npm install --omit=dev',\n logger = noopLogger,\n } = options;\n\n if (!existsSync(join(dir, 'index.mjs'))) {\n throw new Error(`No index.mjs found in \"${dir}\" — did the build succeed?`);\n }\n\n // 1. Start (providers handle create-or-resume by identity, e.g. sandbox name).\n logger.info(`Starting ${sandbox.provider} sandbox...`);\n await sandbox.start?.();\n\n if (!supportsNetworking(sandbox)) {\n throw new Error(\n `Sandbox provider \"${sandbox.provider}\" does not support networking (public port URLs), ` +\n `which is required for sandbox deploys.`,\n );\n }\n if (!sandbox.executeCommand) {\n throw new Error(\n `Sandbox provider \"${sandbox.provider}\" does not support executeCommand, which is required for sandbox deploys.`,\n );\n }\n\n const url = await sandbox.networking.getPortUrl(port);\n if (!url) {\n throw new Error(\n `Sandbox provider \"${sandbox.provider}\" did not expose a public URL for port ${port}. ` +\n `Make sure the port is declared when constructing the sandbox (e.g. \\`ports: [${port}]\\`).`,\n );\n }\n\n // Default the remote dir to $HOME/mastra-app — home directories persist\n // across snapshot stop/resume (unlike /tmp), so wakes find the app intact.\n const remoteDir = await resolveRemoteDir(sandbox, options.remoteDir);\n\n const mergedEnv = { ...env };\n if (studio && mergedEnv.MASTRA_STUDIO_PATH === undefined) {\n mergedEnv.MASTRA_STUDIO_PATH = `${remoteDir}/studio`;\n }\n\n // 2. Upload the build output as a tarball and extract it in the sandbox.\n logger.info(`Uploading build output from ${dir}...`);\n const tarball = await createTarball(dir);\n logger.debug(`Tarball size: ${(tarball.length / 1024 / 1024).toFixed(2)} MB`);\n\n const remoteTarball = `${remoteDir}/.deploy.tgz`;\n await runInSandbox(sandbox, `mkdir -p ${shellQuote(remoteDir)}`);\n await uploadFile(sandbox, remoteTarball, tarball);\n\n // Stop the previous server BEFORE extracting over the live directory so it\n // can never serve a mix of old and new files while the release lands.\n await killPreviousServer(sandbox, remoteDir);\n\n await runInSandbox(sandbox, `cd ${shellQuote(remoteDir)} && tar -xzf .deploy.tgz && rm -f .deploy.tgz`, {\n timeout: 120_000,\n });\n\n // 3. Install dependencies, skipped when the install inputs (package.json,\n // bundled lockfiles, and the install command itself) are unchanged since\n // the last completed install.\n const installHash = await hashInstallInputs(dir, installCommand);\n const marker = `${remoteDir}/${INSTALL_MARKER}`;\n const markerCheck = await runInSandbox(sandbox, `cat ${shellQuote(marker)} 2>/dev/null || true`, {\n allowFailure: true,\n });\n\n if (installHash && markerCheck.stdout.trim() === installHash) {\n logger.info('Dependencies unchanged — skipping install.');\n } else {\n logger.info(`Installing dependencies (${installCommand})...`);\n await runInSandbox(sandbox, `cd ${shellQuote(remoteDir)} && ${installCommand}`, {\n timeout: 600_000,\n label: `install dependencies (${installCommand})`,\n });\n if (installHash) {\n await runInSandbox(sandbox, `printf '%s' ${shellQuote(installHash)} > ${shellQuote(marker)}`);\n }\n }\n\n // 4. Write the launch script and start the new server (the previous one was\n // stopped before extraction).\n const launchScript = buildLaunchScript({ remoteDir, port, env: mergedEnv });\n await uploadFile(sandbox, `${remoteDir}/${SERVER_SCRIPT}`, Buffer.from(launchScript));\n await runInSandbox(sandbox, `chmod 700 ${shellQuote(`${remoteDir}/${SERVER_SCRIPT}`)}`);\n\n logger.info('Starting Mastra server...');\n await launchServer(sandbox, remoteDir);\n\n // 5. Wait for the server to answer on its public URL.\n const healthy = await waitForHealthy(url, {\n path: healthCheckPath,\n timeoutMs: healthCheckTimeoutMs,\n intervalMs: healthCheckIntervalMs,\n });\n if (!healthy) {\n const log = await tailServerLog(sandbox, remoteDir).catch(() => '');\n throw new Error(\n `Mastra server did not become healthy at ${url}${healthCheckPath} within ${healthCheckTimeoutMs}ms.` +\n (log ? `\\n\\nServer log:\\n${log}` : '\\n\\n(no server log output captured)'),\n );\n }\n\n const info = await getInfoSafe(sandbox);\n\n return {\n url,\n sandboxId: info?.id ?? sandbox.id,\n expiresAt: info?.timeoutAt,\n stop: async () => {\n await sandbox.stop?.();\n },\n destroy: async () => {\n await sandbox.destroy?.();\n },\n logs: (lines?: number) => tailServerLog(sandbox, remoteDir, lines),\n };\n}\n\n/**\n * Build the POSIX launch script. Re-running the script restarts the server —\n * the wake path uses this after a snapshot resume (which restores the\n * filesystem but not processes).\n */\nexport function buildLaunchScript(opts: { remoteDir: string; port: number; env: Record<string, string> }): string {\n const lines = ['#!/bin/sh', `cd ${shellQuote(opts.remoteDir)}`];\n\n // MASTRA_AUTO_DETECT_URL so Studio connects to the sandbox's public URL\n // (same origin) instead of localhost:4111 — overridable. PORT and\n // MASTRA_HOST are applied AFTER custom env: networking (`getPortUrl`) and\n // health checks target the configured port, and the server must bind\n // 0.0.0.0 to be reachable through the public port proxy. Change the port\n // via the deploy `port` option, not env.\n const env: Record<string, string> = {\n MASTRA_AUTO_DETECT_URL: 'true',\n ...opts.env,\n PORT: String(opts.port),\n MASTRA_HOST: '0.0.0.0',\n };\n for (const [key, value] of Object.entries(env)) {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) {\n throw new Error(`Invalid environment variable name: \"${key}\"`);\n }\n lines.push(`export ${key}=${shellQuote(value)}`);\n }\n\n lines.push(`echo $$ > ${shellQuote(SERVER_PIDFILE)}`);\n lines.push(`exec node index.mjs >> ${shellQuote(SERVER_LOGFILE)} 2>&1`);\n return lines.join('\\n') + '\\n';\n}\n\n/** Create a gzipped tarball of the directory contents (excluding node_modules). */\nexport async function createTarball(dir: string): Promise<Buffer> {\n const tmp = await mkdtemp(join(tmpdir(), 'mastra-sandbox-'));\n const tarPath = join(tmp, 'deploy.tgz');\n try {\n await execFileAsync('tar', ['-czf', tarPath, '--exclude=node_modules', '-C', dir, '.']);\n return await readFile(tarPath);\n } finally {\n await rm(tmp, { recursive: true, force: true });\n }\n}\n\n/**\n * Upload a file into the sandbox. Uses the provider's native `writeFiles` fast\n * path when available, otherwise falls back to base64 chunks over\n * `executeCommand` — so `executeCommand` + `networking` is the minimum contract.\n */\nexport async function uploadFile(sandbox: WorkspaceSandbox, remotePath: string, content: Buffer): Promise<void> {\n if (sandbox.writeFiles) {\n await sandbox.writeFiles([{ path: remotePath, content }]);\n return;\n }\n\n const b64 = content.toString('base64');\n const tmpPath = `${remotePath}.b64`;\n await runInSandbox(sandbox, `rm -f ${shellQuote(tmpPath)}`);\n for (let i = 0; i < b64.length; i += UPLOAD_CHUNK_SIZE) {\n const chunk = b64.slice(i, i + UPLOAD_CHUNK_SIZE);\n await runInSandbox(sandbox, `printf '%s' ${shellQuote(chunk)} >> ${shellQuote(tmpPath)}`, {\n label: `upload chunk to ${remotePath}`,\n });\n }\n await runInSandbox(\n sandbox,\n `base64 -d ${shellQuote(tmpPath)} > ${shellQuote(remotePath)} && rm -f ${shellQuote(tmpPath)}`,\n { label: `decode upload at ${remotePath}` },\n );\n}\n\n/** Lockfiles that, when present in the build output, participate in the install-skip hash. */\nconst LOCKFILES = ['package-lock.json', 'npm-shrinkwrap.json', 'pnpm-lock.yaml', 'yarn.lock', 'bun.lock'];\n\n/**\n * Hash everything that determines the outcome of a dependency install:\n * package.json, any bundled lockfile, and the install command itself. A\n * matching hash means the previous `node_modules` can be reused.\n */\nexport async function hashInstallInputs(dir: string, installCommand: string): Promise<string | null> {\n const hash = createHash('sha256');\n try {\n hash.update(await readFile(join(dir, 'package.json')));\n } catch {\n return null;\n }\n for (const lockfile of LOCKFILES) {\n let content: Buffer;\n try {\n content = await readFile(join(dir, lockfile));\n } catch {\n // Lockfile not part of the build output.\n continue;\n }\n hash.update(lockfile).update(content);\n }\n hash.update(installCommand);\n return hash.digest('hex');\n}\n","import { readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { SandboxDeploymentManifest } from './types';\n\nexport const MANIFEST_FILENAME = 'sandbox-deployment.json';\n\n/** Write `sandbox-deployment.json` into the build output directory. */\nexport async function writeDeploymentManifest(outputDir: string, manifest: SandboxDeploymentManifest): Promise<void> {\n await writeFile(join(outputDir, MANIFEST_FILENAME), JSON.stringify(manifest, null, 2));\n}\n\n/** Read `sandbox-deployment.json` from the build output directory, or null when absent. */\nexport async function readDeploymentManifest(outputDir: string): Promise<SandboxDeploymentManifest | null> {\n let raw: string;\n try {\n raw = await readFile(join(outputDir, MANIFEST_FILENAME), 'utf-8');\n } catch (error) {\n // Only \"no manifest\" maps to null — anything else (permissions, a\n // corrupted file, malformed JSON below) should surface, not be hidden.\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return null;\n }\n throw error;\n }\n return JSON.parse(raw) as SandboxDeploymentManifest;\n}\n","import { access } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { Config } from '@mastra/core/mastra';\nimport type { WorkspaceSandbox } from '@mastra/core/workspace';\nimport { Deployer } from '@mastra/deployer';\nimport { copy } from 'fs-extra/esm';\nimport { updateEdgeConfigAlias } from './alias';\nimport { deployToSandbox } from './engine';\nimport { writeDeploymentManifest } from './manifest';\nimport { DEFAULT_PORT } from './shared';\nimport type { SandboxDeployerOptions } from './types';\n\n/**\n * Deploy a full Mastra server into any workspace sandbox that supports\n * networking (Vercel Sandbox, E2B, ...) and get a live public URL.\n *\n * Positioning: ephemeral environments — instant previews, PR/CI smoke deploys,\n * agent-built-app verification. Not production hosting.\n *\n * @example\n * ```typescript\n * import { SandboxDeployer } from '@mastra/deployer-sandbox';\n * import { VercelSandbox } from '@mastra/vercel';\n *\n * export const mastra = new Mastra({\n * deployer: new SandboxDeployer({\n * sandbox: new VercelSandbox({ sandboxName: 'my-preview', timeout: 3_600_000, ports: [4111] }),\n * }),\n * });\n * ```\n */\nexport class SandboxDeployer extends Deployer {\n /** Sandbox deploys are push-style: `mastra build` runs `deploy()` after bundling. */\n readonly deployOnBuild = true;\n readonly sandbox: WorkspaceSandbox;\n readonly port: number;\n readonly studio: boolean;\n /** Explicit remote dir, when configured. The engine defaults to `$HOME/mastra-app` inside the sandbox. */\n readonly remoteDir?: string;\n private readonly env: Record<string, string>;\n private readonly alias?: SandboxDeployerOptions['alias'];\n private readonly healthCheckTimeoutMs?: number;\n\n constructor(options: SandboxDeployerOptions) {\n super({ name: 'SANDBOX' });\n\n this.sandbox = options.sandbox;\n this.port = options.port ?? DEFAULT_PORT;\n this.studio = options.studio ?? true;\n this.remoteDir = options.remoteDir;\n this.env = options.env ?? {};\n this.alias = options.alias;\n this.healthCheckTimeoutMs = options.healthCheckTimeoutMs;\n }\n\n /**\n * Merge all existing env files instead of only the first one (base behavior).\n * Later files win in `loadEnvVars()`, so order least → most specific: a\n * `.env.local` written by `vercel env pull` shouldn't shadow the `.env` that\n * holds the app's own keys.\n */\n override async getEnvFiles(): Promise<string[]> {\n const candidates = ['.env', '.env.production', '.env.local'];\n const existing: string[] = [];\n for (const file of candidates) {\n try {\n await access(file);\n existing.push(file);\n } catch {\n // skip missing files\n }\n }\n return existing;\n }\n\n protected async getUserBundlerOptions(\n mastraEntryFile: string,\n outputDirectory: string,\n ): Promise<NonNullable<Config['bundler']>> {\n const bundlerOptions = await super.getUserBundlerOptions(mastraEntryFile, outputDirectory);\n\n // Dependencies are installed inside the sandbox, so keep them external.\n return {\n ...bundlerOptions,\n externals: true,\n };\n }\n\n protected getEntry(): string {\n return `\n // @ts-expect-error\n import { scoreTracesWorkflow } from '@mastra/core/evals/scoreTraces';\n import { mastra } from '#mastra';\n import { createNodeServer, getToolExports } from '#server';\n import { tools } from '#tools';\n\n // @ts-expect-error\n await createNodeServer(mastra, { tools: getToolExports(tools), studio: ${this.studio} });\n\n const storage = mastra.getStorage();\n if (storage) {\n if (!storage.disableInit) {\n storage.init();\n }\n mastra.__registerInternalWorkflow(scoreTracesWorkflow);\n }\n `;\n }\n\n async prepare(outputDirectory: string): Promise<void> {\n await super.prepare(outputDirectory);\n\n if (this.studio) {\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = dirname(__filename);\n\n const studioSource = join(dirname(__dirname), 'dist', 'studio');\n const studioServePath = join(outputDirectory, this.outputDir, 'studio');\n\n try {\n await copy(studioSource, studioServePath, { overwrite: true });\n } catch (err) {\n throw new Error(\n `Failed to copy studio assets from \"${studioSource}\" to \"${studioServePath}\": ${err instanceof Error ? err.message : err}`,\n );\n }\n }\n }\n\n async bundle(\n entryFile: string,\n outputDirectory: string,\n { toolsPaths, projectRoot }: { toolsPaths: (string | string[])[]; projectRoot: string },\n ): Promise<void> {\n return this._bundle(this.getEntry(), entryFile, { outputDirectory, projectRoot }, toolsPaths);\n }\n\n /**\n * Deploy the built output into the sandbox and wait for the server to come\n * up on its public URL. Writes `sandbox-deployment.json` into the output\n * directory and updates the Edge Config alias when configured.\n */\n async deploy(outputDirectory: string): Promise<void> {\n const dir = join(outputDirectory, this.outputDir);\n\n // Merge .env file vars under explicitly configured env.\n const envVars = await this.loadEnvVars();\n const env: Record<string, string> = { ...Object.fromEntries(envVars), ...this.env };\n if (envVars.size > 0) {\n this.logger.warn(\n 'Environment variables from your .env file are injected into the remote sandbox. ' +\n 'Anyone with access to the sandbox can read them.',\n );\n }\n\n const deployment = await deployToSandbox({\n sandbox: this.sandbox,\n dir,\n port: this.port,\n env,\n studio: this.studio,\n remoteDir: this.remoteDir,\n healthCheckTimeoutMs: this.healthCheckTimeoutMs,\n logger: this.logger,\n });\n\n await writeDeploymentManifest(dir, {\n provider: this.sandbox.provider,\n sandboxId: deployment.sandboxId,\n url: deployment.url,\n port: this.port,\n deployedAt: new Date().toISOString(),\n expiresAt: deployment.expiresAt?.toISOString(),\n });\n\n if (this.alias) {\n await updateEdgeConfigAlias({ ...this.alias, url: deployment.url });\n this.logger.info(`Edge Config alias \"${this.alias.key}\" now points at ${deployment.url}`);\n }\n\n this.logger.info(`Mastra server deployed: ${deployment.url}/api`);\n if (this.studio) {\n this.logger.info(`Studio: ${deployment.url}`);\n }\n if (deployment.expiresAt) {\n this.logger.warn(`Sandbox expires at ${deployment.expiresAt.toISOString()} (provider runtime cap).`);\n }\n }\n}\n","import { posix } from 'node:path';\n\nimport type { WorkspaceSandbox } from '@mastra/core/workspace';\n\nimport { createTarball, hashInstallInputs, uploadFile } from './engine.js';\nimport { getInfoSafe, resolveRemoteDir, runInSandbox, shellQuote } from './shared.js';\nimport type {\n DeployWorkerToSandboxOptions,\n SandboxDestroyResult,\n SandboxWorkerDeployment,\n SandboxWorkerInput,\n SandboxWorkerOutput,\n SandboxWorkerStatus,\n} from './types.js';\n\nconst ARCHIVE = '.mastra-worker.tar.gz';\nconst RUNTIME_DIR = '.mastra/executions';\nconst INSTALL_MARKER = '.mastra-install-hash';\nconst INSTALL_LOCK = '.mastra-install-lock';\nconst ARTIFACT_LOCK = '.mastra-artifact-lock';\nconst EXECUTION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;\nconst DEFAULT_INPUT_LIMIT = 16 * 1024 * 1024;\nconst DEFAULT_OUTPUT_READ_LIMIT = 1024 * 1024;\n\ninterface WorkerConfig {\n sandbox: WorkspaceSandbox;\n remoteDir: string;\n command: string;\n args: string[];\n env: Record<string, string>;\n workingDirectory: string;\n mode: 'worker' | 'job';\n startupTimeoutMs: number;\n executionTimeoutMs?: number;\n terminationGraceMs: number;\n inputLimitBytes: number;\n}\n\nexport async function deployWorkerToSandbox(options: DeployWorkerToSandboxOptions): Promise<SandboxWorkerDeployment> {\n validateOptions(options);\n const {\n sandbox,\n dir,\n executionId,\n command,\n mode = 'worker',\n args = [],\n env = {},\n workingDirectory = '.',\n installCommand = 'npm install --omit=dev',\n startupTimeoutMs = 10_000,\n executionTimeoutMs,\n terminationGraceMs = 5_000,\n inputLimitBytes = DEFAULT_INPUT_LIMIT,\n } = options;\n\n const remoteDir = await resolveRemoteDir(sandbox, options.remoteDir);\n const config: WorkerConfig = {\n sandbox,\n remoteDir,\n command,\n args,\n env,\n workingDirectory,\n mode,\n startupTimeoutMs,\n executionTimeoutMs,\n terminationGraceMs,\n inputLimitBytes,\n };\n\n const archive = `${remoteDir}/${ARCHIVE}`;\n const tarball = await createTarball(dir);\n const installHash = await hashInstallInputs(dir, installCommand);\n\n const artifactLock = `${remoteDir}/${ARTIFACT_LOCK}`;\n let artifactLockAcquired = false;\n try {\n await runInSandbox(sandbox, `mkdir -p ${shellQuote(remoteDir)}`);\n await acquireLock(sandbox, artifactLock, options.installTimeoutMs, 'worker artifact');\n artifactLockAcquired = true;\n await uploadFile(sandbox, archive, tarball);\n await runInSandbox(\n sandbox,\n `tar -xzf ${shellQuote(archive)} -C ${shellQuote(remoteDir)} && rm -f ${shellQuote(archive)}`,\n { label: 'extract worker artifact' },\n );\n } catch (error) {\n throw workerPhaseError('upload', error);\n } finally {\n if (artifactLockAcquired) {\n await runInSandbox(sandbox, `rm -rf ${shellQuote(artifactLock)}`, {\n allowFailure: true,\n label: 'release worker artifact lock',\n });\n }\n }\n\n try {\n await installDependencies(sandbox, remoteDir, installHash ?? undefined, installCommand, options.installTimeoutMs);\n } catch (error) {\n throw workerPhaseError('install', error);\n }\n\n return createExecution(config, executionId, options.input);\n}\n\nfunction validateOptions(options: DeployWorkerToSandboxOptions): void {\n if (!options.sandbox.executeCommand) {\n throw new Error(\n `Sandbox provider \"${options.sandbox.provider}\" does not support executeCommand, which is required for worker deploys.`,\n );\n }\n validateExecutionId(options.executionId);\n if (!options.command || /[\\0\\r\\n]/.test(options.command)) {\n throw new Error('Worker command must be a non-empty executable path.');\n }\n if (options.args?.some(arg => arg.includes('\\0'))) throw new Error('Worker arguments must not contain NUL bytes.');\n for (const key of Object.keys(options.env ?? {})) {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) throw new Error(`Invalid worker environment variable name: ${key}`);\n }\n validateRelativePath(options.workingDirectory ?? '.', 'workingDirectory');\n validateInput(options.input);\n for (const [name, value] of [\n ['inputLimitBytes', options.inputLimitBytes],\n ['startupTimeoutMs', options.startupTimeoutMs],\n ['executionTimeoutMs', options.executionTimeoutMs],\n ['terminationGraceMs', options.terminationGraceMs],\n ] as const) {\n if (value !== undefined && (!Number.isFinite(value) || value <= 0))\n throw new Error(`${name} must be greater than zero.`);\n }\n}\n\nfunction validateRelativePath(value: string, label: string): void {\n if (!value || posix.isAbsolute(value) || posix.normalize(value).startsWith('..')) {\n throw new Error(`Worker ${label} must stay within the deployed artifact root.`);\n }\n}\n\nfunction validateInput(input: SandboxWorkerInput | undefined): void {\n if (input?.type === 'file') validateRelativePath(input.path, 'input file path');\n}\n\nasync function acquireLock(\n sandbox: WorkspaceSandbox,\n lock: string,\n timeout: number | undefined,\n label: string,\n): Promise<void> {\n const timeoutMs = timeout ?? 600_000;\n const attempts = Math.max(1, Math.ceil(timeoutMs / 1000));\n await runInSandbox(\n sandbox,\n [\n 'i=0',\n `while ! mkdir ${shellQuote(lock)} 2>/dev/null; do`,\n ` if [ \"$i\" -ge ${attempts} ]; then echo ${shellQuote(`${label} lock timeout`)} >&2; exit 1; fi`,\n ' sleep 1; i=$((i + 1))',\n 'done',\n ].join('\\n'),\n { timeout: timeoutMs, label: `acquire ${label} lock` },\n );\n}\n\nasync function installDependencies(\n sandbox: WorkspaceSandbox,\n remoteDir: string,\n installHash: string | undefined,\n installCommand: string,\n timeout?: number,\n): Promise<void> {\n if (!installHash) return;\n const marker = `${remoteDir}/${INSTALL_MARKER}`;\n const lock = `${remoteDir}/${INSTALL_LOCK}`;\n await acquireLock(sandbox, lock, timeout, 'dependency install');\n try {\n const script = [\n `current=\"$(cat ${shellQuote(marker)} 2>/dev/null || true)\"`,\n `if [ \"$current\" != ${shellQuote(installHash)} ]; then`,\n ` cd ${shellQuote(remoteDir)} && ${installCommand}`,\n ` printf %s ${shellQuote(installHash)} > ${shellQuote(`${marker}.tmp`)}`,\n ` mv ${shellQuote(`${marker}.tmp`)} ${shellQuote(marker)}`,\n 'fi',\n ].join('\\n');\n await runInSandbox(sandbox, script, {\n timeout: timeout ?? 600_000,\n label: 'install worker dependencies',\n });\n } finally {\n await runInSandbox(sandbox, `rm -rf ${shellQuote(lock)}`, {\n allowFailure: true,\n label: 'release dependency install lock',\n });\n }\n}\n\nasync function createExecution(\n config: WorkerConfig,\n executionId: string,\n input?: SandboxWorkerInput,\n): Promise<SandboxWorkerDeployment> {\n validateExecutionId(executionId);\n const paths = executionPaths(config.remoteDir, executionId);\n await runInSandbox(\n config.sandbox,\n `mkdir -p ${shellQuote(`${config.remoteDir}/${RUNTIME_DIR}`)} && mkdir -m 700 ${shellQuote(paths.dir)}`,\n { label: 'create worker execution namespace' },\n );\n const stdinPath = await stageInput(config, paths, input);\n const script = buildExecutionScript(config, paths, stdinPath);\n await uploadFile(config.sandbox, paths.script, Buffer.from(script));\n await runInSandbox(config.sandbox, `chmod 700 ${shellQuote(paths.script)}`);\n\n try {\n await launchExecution(config.sandbox, paths);\n } catch (error) {\n await writeFailedStatus(config.sandbox, paths, executionId, 'launch', error);\n throw workerPhaseError('launch', error);\n }\n\n const startup = await waitForStartup(config, executionId, paths);\n if (startup.state === 'timed_out') await cancelExecution(config, executionId, paths, 'startup');\n if (startup.state === 'failed' || startup.state === 'timed_out' || startup.state === 'provider_unavailable') {\n throw new Error(\n `Worker ${startup.state} during startup${'message' in startup && startup.message ? `: ${startup.message}` : ''}.`,\n );\n }\n\n const info = await getInfoSafe(config.sandbox);\n return deployment(config, executionId, paths, info?.id ?? config.sandbox.id ?? 'unknown', info?.timeoutAt);\n}\n\nfunction deployment(\n config: WorkerConfig,\n executionId: string,\n paths: ReturnType<typeof executionPaths>,\n sandboxId: string,\n expiresAt?: Date,\n): SandboxWorkerDeployment {\n return {\n sandboxId,\n executionId,\n expiresAt,\n status: options => readWorkerStatus(config.sandbox, executionId, paths, options),\n readOutput: (stream, options) => readOutput(config.sandbox, executionId, paths, stream, options),\n cancel: () => cancelExecution(config, executionId, paths),\n stop: async () => {\n if (!config.sandbox.stop) throw new Error(`Sandbox provider \"${config.sandbox.provider}\" does not support stop.`);\n await config.sandbox.stop();\n },\n destroy: options => destroyWithRetry(config.sandbox, options),\n relaunch: async options => {\n if (options.executionId === executionId) throw new Error('Relaunch requires a new executionId.');\n validateInput(options.input);\n return createExecution(config, options.executionId, options.input);\n },\n };\n}\n\nasync function stageInput(\n config: WorkerConfig,\n paths: ReturnType<typeof executionPaths>,\n input?: SandboxWorkerInput,\n): Promise<string | undefined> {\n if (!input) return undefined;\n const data = typeof input.data === 'string' ? Buffer.from(input.data) : Buffer.from(input.data);\n if (data.byteLength > config.inputLimitBytes) {\n throw new Error(`Worker input exceeds inputLimitBytes (${data.byteLength} > ${config.inputLimitBytes}).`);\n }\n const path = input.type === 'stdin' ? paths.stdin : posix.resolve(config.remoteDir, input.path);\n await uploadFile(config.sandbox, path, data);\n await runInSandbox(config.sandbox, `chmod 600 ${shellQuote(path)}`);\n return input.type === 'stdin' ? path : undefined;\n}\n\nfunction buildExecutionScript(\n config: WorkerConfig,\n paths: ReturnType<typeof executionPaths>,\n stdinPath?: string,\n): string {\n const cwd = posix.resolve(config.remoteDir, config.workingDirectory);\n const envPrefix = Object.entries(config.env)\n .map(([key, value]) => `${key}=${shellQuote(value)}`)\n .join(' ');\n const executable = [shellQuote(config.command), ...config.args.map(shellQuote)].join(' ');\n const target = `${envPrefix ? `env ${envPrefix} ` : ''}${executable}`;\n const graceAttempts = Math.max(1, Math.ceil(config.terminationGraceMs / 1000));\n const state = (value: string) =>\n `tmp=${shellQuote(`${paths.status}.tmp.$$`)}; printf '%s\\\\n' ${shellQuote(value)} > \"$tmp\"; mv \"$tmp\" ${shellQuote(paths.status)};`;\n\n return [\n '#!/bin/sh',\n `cd ${shellQuote(cwd)}`,\n `execution_id=${shellQuote(paths.executionId)}`,\n `stdout=${shellQuote(paths.stdout)}`,\n `stderr=${shellQuote(paths.stderr)}`,\n `pidfile=${shellQuote(paths.pid)}`,\n `tokenfile=${shellQuote(paths.pidToken)}`,\n `: > \"$stdout\"; : > \"$stderr\"`,\n state(`starting|${paths.executionId}`),\n `setsid sh -c ${shellQuote(`exec ${target}${stdinPath ? ` < ${shellQuote(stdinPath)}` : ''}`)} > \"$stdout\" 2> \"$stderr\" &`,\n 'child=$!',\n 'printf %s \"$child\" > \"$pidfile\"',\n `if [ -r \"/proc/$child/stat\" ]; then awk '{print $22}' \"/proc/$child/stat\" > \"$tokenfile\"; else : > \"$tokenfile\"; fi`,\n state(`running|${paths.executionId}`),\n 'cancelled=0',\n `trap 'cancelled=1; kill -TERM -\"$child\" 2>/dev/null || kill -TERM \"$child\" 2>/dev/null || true' TERM INT`,\n ...(config.executionTimeoutMs\n ? [\n `(sleep ${Math.max(1, Math.ceil(config.executionTimeoutMs / 1000))}; if kill -0 \"$child\" 2>/dev/null; then ${state(\n `timed_out|${paths.executionId}|execution`,\n )} kill -TERM -\"$child\" 2>/dev/null || kill -TERM \"$child\" 2>/dev/null || true; i=0; while kill -0 \"$child\" 2>/dev/null && [ \"$i\" -lt ${graceAttempts} ]; do sleep 1; i=$((i + 1)); done; kill -KILL -\"$child\" 2>/dev/null || kill -KILL \"$child\" 2>/dev/null || true; fi) &`,\n 'watchdog=$!',\n ]\n : []),\n 'wait \"$child\"',\n 'code=$?',\n ...(config.executionTimeoutMs ? ['kill \"$watchdog\" 2>/dev/null || true'] : []),\n `current=\"$(cat ${shellQuote(paths.status)} 2>/dev/null || true)\"`,\n `case \"$current\" in timed_out*) ;; *) if [ \"$cancelled\" -eq 1 ]; then ${state(\n `cancelled|${paths.executionId}|TERM`,\n )} else signal=''; if [ \"$code\" -gt 128 ]; then signal=\"SIG$((code - 128))\"; fi; tmp=${shellQuote(\n `${paths.status}.tmp.$$`,\n )}; printf 'exited|%s|%s|%s\\\\n' \"$execution_id\" \"$code\" \"$signal\" > \"$tmp\"; mv \"$tmp\" ${shellQuote(\n paths.status,\n )}; fi ;; esac`,\n 'rm -f \"$pidfile\" \"$tokenfile\"',\n 'exit \"$code\"',\n ].join('\\n');\n}\n\nasync function launchExecution(sandbox: WorkspaceSandbox, paths: ReturnType<typeof executionPaths>): Promise<void> {\n await runInSandbox(sandbox, `setsid nohup sh ${shellQuote(paths.script)} >/dev/null 2>&1 & echo $!`, {\n label: 'launch worker execution',\n });\n}\n\nasync function waitForStartup(\n config: WorkerConfig,\n executionId: string,\n paths: ReturnType<typeof executionPaths>,\n): Promise<SandboxWorkerStatus> {\n const deadline = Date.now() + config.startupTimeoutMs;\n while (Date.now() < deadline) {\n const status = await readWorkerStatus(config.sandbox, executionId, paths);\n if (status.state !== 'unknown' && status.state !== 'starting') return status;\n await new Promise(resolve => setTimeout(resolve, 100));\n }\n return { state: 'timed_out', executionId, phase: 'startup' };\n}\n\nasync function readWorkerStatus(\n sandbox: WorkspaceSandbox,\n executionId: string,\n paths: ReturnType<typeof executionPaths>,\n options?: { wake?: boolean },\n): Promise<SandboxWorkerStatus> {\n const providerState = sandbox.status;\n if (providerState === 'destroyed' || providerState === 'destroying') {\n return { state: 'provider_unavailable', executionId, providerState };\n }\n if (providerState === 'stopped' || providerState === 'stopping') {\n if (!options?.wake || !sandbox.start) return { state: 'provider_unavailable', executionId, providerState };\n try {\n await sandbox.start();\n } catch (error) {\n return { state: 'provider_unavailable', executionId, providerState, message: errorMessage(error) };\n }\n }\n\n try {\n const result = await runInSandbox(\n sandbox,\n [\n `status=\"$(cat ${shellQuote(paths.status)} 2>/dev/null || true)\"`,\n `if [ -f ${shellQuote(paths.pid)} ]; then`,\n ` pid=\"$(cat ${shellQuote(paths.pid)})\"`,\n ` expected=\"$(cat ${shellQuote(paths.pidToken)} 2>/dev/null || true)\"`,\n ` actual=\"$(if [ -r \"/proc/$pid/stat\" ]; then awk '{print $22}' \"/proc/$pid/stat\"; fi)\"`,\n ` if kill -0 \"$pid\" 2>/dev/null && { [ -z \"$expected\" ] || [ \"$expected\" = \"$actual\" ]; }; then echo \"running|${executionId}\"; exit 0; fi`,\n ` if kill -0 \"$pid\" 2>/dev/null; then echo \"stale|${executionId}\"; exit 0; fi`,\n 'fi',\n `if [ -n \"$status\" ]; then printf '%s\\\\n' \"$status\"; else echo \"unknown|${executionId}\"; fi`,\n ].join('\\n'),\n { allowFailure: true, label: 'read worker status' },\n );\n if (result.exitCode !== 0) {\n return {\n state: 'provider_unavailable',\n executionId,\n providerState: sandbox.status,\n message: result.stderr || result.stdout || 'Sandbox status inspection failed.',\n };\n }\n return parseStatus(executionId, result.stdout.trim());\n } catch (error) {\n return { state: 'provider_unavailable', executionId, providerState: sandbox.status, message: errorMessage(error) };\n }\n}\n\nfunction parseStatus(executionId: string, value: string): SandboxWorkerStatus {\n const [state, recordedId, first, second] = value.split('|');\n if (recordedId !== executionId || state === 'stale') return { state: 'unknown', executionId };\n if (state === 'starting') return { state, executionId };\n if (state === 'running') return { state, executionId };\n if (state === 'exited') {\n const exitCode = Number(first);\n return Number.isInteger(exitCode)\n ? { state, executionId, exitCode, ...(second ? { signal: second } : {}) }\n : { state: 'unknown', executionId };\n }\n if (state === 'cancelled') return { state, executionId, ...(first ? { signal: first } : {}) };\n if (state === 'timed_out' && (first === 'startup' || first === 'execution')) {\n return { state, executionId, phase: first };\n }\n if (state === 'failed' && (first === 'upload' || first === 'install' || first === 'launch')) {\n return { state, executionId, phase: first, message: second ?? '' };\n }\n return { state: 'unknown', executionId };\n}\n\nasync function cancelExecution(\n config: WorkerConfig,\n executionId: string,\n paths: ReturnType<typeof executionPaths>,\n timeoutPhase?: 'startup',\n): Promise<SandboxWorkerStatus> {\n const current = await readWorkerStatus(config.sandbox, executionId, paths);\n if (current.state !== 'running' && current.state !== 'starting') return current;\n const attempts = Math.max(1, Math.ceil(config.terminationGraceMs / 1000));\n const terminal = timeoutPhase ? `timed_out|${executionId}|startup` : `cancelled|${executionId}|TERM`;\n await runInSandbox(\n config.sandbox,\n [\n `pid=\"$(cat ${shellQuote(paths.pid)} 2>/dev/null || true)\"`,\n '[ -n \"$pid\" ] || exit 0',\n `expected=\"$(cat ${shellQuote(paths.pidToken)} 2>/dev/null || true)\"`,\n `actual=\"$(if [ -r \"/proc/$pid/stat\" ]; then awk '{print $22}' \"/proc/$pid/stat\"; fi)\"`,\n '[ -n \"$expected\" ] && [ \"$expected\" != \"$actual\" ] && exit 0',\n 'kill -TERM -\"$pid\" 2>/dev/null || kill -TERM \"$pid\" 2>/dev/null || true',\n `i=0; while kill -0 \"$pid\" 2>/dev/null && [ \"$i\" -lt ${attempts} ]; do sleep 1; i=$((i + 1)); done`,\n 'kill -KILL -\"$pid\" 2>/dev/null || kill -KILL \"$pid\" 2>/dev/null || true',\n `tmp=${shellQuote(`${paths.status}.tmp.$$`)}; printf '%s\\\\n' ${shellQuote(terminal)} > \"$tmp\"; mv \"$tmp\" ${shellQuote(paths.status)}`,\n `rm -f ${shellQuote(paths.pid)} ${shellQuote(paths.pidToken)}`,\n ].join('\\n'),\n { allowFailure: true, timeout: config.terminationGraceMs + 5_000, label: 'cancel worker execution' },\n );\n return parseStatus(executionId, terminal);\n}\n\nasync function readOutput(\n sandbox: WorkspaceSandbox,\n executionId: string,\n paths: ReturnType<typeof executionPaths>,\n stream: 'stdout' | 'stderr',\n options?: { offset?: number; maxBytes?: number },\n): Promise<SandboxWorkerOutput> {\n const offset = Math.max(0, Math.floor(options?.offset ?? 0));\n const maxBytes = Math.max(1, Math.floor(options?.maxBytes ?? DEFAULT_OUTPUT_READ_LIMIT));\n const path = stream === 'stdout' ? paths.stdout : paths.stderr;\n try {\n const result = await runInSandbox(\n sandbox,\n `size=$(wc -c < ${shellQuote(path)} 2>/dev/null || echo 0); printf '%s\\\\n' \"$size\"; tail -c +${offset + 1} ${shellQuote(\n path,\n )} 2>/dev/null | head -c ${maxBytes} | base64`,\n { allowFailure: true, label: `read worker ${stream}` },\n );\n if (result.exitCode !== 0) throw new Error(result.stderr || result.stdout || `Unable to read worker ${stream}.`);\n const newline = result.stdout.indexOf('\\n');\n const totalBytes = Number((newline === -1 ? result.stdout : result.stdout.slice(0, newline)).trim()) || 0;\n const encoded = newline === -1 ? '' : result.stdout.slice(newline + 1).replace(/\\s/g, '');\n const data = Buffer.from(encoded, 'base64');\n const nextOffset = offset + data.byteLength;\n const status = await readWorkerStatus(sandbox, executionId, paths);\n const terminal = ['exited', 'cancelled', 'timed_out', 'failed'].includes(status.state);\n const interrupted = status.state === 'provider_unavailable' || status.state === 'unknown';\n return {\n stream,\n data,\n offset,\n nextOffset,\n totalBytes,\n eof: terminal && nextOffset >= totalBytes,\n truncated: nextOffset < totalBytes,\n interrupted,\n };\n } catch {\n return {\n stream,\n data: new Uint8Array(),\n offset,\n nextOffset: offset,\n totalBytes: offset,\n eof: false,\n truncated: false,\n interrupted: true,\n };\n }\n}\n\nasync function destroyWithRetry(\n sandbox: WorkspaceSandbox,\n options?: { attempts?: number; delayMs?: number },\n): Promise<SandboxDestroyResult> {\n if (!sandbox.destroy) return { state: 'unsupported', attempts: 0 };\n const attempts = Math.max(1, Math.floor(options?.attempts ?? 3));\n const delayMs = Math.max(0, Math.floor(options?.delayMs ?? 250));\n let lastError: unknown;\n for (let attempt = 1; attempt <= attempts; attempt++) {\n try {\n await sandbox.destroy();\n return { state: 'destroyed', attempts: attempt };\n } catch (error) {\n lastError = error;\n if (attempt < attempts) await new Promise(resolve => setTimeout(resolve, delayMs));\n }\n }\n return { state: 'exhausted', attempts, error: lastError };\n}\n\nasync function writeFailedStatus(\n sandbox: WorkspaceSandbox,\n paths: ReturnType<typeof executionPaths>,\n executionId: string,\n phase: 'upload' | 'install' | 'launch',\n error: unknown,\n): Promise<void> {\n await writeStatus(\n sandbox,\n paths.status,\n `failed|${executionId}|${phase}|${sanitizeStatusValue(errorMessage(error))}`,\n );\n}\n\nasync function writeStatus(sandbox: WorkspaceSandbox, path: string, value: string): Promise<void> {\n await runInSandbox(\n sandbox,\n `tmp=${shellQuote(`${path}.tmp.$$`)}; printf '%s\\\\n' ${shellQuote(value)} > \"$tmp\"; mv \"$tmp\" ${shellQuote(path)}`,\n { allowFailure: true, label: 'write worker status' },\n );\n}\n\nfunction executionPaths(remoteDir: string, executionId: string) {\n const dir = `${remoteDir}/${RUNTIME_DIR}/${executionId}`;\n return {\n executionId,\n dir,\n script: `${dir}/launch.sh`,\n pid: `${dir}/pid`,\n pidToken: `${dir}/pid-start`,\n status: `${dir}/status`,\n stdin: `${dir}/stdin`,\n stdout: `${dir}/stdout`,\n stderr: `${dir}/stderr`,\n };\n}\n\nfunction validateExecutionId(executionId: string): void {\n if (!executionId || !EXECUTION_ID_PATTERN.test(executionId)) {\n throw new Error('Worker executionId must contain only letters, numbers, dots, underscores, and hyphens.');\n }\n}\n\nfunction workerPhaseError(phase: 'upload' | 'install' | 'launch', error: unknown): Error {\n return new Error(`Worker ${phase} failed: ${errorMessage(error)}`, { cause: error });\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction sanitizeStatusValue(value: string): string {\n return value.replace(/[|\\r\\n]/g, ' ').slice(0, 500);\n}\n"],"mappings":";;;;;;;;;;;;;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S,oBAAoB,OAAuB;CAClD,OAAO,MAAM,QAAQ,YAAY,GAAG,CAAC,CAAC,MAAM,GAAG,GAAG;AACpD"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export { SandboxDeployer } from './deployer.js';
|
|
2
2
|
export { deployToSandbox, buildLaunchScript } from './engine.js';
|
|
3
|
+
export { deployWorkerToSandbox } from './worker.js';
|
|
3
4
|
export { updateEdgeConfigAlias } from './alias.js';
|
|
4
5
|
export { readDeploymentManifest, writeDeploymentManifest, MANIFEST_FILENAME } from './manifest.js';
|
|
5
|
-
export type { SandboxAliasOptions, SandboxDeployerOptions, SandboxDeployLogger, SandboxDeployment, SandboxDeploymentManifest, DeployToSandboxOptions, } from './types.js';
|
|
6
|
+
export type { SandboxAliasOptions, SandboxDeployerOptions, SandboxDeployLogger, SandboxDeployment, SandboxDeploymentManifest, DeployToSandboxOptions, DeployWorkerToSandboxOptions, SandboxWorkerInput, SandboxWorkerDeployment, SandboxWorkerStatus, SandboxWorkerOutput, SandboxDestroyResult, } from './types.js';
|
|
6
7
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAC7C,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAC9D,OAAO,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAC;AAChD,OAAO,EAAE,sBAAsB,EAAE,uBAAuB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAChG,YAAY,EACV,mBAAmB,EACnB,sBAAsB,EACtB,mBAAmB,EACnB,iBAAiB,EACjB,yBAAyB,EACzB,sBAAsB,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAC7C,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAC9D,OAAO,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AACjD,OAAO,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAC;AAChD,OAAO,EAAE,sBAAsB,EAAE,uBAAuB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAChG,YAAY,EACV,mBAAmB,EACnB,sBAAsB,EACtB,mBAAmB,EACnB,iBAAiB,EACjB,yBAAyB,EACzB,sBAAsB,EACtB,4BAA4B,EAC5B,kBAAkB,EAClB,uBAAuB,EACvB,mBAAmB,EACnB,mBAAmB,EACnB,oBAAoB,GACrB,MAAM,SAAS,CAAC"}
|