@mastra/daytona 0.2.0 → 0.2.1

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/utils/compact.ts","../src/utils/shell-quote.ts","../src/sandbox/mounts/types.ts","../src/sandbox/mounts/s3.ts","../src/sandbox/mounts/gcs.ts","../src/sandbox/process-manager.ts","../src/sandbox/index.ts"],"names":["createHash","ProcessHandle","SandboxProcessManager","MastraSandbox","SandboxNotReadyError","Daytona","SandboxState","DaytonaNotFoundError","DaytonaError"],"mappings":";;;;;;;;;AAGO,SAAS,QAA0B,GAAA,EAAW;AACnD,EAAA,OAAO,MAAA,CAAO,WAAA,CAAY,MAAA,CAAO,OAAA,CAAQ,GAAG,CAAA,CAAE,MAAA,CAAO,CAAC,GAAG,CAAC,CAAA,KAAM,CAAA,KAAM,MAAS,CAAC,CAAA;AAClF;;;ACCO,SAAS,WAAW,GAAA,EAAqB;AAE9C,EAAA,IAAI,wBAAA,CAAyB,IAAA,CAAK,GAAG,CAAA,EAAG,OAAO,GAAA;AAE/C,EAAA,OAAO,GAAA,GAAM,GAAA,CAAI,OAAA,CAAQ,IAAA,EAAM,OAAO,CAAA,GAAI,GAAA;AAC5C;;;ACFO,IAAM,UAAA,GAAa,mBAAA;AA0B1B,IAAM,gBAAA,GAAmB,qCAAA;AAElB,SAAS,mBAAmB,MAAA,EAAsB;AACvD,EAAA,IAAI,CAAC,gBAAA,CAAiB,IAAA,CAAK,MAAM,CAAA,EAAG;AAClC,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,yBAAyB,MAAM,CAAA,kFAAA;AAAA,KACjC;AAAA,EACF;AACF;AAMO,SAAS,iBAAiB,QAAA,EAAwB;AACvD,EAAA,IAAI,MAAA;AACJ,EAAA,IAAI;AACF,IAAA,MAAA,GAAS,IAAI,IAAI,QAAQ,CAAA;AAAA,EAC3B,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IA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,EAAY;AAC3D,UAAA,IAAA,CAAK,OAAO,GAAA,CAAI,IAAA,EAAM,EAAE,KAAA,EAAO,WAAW,CAAA;AAAA,QAC5C;AAAA,MACF;AAAA,IACF;AAEA,IAAA,IAAA,CAAK,MAAA,GAAS,SAAA;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,MAAM,YAAe,EAAA,EAAkC;AACrD,IAAA,IAAI;AACF,MAAA,OAAO,MAAM,EAAA,EAAG;AAAA,IAClB,SAAS,KAAA,EAAO;AACd,MAAA,IAAI,KAAK,kBAAA,CAAmB,KAAK,CAAA,IAAK,CAAC,KAAK,WAAA,EAAa;AACvD,QAAA,IAAA,CAAK,oBAAA,EAAqB;AAC1B,QAAA,IAAA,CAAK,WAAA,GAAc,IAAA;AACnB,QAAA,IAAI;AACF,UAAA,MAAM,KAAK,aAAA,EAAc;AACzB,UAAA,OAAO,MAAM,EAAA,EAAG;AAAA,QAClB,CAAA,SAAE;AACA,UAAA,IAAA,CAAK,WAAA,GAAc,KAAA;AAAA,QACrB;AAAA,MACF;AACA,MAAA,MAAM,KAAA;AAAA,IACR;AAAA,EACF;AACF","file":"index.cjs","sourcesContent":["/**\n * Returns a shallow copy of the object with all undefined values removed.\n */\nexport function compact<T extends object>(obj: T): T {\n return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined)) as T;\n}\n","/**\n * Shell-quote a single argument for safe use in a command string.\n *\n * Arguments containing only safe characters are returned as-is.\n * All others are wrapped in single quotes with embedded single quotes escaped.\n */\nexport function shellQuote(arg: string): string {\n // Safe characters that don't need quoting\n if (/^[a-zA-Z0-9._\\-/@:=]+$/.test(arg)) return arg;\n // Wrap in single quotes, escaping any embedded single quotes\n return \"'\" + arg.replace(/'/g, \"'\\\\''\") + \"'\";\n}\n","/**\n * Shared types for Daytona mount operations.\n */\n\nimport type { Sandbox } from '@daytonaio/sdk';\n\nimport type { DaytonaGCSMountConfig } from './gcs';\nimport type { DaytonaS3MountConfig } from './s3';\n\nexport const LOG_PREFIX = '[@mastra/daytona]';\n\n/**\n * Union of mount configs supported by Daytona sandbox.\n */\nexport type DaytonaMountConfig = DaytonaS3MountConfig | DaytonaGCSMountConfig;\n\n/**\n * Context for mount operations.\n * Abstracts over the Daytona SDK so mount helpers stay SDK-agnostic.\n */\nexport interface MountContext {\n run: (cmd: string, timeoutMs?: number) => Promise<{ exitCode: number; stdout: string; stderr: string }>;\n writeFile: (path: string, content: string) => Promise<void>;\n logger: {\n debug: (message: string, ...args: unknown[]) => void;\n info: (message: string, ...args: unknown[]) => void;\n warn: (message: string, ...args: unknown[]) => void;\n error: (message: string, ...args: unknown[]) => void;\n };\n}\n\n/**\n * Validate a bucket name before interpolating into shell commands.\n * Covers S3, GCS, and S3-compatible (R2, MinIO) naming rules.\n */\nconst SAFE_BUCKET_NAME = /^[a-z0-9][a-z0-9.\\-]{1,61}[a-z0-9]$/;\n\nexport function validateBucketName(bucket: string): void {\n if (!SAFE_BUCKET_NAME.test(bucket)) {\n throw new Error(\n `Invalid bucket name: \"${bucket}\". Bucket names must be 3-63 characters, lowercase alphanumeric, hyphens, or dots.`,\n );\n }\n}\n\n/**\n * Validate an endpoint URL before interpolating into shell commands.\n * Only http and https schemes are allowed.\n */\nexport function validateEndpoint(endpoint: string): void {\n let parsed: URL;\n try {\n parsed = new URL(endpoint);\n } catch {\n throw new Error(`Invalid endpoint URL: \"${endpoint}\"`);\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new Error(`Invalid endpoint URL scheme: \"${parsed.protocol}\". Only http: and https: are allowed.`);\n }\n}\n\n/**\n * Result of running a command in the Daytona sandbox.\n *\n * Note: Daytona's `executeCommand` returns a single combined string (stdout + stderr).\n * There is no separate stderr stream. If you need stderr isolated, redirect it in the\n * shell command itself (e.g. `2>/dev/null` or `2>&1`).\n */\nexport interface CommandResult {\n exitCode: number;\n /** Combined stdout/stderr output from the command. */\n output: string;\n}\n\n/**\n * Run a command in the Daytona sandbox.\n *\n * Thin wrapper around `sandbox.process.executeCommand` that converts timeout\n * from milliseconds to seconds and null-coalesces the output string.\n *\n * Does NOT throw on non-zero exit codes — callers should check `exitCode`.\n */\nexport async function runCommand(\n sandbox: Sandbox,\n command: string,\n options?: { timeout?: number },\n): Promise<CommandResult> {\n const result = await sandbox.process.executeCommand(\n command,\n undefined, // cwd\n undefined, // env\n options?.timeout !== undefined ? Math.ceil(options.timeout / 1000) : undefined,\n );\n\n return {\n exitCode: result.exitCode,\n output: result.result ?? '',\n };\n}\n","import { createHash } from 'node:crypto';\n\nimport type { FilesystemMountConfig } from '@mastra/core/workspace';\n\nimport { shellQuote } from '../../utils/shell-quote';\nimport { LOG_PREFIX, validateBucketName, validateEndpoint } from './types';\nimport type { MountContext } from './types';\n\n/**\n * S3 mount config for Daytona (mounted via s3fs-fuse).\n *\n * If credentials are not provided, the bucket will be mounted as read-only\n * using the `public_bucket=1` option (for public AWS S3 buckets only).\n *\n * Note: S3-compatible services (R2, MinIO, etc.) always require credentials.\n */\nexport interface DaytonaS3MountConfig extends FilesystemMountConfig {\n type: 's3';\n /** S3 bucket name */\n bucket: string;\n /** AWS region */\n region: string;\n /** S3 endpoint for S3-compatible storage (MinIO, R2, etc.) */\n endpoint?: string;\n /** AWS access key ID (optional - omit for public buckets) */\n accessKeyId?: string;\n /** AWS secret access key (optional - omit for public buckets) */\n secretAccessKey?: string;\n /** Mount as read-only (even if credentials have write access) */\n readOnly?: boolean;\n}\n\n/**\n * Mount an S3 bucket using s3fs-fuse.\n */\nexport async function mountS3(mountPath: string, config: DaytonaS3MountConfig, ctx: MountContext): Promise<void> {\n const { run, writeFile, logger } = ctx;\n\n validateBucketName(config.bucket);\n if (config.endpoint) {\n validateEndpoint(config.endpoint);\n }\n\n const quotedMountPath = shellQuote(mountPath);\n\n // Validate credentials before any network calls — this gives the user a clear,\n // immediate error instead of a confusing connectivity failure.\n const hasAccessKey = !!config.accessKeyId;\n const hasSecretKey = !!config.secretAccessKey;\n if (hasAccessKey !== hasSecretKey) {\n throw new Error('Both accessKeyId and secretAccessKey must be provided together.');\n }\n const hasCredentials = hasAccessKey && hasSecretKey;\n\n if (!hasCredentials && config.endpoint) {\n throw new Error(\n `S3-compatible storage requires credentials. ` +\n `Detected endpoint: ${config.endpoint}. ` +\n `The public_bucket option only works for AWS S3 public buckets, not R2, MinIO, etc.`,\n );\n }\n\n // For S3-compatible storage (R2, MinIO, etc.), check connectivity to the custom endpoint.\n // AWS S3 endpoints are whitelisted in Daytona's proxy so no check needed for the default case.\n if (config.endpoint) {\n const endpoint = config.endpoint.replace(/\\/$/, '');\n const connectivityCheck = await run(`curl -sS --max-time 5 ${shellQuote(endpoint)} 2>&1`, 10_000);\n const checkOutput = connectivityCheck.stdout.trim();\n if (\n connectivityCheck.exitCode !== 0 ||\n checkOutput.toLowerCase().includes('restricted') ||\n checkOutput.toLowerCase().includes('blocked')\n ) {\n throw new Error(\n `Cannot reach ${endpoint} from this sandbox. ` +\n `S3-compatible storage mounting requires network access to the configured endpoint, ` +\n `which may be blocked on Daytona's restricted tiers. ` +\n `Upgrade to a tier with unrestricted internet access, or contact Daytona support to remove the network restriction.` +\n (checkOutput ? `\\n\\nSandbox network response: ${checkOutput}` : ''),\n );\n }\n }\n\n // Install s3fs if not present\n const checkResult = await run('which s3fs 2>/dev/null || echo \"not found\"', 30_000);\n if (checkResult.stdout.includes('not found')) {\n logger.warn(`${LOG_PREFIX} s3fs not found, attempting runtime installation...`);\n logger.info(`${LOG_PREFIX} Tip: For faster startup, pre-install s3fs in your sandbox image`);\n\n await run('sudo apt-get update -qq 2>&1', 60_000);\n\n // The fuse package's post-install script may fail in containers (e.g. can't run modprobe,\n // can't set SUID). Use || true so the overall command succeeds even if dpkg exits non-zero,\n // then verify the binary is actually present below.\n await run('sudo apt-get install -y s3fs fuse 2>&1 || sudo apt-get install -y s3fs-fuse fuse 2>&1 || true', 120_000);\n\n // Verify installation\n const s3fsCheck = await run('which s3fs 2>/dev/null || echo \"not found\"', 30_000);\n if (s3fsCheck.stdout.includes('not found')) {\n throw new Error('Failed to install s3fs: binary not found after install attempt');\n }\n }\n\n // The fuse post-install script may fail to set the SUID bit on fusermount.\n // Set it explicitly so non-root processes can call fusermount.\n await run('sudo chmod u+s /usr/bin/fusermount3 /usr/bin/fusermount 2>/dev/null || true', 30_000);\n\n // Get uid/gid for proper file ownership\n const idResult = await run('id -u && id -g', 30_000);\n const [uid, gid] = idResult.stdout.trim().split('\\n');\n const validUidGid = uid && gid && /^\\d+$/.test(uid) && /^\\d+$/.test(gid);\n if (!validUidGid) {\n logger.warn(\n `${LOG_PREFIX} Unexpected uid/gid format: \"${idResult.stdout.trim()}\" — mounted files will be owned by root`,\n );\n }\n\n // Use a mount-specific credentials path to avoid races with concurrent mounts\n const mountHash = createHash('md5').update(mountPath).digest('hex').slice(0, 8);\n const credentialsPath = `/tmp/.passwd-s3fs-${mountHash}`;\n\n // Allow non-root processes to use FUSE and the allow_other mount option.\n // These are no-ops if already configured.\n await run(\n `sudo chmod a+rw /dev/fuse 2>/dev/null || true; ` +\n `sudo bash -c 'grep -q \"^user_allow_other\" /etc/fuse.conf 2>/dev/null || echo \"user_allow_other\" >> /etc/fuse.conf' 2>/dev/null || true`,\n );\n\n if (hasCredentials) {\n await run(`sudo rm -f ${shellQuote(credentialsPath)}`, 30_000);\n await writeFile(credentialsPath, `${config.accessKeyId}:${config.secretAccessKey}`);\n await run(`chmod 600 ${shellQuote(credentialsPath)}`, 30_000);\n }\n\n const mountOptions: string[] = [];\n\n if (hasCredentials) {\n mountOptions.push(`passwd_file=${credentialsPath}`);\n } else {\n mountOptions.push('public_bucket=1');\n logger.debug(`${LOG_PREFIX} No credentials provided, mounting as public bucket (read-only)`);\n }\n\n // allow_other: let other users (e.g. root for rmdir) access the mount.\n // Requires user_allow_other in /etc/fuse.conf for non-root mounts.\n mountOptions.push('allow_other');\n\n if (validUidGid) {\n mountOptions.push(`uid=${uid}`, `gid=${gid}`);\n }\n\n if (config.endpoint) {\n const endpoint = config.endpoint.replace(/\\/$/, '');\n mountOptions.push(`url=${shellQuote(endpoint)}`, 'use_path_request_style', 'sigv4', 'nomultipart');\n }\n\n if (config.readOnly) {\n mountOptions.push('ro');\n logger.debug(`${LOG_PREFIX} Mounting as read-only`);\n }\n\n // Run s3fs as the sandbox user (not root) so the FUSE connection is registered\n // in the container's user namespace — allowing fusermount -u to unmount it later.\n const mountCmd = `s3fs ${shellQuote(config.bucket)} ${quotedMountPath} -o ${mountOptions.join(' -o ')}`;\n logger.debug(`${LOG_PREFIX} Mounting S3:`, hasCredentials ? mountCmd.replace(credentialsPath, '***') : mountCmd);\n\n const result = await run(mountCmd, 60_000);\n logger.debug(`${LOG_PREFIX} s3fs result:`, {\n exitCode: result.exitCode,\n stdout: result.stdout,\n stderr: result.stderr,\n });\n if (result.exitCode !== 0) {\n throw new Error(`Failed to mount S3 bucket: ${result.stderr || result.stdout}`);\n }\n}\n","import { createHash } from 'node:crypto';\n\nimport type { FilesystemMountConfig } from '@mastra/core/workspace';\n\nimport { shellQuote } from '../../utils/shell-quote';\nimport { LOG_PREFIX, validateBucketName } from './types';\nimport type { MountContext } from './types';\n\n/**\n * GCS mount config for Daytona (mounted via gcsfuse).\n *\n * If credentials are not provided, the bucket will be mounted as read-only\n * using anonymous access (for public buckets only).\n */\nexport interface DaytonaGCSMountConfig extends FilesystemMountConfig {\n type: 'gcs';\n /** GCS bucket name */\n bucket: string;\n /** Service account key JSON (optional - omit for public buckets) */\n serviceAccountKey?: string;\n}\n\n/**\n * Mount a GCS bucket using gcsfuse.\n */\nexport async function mountGCS(mountPath: string, config: DaytonaGCSMountConfig, ctx: MountContext): Promise<void> {\n const { run, writeFile, logger } = ctx;\n\n validateBucketName(config.bucket);\n\n const quotedMountPath = shellQuote(mountPath);\n\n // gcsfuse needs to reach Google Cloud Storage APIs at runtime.\n // Daytona's free/restricted tiers block access to Google services.\n // Fail fast with a clear message instead of hanging on the mount command.\n const connectivityCheck = await run('curl -sS --max-time 5 http://storage.googleapis.com 2>&1', 10_000);\n const checkOutput = connectivityCheck.stdout.trim();\n // Daytona's restricted tiers return HTTP 200 with a plain-text restriction message\n // for HTTP requests, or reset the connection for HTTPS. Detect either case.\n if (\n connectivityCheck.exitCode !== 0 ||\n checkOutput.toLowerCase().includes('restricted') ||\n checkOutput.toLowerCase().includes('blocked')\n ) {\n throw new Error(\n `Cannot reach Google Cloud Storage from this sandbox. ` +\n `GCS mounting requires network access to storage.googleapis.com, ` +\n `which may be blocked on Daytona's restricted tiers. ` +\n `Upgrade to a tier with unrestricted internet access, or contact Daytona support to remove the network restriction.` +\n (checkOutput ? `\\n\\nSandbox network response: ${checkOutput}` : ''),\n );\n }\n\n // Install gcsfuse if not present\n const checkResult = await run('which gcsfuse 2>/dev/null || echo \"not found\"', 30_000);\n if (checkResult.stdout.includes('not found')) {\n logger.warn(`${LOG_PREFIX} gcsfuse not found, attempting runtime installation...`);\n logger.info(`${LOG_PREFIX} Tip: For faster startup, pre-install gcsfuse in your sandbox image`);\n\n // Ensure curl and gpg are available for downloading the gcsfuse apt key.\n // Do NOT pre-install fuse here — the fuse package post-install script fails in containers\n // (can't run modprobe), leaving dpkg in a broken state that prevents gcsfuse from installing.\n // The gcsfuse apt package handles the fuse/fuse3 dependency automatically when installed.\n await run('sudo apt-get update -qq 2>&1', 60_000);\n const prepResult = await run('sudo apt-get install -y curl gnupg 2>&1', 120_000);\n if (prepResult.exitCode !== 0) {\n throw new Error(\n `Failed to install gcsfuse prerequisites (curl, gnupg): ${prepResult.stderr || prepResult.stdout}`,\n );\n }\n\n // Detect distro ID and codename from /etc/os-release (more reliable than lsb_release).\n // Google's gcsfuse apt repo only has packages for certain codenames (e.g. bookworm, jammy).\n // If the detected codename has no repo (e.g. trixie, noble), fall back to a known-good\n // codename for the distro family: bookworm for Debian, jammy for Ubuntu.\n const distroIdResult = await run(\n 'cat /etc/os-release 2>/dev/null | grep \"^ID=\" | cut -d= -f2 || echo debian',\n 30_000,\n );\n const distroId = distroIdResult.stdout.trim().replace(/\"/g, '') || 'debian';\n\n // Pick the appropriate known-good fallback for this distro family\n const fallbackCodename = distroId === 'ubuntu' ? 'jammy' : 'bookworm';\n\n const codenameResult = await run(\n `cat /etc/os-release 2>/dev/null | grep \"^VERSION_CODENAME=\" | cut -d= -f2 || echo ${fallbackCodename}`,\n 30_000,\n );\n const detectedCodename = codenameResult.stdout.trim() || fallbackCodename;\n if (!/^[a-z0-9][a-z0-9-]*$/.test(detectedCodename)) {\n throw new Error(`Invalid distro codename for gcsfuse repo: \"${detectedCodename}\"`);\n }\n\n logger.debug(`${LOG_PREFIX} Detected distro: ${distroId}/${detectedCodename}, fallback: ${fallbackCodename}`);\n\n // Set up the gcsfuse apt repository. Use separate curl + gpg steps (not piped)\n // so a curl failure propagates as non-zero exit rather than being masked by gpg.\n const repoSetup = await run(\n 'sudo mkdir -p /etc/apt/keyrings && ' +\n 'curl -fsSL https://packages.cloud.google.com/apt/doc/apt-key.gpg -o /tmp/gcsfuse-key.gpg && ' +\n 'sudo gpg --batch --yes --dearmor -o /etc/apt/keyrings/gcsfuse.gpg /tmp/gcsfuse-key.gpg && ' +\n `echo \"deb [signed-by=/etc/apt/keyrings/gcsfuse.gpg] https://packages.cloud.google.com/apt gcsfuse-${detectedCodename} main\" | sudo tee /etc/apt/sources.list.d/gcsfuse.list`,\n 30_000,\n );\n if (repoSetup.exitCode !== 0) {\n throw new Error(`Failed to set up gcsfuse apt repository: ${repoSetup.stderr || repoSetup.stdout}`);\n }\n\n // apt-get update may fail on unrelated repos (e.g. broken keys); use || true and verify install separately\n await run('sudo apt-get update -qq 2>&1 || true', 60_000);\n\n let installResult = await run('sudo apt-get install -y gcsfuse 2>&1', 120_000);\n\n // Fallback: if install failed with detected codename (e.g. trixie, noble — no repo yet),\n // retry with a known-good codename for the distro family.\n if (installResult.exitCode !== 0 && detectedCodename !== fallbackCodename) {\n logger.warn(\n `${LOG_PREFIX} gcsfuse install failed for \"${detectedCodename}\", retrying with \"${fallbackCodename}\" fallback`,\n );\n await run(\n 'sudo rm -f /etc/apt/sources.list.d/gcsfuse.list && ' +\n `echo \"deb [signed-by=/etc/apt/keyrings/gcsfuse.gpg] https://packages.cloud.google.com/apt gcsfuse-${fallbackCodename} main\" | sudo tee /etc/apt/sources.list.d/gcsfuse.list`,\n 10_000,\n );\n await run('sudo apt-get update -qq 2>&1 || true', 60_000);\n installResult = await run('sudo apt-get install -y gcsfuse 2>&1', 120_000);\n }\n\n // Verify installation by checking the binary directly.\n // dpkg may report a non-zero exit if fuse's post-install script fails in containers\n // (can't run modprobe), but gcsfuse is still unpacked and usable in that case.\n const verifyResult = await run('which gcsfuse 2>/dev/null || echo \"not found\"', 30_000);\n if (verifyResult.stdout.includes('not found')) {\n throw new Error(`Failed to install gcsfuse: ${installResult.stderr || installResult.stdout}`);\n }\n if (installResult.exitCode !== 0) {\n logger.warn(\n `${LOG_PREFIX} gcsfuse install reported dpkg errors (likely fuse post-install in container) but binary is present — proceeding`,\n );\n }\n }\n\n // Get uid/gid for proper file ownership\n const idResult = await run('id -u && id -g', 30_000);\n const [uid, gid] = idResult.stdout.trim().split('\\n');\n const validUidGid = uid && gid && /^\\d+$/.test(uid) && /^\\d+$/.test(gid);\n if (!validUidGid) {\n logger.warn(\n `${LOG_PREFIX} Unexpected uid/gid format: \"${idResult.stdout.trim()}\" — mounted files will be owned by root`,\n );\n }\n // Note: gcsfuse uses --uid/--gid flags, not -o uid=X style\n const uidGidFlags = validUidGid ? `--uid=${uid} --gid=${gid}` : '';\n\n // Allow non-root processes to use FUSE and the allow_other mount option.\n // These are no-ops if already configured.\n await run(\n `sudo chmod a+rw /dev/fuse 2>/dev/null || true; ` +\n `sudo bash -c 'grep -q \"^user_allow_other\" /etc/fuse.conf 2>/dev/null || echo \"user_allow_other\" >> /etc/fuse.conf' 2>/dev/null || true`,\n );\n\n const hasCredentials = !!config.serviceAccountKey;\n // Run gcsfuse as the sandbox user (not root) so the FUSE connection is registered\n // in the container's user namespace — allowing fusermount -u to unmount it later.\n let mountCmd: string;\n\n if (hasCredentials) {\n // Use a mount-specific key path to avoid races with concurrent mounts\n const mountHash = createHash('md5').update(mountPath).digest('hex').slice(0, 8);\n const keyPath = `/tmp/gcs-key-${mountHash}.json`;\n await run(`sudo rm -f ${shellQuote(keyPath)}`, 30_000);\n await writeFile(keyPath, config.serviceAccountKey!);\n await run(`chmod 600 ${shellQuote(keyPath)}`, 30_000);\n\n mountCmd = `gcsfuse --key-file=${shellQuote(keyPath)} -o allow_other ${uidGidFlags} ${shellQuote(config.bucket)} ${quotedMountPath}`;\n } else {\n logger.debug(`${LOG_PREFIX} No credentials provided, mounting GCS as public bucket (read-only)`);\n mountCmd = `gcsfuse --anonymous-access -o allow_other ${uidGidFlags} ${shellQuote(config.bucket)} ${quotedMountPath}`;\n }\n\n logger.debug(`${LOG_PREFIX} Mounting GCS:`, mountCmd);\n\n const result = await run(mountCmd, 60_000);\n logger.debug(`${LOG_PREFIX} gcsfuse result:`, {\n exitCode: result.exitCode,\n stdout: result.stdout,\n stderr: result.stderr,\n });\n if (result.exitCode !== 0) {\n throw new Error(`Failed to mount GCS bucket: ${result.stderr || result.stdout}`);\n }\n}\n","/**\n * Daytona Process Manager\n *\n * Implements SandboxProcessManager for Daytona cloud sandboxes.\n * Wraps the Daytona SDK's session API (createSession, executeSessionCommand,\n * getSessionCommandLogs, deleteSession) for background process management.\n *\n * Each spawn() creates a dedicated session with a single command.\n * The user command is wrapped in a subshell `(command)` so that:\n * - `exit N` exits the subshell, not the session shell\n * - Heredocs are contained within the subshell\n * - The session command finishes cleanly\n */\n\nimport type { Sandbox } from '@daytonaio/sdk';\nimport { ProcessHandle, SandboxProcessManager } from '@mastra/core/workspace';\nimport type { CommandResult, ProcessInfo, SpawnProcessOptions } from '@mastra/core/workspace';\nimport { shellQuote } from '../utils/shell-quote';\nimport type { DaytonaSandbox } from './index';\n\n// =============================================================================\n// Daytona Process Handle\n// =============================================================================\n\n/**\n * Wraps a Daytona session + command pair to conform to Mastra's ProcessHandle.\n * Not exported — internal to this module.\n */\nclass DaytonaProcessHandle extends ProcessHandle {\n readonly pid: string;\n\n private readonly _cmdId: string;\n private readonly _sandbox: Sandbox;\n private readonly _startTime: number;\n private readonly _timeout?: number;\n\n private _exitCode: number | undefined;\n private _waitPromise: Promise<CommandResult> | null = null;\n private _streamingPromise: Promise<void> | null = null;\n private _killed = false;\n\n constructor(sessionId: string, cmdId: string, sandbox: Sandbox, startTime: number, options?: SpawnProcessOptions) {\n super(options);\n this.pid = sessionId;\n this._cmdId = cmdId;\n this._sandbox = sandbox;\n this._startTime = startTime;\n this._timeout = options?.timeout;\n }\n\n get exitCode(): number | undefined {\n return this._exitCode;\n }\n\n /** @internal Set by the process manager after streaming starts. */\n set streamingPromise(p: Promise<void>) {\n this._streamingPromise = p;\n\n // Auto-resolve exit code when streaming ends (so exitCode is available without wait())\n p.then(() => this._resolveExitCode()).catch(() => this._resolveExitCode());\n }\n\n /** Fetch the exit code from Daytona and set _exitCode. No-op if already set. */\n private async _resolveExitCode(): Promise<void> {\n if (this._exitCode !== undefined) return;\n try {\n const cmd = await this._sandbox.process.getSessionCommand(this.pid, this._cmdId);\n this._exitCode = cmd.exitCode ?? 0;\n } catch {\n if (this._exitCode === undefined) {\n this._exitCode = 1;\n }\n }\n }\n\n async wait(): Promise<CommandResult> {\n // Idempotent — cache the promise so repeated calls return the same result\n if (!this._waitPromise) {\n this._waitPromise = this._doWait();\n }\n return this._waitPromise;\n }\n\n private async _doWait(): Promise<CommandResult> {\n // Race streaming against timeout (if configured)\n const streamDone = this._streamingPromise ?? Promise.resolve();\n\n if (this._timeout) {\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutId = setTimeout(() => reject(new Error(`Command timed out after ${this._timeout}ms`)), this._timeout);\n });\n\n try {\n await Promise.race([streamDone, timeoutPromise]);\n } catch (error) {\n // On timeout, kill the process and return partial output\n if (error instanceof Error && error.message.includes('timed out')) {\n await this.kill();\n this._exitCode = 124; // Standard timeout exit code\n return {\n success: false,\n exitCode: 124,\n stdout: this.stdout,\n stderr: this.stderr || error.message,\n executionTimeMs: Date.now() - this._startTime,\n };\n }\n throw error;\n } finally {\n clearTimeout(timeoutId);\n }\n } else {\n // No timeout — just wait for streaming to complete\n await streamDone.catch(() => {});\n }\n\n // If killed during wait, return with kill exit code\n if (this._killed) {\n return {\n success: false,\n exitCode: this._exitCode ?? 137,\n stdout: this.stdout,\n stderr: this.stderr,\n executionTimeMs: Date.now() - this._startTime,\n };\n }\n\n // Ensure exit code is resolved\n await this._resolveExitCode();\n\n return {\n success: this._exitCode === 0,\n exitCode: this._exitCode ?? 1,\n stdout: this.stdout,\n stderr: this.stderr,\n executionTimeMs: Date.now() - this._startTime,\n };\n }\n\n async kill(): Promise<boolean> {\n if (this._exitCode !== undefined) return false;\n this._killed = true;\n this._exitCode = 137; // SIGKILL\n try {\n await this._sandbox.process.deleteSession(this.pid);\n } catch {\n // Session may already be gone\n }\n return true;\n }\n\n async sendStdin(data: string): Promise<void> {\n if (this._exitCode !== undefined) {\n throw new Error(`Process ${this.pid} has already exited with code ${this._exitCode}`);\n }\n await this._sandbox.process.sendSessionCommandInput(this.pid, this._cmdId, data);\n }\n}\n\n// =============================================================================\n// Daytona Process Manager\n// =============================================================================\n\nexport interface DaytonaProcessManagerOptions {\n env?: Record<string, string | undefined>;\n /** Default timeout in milliseconds for commands that don't specify one. */\n defaultTimeout?: number;\n}\n\n/**\n * Daytona implementation of SandboxProcessManager.\n * Uses the Daytona SDK's session API with one session per spawned process.\n */\nexport class DaytonaProcessManager extends SandboxProcessManager<DaytonaSandbox> {\n private _spawnCounter = 0;\n private readonly _defaultTimeout?: number;\n\n constructor(opts: DaytonaProcessManagerOptions = {}) {\n super({ env: opts.env });\n this._defaultTimeout = opts.defaultTimeout;\n }\n\n async spawn(command: string, options: SpawnProcessOptions = {}): Promise<ProcessHandle> {\n // Apply default timeout if the caller didn't specify one\n const effectiveOptions = {\n ...options,\n timeout: options.timeout ?? this._defaultTimeout,\n };\n return this.sandbox.retryOnDead(async () => {\n const sandbox = this.sandbox.daytona;\n\n // Merge default env with per-spawn env\n const mergedEnv = { ...this.env, ...effectiveOptions.env };\n const envs = Object.fromEntries(\n Object.entries(mergedEnv).filter((entry): entry is [string, string] => entry[1] !== undefined),\n );\n\n // Build command with baked-in env and cwd, wrapped in subshell\n const sessionCommand = buildSpawnCommand(command, effectiveOptions.cwd, envs);\n\n // Unique session ID per spawn — used as the PID\n const sessionId = `mastra-proc-${Date.now().toString(36)}-${++this._spawnCounter}`;\n\n await sandbox.process.createSession(sessionId);\n\n const { cmdId } = await sandbox.process.executeSessionCommand(sessionId, {\n command: sessionCommand,\n runAsync: true,\n });\n\n const handle = new DaytonaProcessHandle(sessionId, cmdId, sandbox, Date.now(), effectiveOptions);\n\n // Start streaming logs — route to handle's emitters\n const streamingPromise = sandbox.process\n .getSessionCommandLogs(\n sessionId,\n cmdId,\n (chunk: string) => handle.emitStdout(chunk),\n (chunk: string) => handle.emitStderr(chunk),\n )\n .catch(() => {\n // Stream ends when session is deleted (e.g., after kill) — swallow the error\n });\n\n handle.streamingPromise = streamingPromise;\n\n this._tracked.set(handle.pid, handle);\n return handle;\n });\n }\n\n async list(): Promise<ProcessInfo[]> {\n const result: ProcessInfo[] = [];\n for (const [pid, handle] of this._tracked) {\n result.push({\n pid,\n command: handle.command,\n running: handle.exitCode === undefined,\n exitCode: handle.exitCode,\n });\n }\n return result;\n }\n}\n\n// =============================================================================\n// Command Building\n// =============================================================================\n\n/**\n * Build a shell command string that bakes in cwd and env vars.\n * Wraps the user command in a subshell `(command)` so that:\n * - `exit N` exits the subshell, not the session shell\n * - Heredocs work correctly within the subshell\n *\n * @example\n * buildSpawnCommand('npm test', '/app', { NODE_ENV: 'test' })\n * // → \"export NODE_ENV='test' && cd '/app' && (npm test)\"\n */\nfunction buildSpawnCommand(command: string, cwd: string | undefined, envs: Record<string, string>): string {\n const parts: string[] = [];\n\n for (const [k, v] of Object.entries(envs)) {\n parts.push(`export ${k}=${shellQuote(v)}`);\n }\n\n if (cwd) {\n parts.push(`cd ${shellQuote(cwd)}`);\n }\n\n // Wrap in subshell to isolate exit codes and heredocs\n parts.push(`(${command})`);\n\n return parts.join(' && ');\n}\n","/**\n * Daytona Sandbox Provider\n *\n * A Daytona sandbox implementation for Mastra workspaces.\n * Supports command execution, environment variables, resource configuration,\n * snapshots, Daytona volumes, and FUSE-based cloud filesystem mounting (S3, GCS).\n *\n * @see https://www.daytona.io/docs\n */\n\nimport { Daytona, DaytonaError, DaytonaNotFoundError, SandboxState } from '@daytonaio/sdk';\nimport type {\n CreateSandboxFromImageParams,\n CreateSandboxFromSnapshotParams,\n Sandbox,\n VolumeMount,\n} from '@daytonaio/sdk';\nimport type {\n SandboxInfo,\n ProviderStatus,\n MastraSandboxOptions,\n WorkspaceFilesystem,\n MountResult,\n FilesystemMountConfig,\n MountManager,\n CommandResult,\n ExecuteCommandOptions,\n} from '@mastra/core/workspace';\nimport { MastraSandbox, SandboxNotReadyError } from '@mastra/core/workspace';\n\nimport { compact } from '../utils/compact';\nimport { shellQuote } from '../utils/shell-quote';\nimport { mountS3, mountGCS, LOG_PREFIX, runCommand } from './mounts';\nimport type { DaytonaMountConfig, MountContext } from './mounts';\nimport { DaytonaProcessManager } from './process-manager';\nimport type { DaytonaResources } from './types';\n\n/** Allowlist pattern for mount paths — absolute path with safe characters only. */\nconst SAFE_MOUNT_PATH = /^\\/[a-zA-Z0-9_.\\-/]+$/;\n\n/** Default timeout for mount lifecycle shell commands (mkdir, unmount, proc reads, etc.) */\nconst MOUNT_COMMAND_TIMEOUT_MS = 30_000;\n\n/** Convert an unknown error to a readable string. */\nfunction errorToString(error: unknown): string {\n if (error instanceof Error) return error.message;\n if (typeof error === 'string') return error;\n if (error && typeof error === 'object' && 'message' in error) {\n const maybeError = error as { message?: unknown };\n if (typeof maybeError.message === 'string') {\n return maybeError.message;\n }\n }\n try {\n return JSON.stringify(error);\n } catch {\n return String(error);\n }\n}\n\nfunction validateMountPath(mountPath: string): void {\n if (!SAFE_MOUNT_PATH.test(mountPath)) {\n throw new Error(\n `Invalid mount path: ${mountPath}. Must be an absolute path with alphanumeric, dash, dot, underscore, or slash characters only.`,\n );\n }\n const segments = mountPath.split('/');\n if (mountPath.includes('//') || segments.some(segment => segment === '.' || segment === '..')) {\n throw new Error(`Invalid mount path: ${mountPath}. Path traversal segments are not allowed.`);\n }\n}\n\n/** Allowlist for marker filenames from ls output — e.g. \"mount-abc123\" */\nconst SAFE_MARKER_NAME = /^mount-[a-z0-9]+$/;\n\n/** Patterns indicating the sandbox is dead/gone (@daytonaio/sdk@0.143.0). */\nconst SANDBOX_DEAD_PATTERNS: RegExp[] = [\n /sandbox is not running/i,\n /sandbox already destroyed/i,\n /sandbox.*not found/i,\n /failed to resolve container IP/i,\n /is the sandbox started/i,\n];\n\n// =============================================================================\n// Daytona Sandbox Options\n// =============================================================================\n\n/**\n * Daytona sandbox provider configuration.\n */\nexport interface DaytonaSandboxOptions extends Omit<MastraSandboxOptions, 'processes'> {\n /** Unique identifier for this sandbox instance */\n id?: string;\n /** API key for authentication. Falls back to DAYTONA_API_KEY env var. */\n apiKey?: string;\n /** API URL. Falls back to DAYTONA_API_URL env var or https://app.daytona.io/api. */\n apiUrl?: string;\n /** Target runner region. Falls back to DAYTONA_TARGET env var. */\n target?: string;\n /**\n * Default execution timeout in milliseconds.\n * @default 300_000 // 5 minutes\n */\n timeout?: number;\n /**\n * Sandbox runtime language.\n * @default 'typescript'\n */\n language?: 'typescript' | 'javascript' | 'python';\n /** Resource allocation for the sandbox */\n resources?: DaytonaResources;\n /** Environment variables to set in the sandbox */\n env?: Record<string, string>;\n /** Custom metadata labels */\n labels?: Record<string, string>;\n /** Pre-built snapshot ID to create sandbox from. Takes precedence over resources/image. */\n snapshot?: string;\n /**\n * Docker image to use for sandbox creation. When set, triggers image-based creation.\n * Can optionally be combined with `resources` for custom resource allocation.\n * Has no effect when `snapshot` is set.\n */\n image?: string;\n /**\n * Whether the sandbox should be ephemeral. If true, autoDeleteInterval will be set to 0\n * (delete immediately on stop).\n * @default false\n */\n ephemeral?: boolean;\n /**\n * Auto-stop interval in minutes (0 = disabled).\n * @default 15\n */\n autoStopInterval?: number;\n /**\n * Auto-archive interval in minutes (0 = maximum interval, which is 7 days).\n * @default 7 days\n */\n autoArchiveInterval?: number;\n /**\n * Daytona volumes to attach at creation.\n * Volumes are configured at sandbox creation time, not mounted dynamically.\n */\n volumes?: Array<VolumeMount>;\n /** Sandbox display name */\n name?: string;\n /** OS user to use for the sandbox */\n user?: string;\n /** Whether the sandbox port preview is public */\n public?: boolean;\n /**\n * Auto-delete interval in minutes (negative = disabled, 0 = delete immediately on stop).\n * @default disabled\n */\n autoDeleteInterval?: number;\n /** Whether to block all network access for the sandbox */\n networkBlockAll?: boolean;\n /** Comma-separated list of allowed CIDR network addresses for the sandbox */\n networkAllowList?: string;\n}\n\n// =============================================================================\n// Daytona Sandbox Implementation\n// =============================================================================\n\n/**\n * Daytona sandbox provider for Mastra workspaces.\n *\n * Features:\n * - Isolated cloud sandbox via Daytona SDK\n * - Multi-runtime support (TypeScript, JavaScript, Python)\n * - Resource configuration (CPU, memory, disk)\n * - Volume attachment at creation time\n * - FUSE-based cloud filesystem mounting (S3, GCS)\n * - Automatic sandbox timeout handling with retry\n *\n * @example Basic usage\n * ```typescript\n * import { Workspace } from '@mastra/core/workspace';\n * import { DaytonaSandbox } from '@mastra/daytona';\n *\n * const sandbox = new DaytonaSandbox({\n * timeout: 60000,\n * language: 'typescript',\n * });\n *\n * const workspace = new Workspace({ sandbox });\n * const result = await workspace.executeCode('console.log(\"Hello!\")');\n * ```\n *\n * @example With resources and volumes\n * ```typescript\n * const sandbox = new DaytonaSandbox({\n * resources: { cpu: 2, memory: 4, disk: 6 },\n * volumes: [{ volumeId: 'vol-123', mountPath: '/data' }],\n * env: { NODE_ENV: 'production' },\n * });\n * ```\n */\nexport class DaytonaSandbox extends MastraSandbox {\n readonly id: string;\n readonly name = 'DaytonaSandbox';\n readonly provider = 'daytona';\n\n declare readonly mounts: MountManager; // Non-optional (initialized by base class when mount() exists)\n\n status: ProviderStatus = 'pending';\n\n private _daytona: Daytona | null = null;\n private _sandbox: Sandbox | null = null;\n private _createdAt: Date | null = null;\n private _workingDir: string | null = null;\n private _isRetrying = false;\n\n private readonly timeout: number;\n private readonly language: 'typescript' | 'javascript' | 'python';\n private readonly resources?: DaytonaResources;\n private readonly env: Record<string, string>;\n private readonly labels: Record<string, string>;\n private readonly snapshotId?: string;\n private readonly image?: string;\n private readonly ephemeral: boolean;\n private readonly autoStopInterval?: number;\n private readonly autoArchiveInterval?: number;\n private readonly autoDeleteInterval?: number;\n private readonly volumeConfigs: Array<VolumeMount>;\n private readonly sandboxName?: string;\n private readonly sandboxUser?: string;\n private readonly sandboxPublic?: boolean;\n private readonly networkBlockAll?: boolean;\n private readonly networkAllowList?: string;\n private readonly connectionOpts: { apiKey?: string; apiUrl?: string; target?: string };\n\n constructor(options: DaytonaSandboxOptions = {}) {\n super({\n ...options,\n name: 'DaytonaSandbox',\n processes: new DaytonaProcessManager({\n env: options.env,\n defaultTimeout: options.timeout ?? 300_000,\n }),\n });\n\n this.id = options.id ?? this.generateId();\n this.timeout = options.timeout ?? 300_000;\n this.language = options.language ?? 'typescript';\n this.resources = options.resources;\n this.env = options.env ?? {};\n this.labels = options.labels ?? {};\n this.snapshotId = options.snapshot;\n this.image = options.image;\n this.ephemeral = options.ephemeral ?? false;\n this.autoStopInterval = options.autoStopInterval ?? 15;\n this.autoArchiveInterval = options.autoArchiveInterval;\n this.autoDeleteInterval = options.autoDeleteInterval;\n this.volumeConfigs = options.volumes ?? [];\n this.sandboxName = options.name ?? this.id;\n this.sandboxUser = options.user;\n this.sandboxPublic = options.public;\n this.networkBlockAll = options.networkBlockAll;\n this.networkAllowList = options.networkAllowList;\n\n this.connectionOpts = {\n ...(options.apiKey !== undefined && { apiKey: options.apiKey }),\n ...(options.apiUrl !== undefined && { apiUrl: options.apiUrl }),\n ...(options.target !== undefined && { target: options.target }),\n };\n }\n\n private generateId(): string {\n return `daytona-sandbox-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;\n }\n\n /**\n * Get the underlying Daytona Sandbox instance for direct access to Daytona APIs.\n *\n * Use this when you need to access Daytona features not exposed through the\n * WorkspaceSandbox interface (e.g., filesystem API, git operations, LSP).\n *\n * @throws {SandboxNotReadyError} If the sandbox has not been started\n *\n * @example Direct file operations\n * ```typescript\n * await sandbox.start();\n * const daytonaSandbox = sandbox.daytona;\n * await daytonaSandbox.fs.uploadFile(Buffer.from('Hello'), '/tmp/test.txt');\n * ```\n */\n get daytona(): Sandbox {\n if (!this._sandbox) {\n throw new SandboxNotReadyError(this.id);\n }\n return this._sandbox;\n }\n\n /** @deprecated Use `daytona` instead. */\n get instance(): Sandbox {\n return this.daytona;\n }\n\n // ---------------------------------------------------------------------------\n // Lifecycle\n // ---------------------------------------------------------------------------\n\n /**\n * Start the Daytona sandbox.\n * Reconnects to an existing sandbox with the same logical ID if one exists,\n * otherwise creates a new sandbox instance.\n */\n async start(): Promise<void> {\n if (this._sandbox) {\n return;\n }\n\n // Create Daytona client if not exists\n if (!this._daytona) {\n this._daytona = new Daytona(this.connectionOpts);\n }\n\n // Try to reconnect to an existing sandbox with the same logical ID\n const existing = await this.findExistingSandbox();\n if (existing) {\n this._sandbox = existing;\n this._createdAt = existing.createdAt ? new Date(existing.createdAt) : new Date();\n this.logger.debug(`${LOG_PREFIX} Reconnected to existing sandbox ${existing.id} for: ${this.id}`);\n\n // Reconcile FUSE mounts — clean up stale mounts from a previous session\n const expectedPaths = Array.from(this.mounts.entries.keys());\n this.logger.debug(`${LOG_PREFIX} Running mount reconciliation...`);\n await this.reconcileMounts(expectedPaths);\n this.logger.debug(`${LOG_PREFIX} Mount reconciliation complete`);\n await this.detectWorkingDir();\n return;\n }\n\n this.logger.debug(`${LOG_PREFIX} Creating sandbox for: ${this.id}`);\n\n // Base params shared by both creation modes\n const baseParams = compact({\n language: this.language,\n labels: { ...this.labels, 'mastra-sandbox-id': this.id },\n ephemeral: this.ephemeral,\n autoStopInterval: this.autoStopInterval,\n autoArchiveInterval: this.autoArchiveInterval,\n autoDeleteInterval: this.autoDeleteInterval,\n volumes: this.volumeConfigs.length > 0 ? this.volumeConfigs : undefined,\n name: this.sandboxName,\n user: this.sandboxUser,\n public: this.sandboxPublic,\n networkBlockAll: this.networkBlockAll,\n networkAllowList: this.networkAllowList,\n });\n\n // Snapshot takes precedence. Image alone (with optional resources) triggers image-based creation.\n // Resources without image fall back to snapshot-based creation (resources are ignored).\n if (this.resources && !this.image) {\n this.logger.warn(\n `${LOG_PREFIX} 'resources' option requires 'image' to take effect — falling back to snapshot-based creation without custom resources`,\n );\n }\n\n const createParams: CreateSandboxFromSnapshotParams | CreateSandboxFromImageParams =\n this.image && !this.snapshotId\n ? (compact({\n ...baseParams,\n image: this.image,\n resources: this.resources,\n }) satisfies CreateSandboxFromImageParams)\n : (compact({ ...baseParams, snapshot: this.snapshotId }) satisfies CreateSandboxFromSnapshotParams);\n\n // Create sandbox\n this._sandbox = await this._daytona.create(createParams);\n\n this.logger.debug(`${LOG_PREFIX} Created sandbox ${this._sandbox.id} for logical ID: ${this.id}`);\n this._createdAt = new Date();\n await this.detectWorkingDir();\n }\n\n /**\n * Stop the Daytona sandbox.\n * Unmounts all filesystems, then stops the sandbox.\n */\n async stop(): Promise<void> {\n for (const mountPath of [...this.mounts.entries.keys()]) {\n try {\n await this.unmount(mountPath);\n } catch {\n // Best-effort unmount; sandbox may already be dead\n }\n }\n\n if (this._sandbox && this._daytona) {\n try {\n await this._daytona.stop(this._sandbox);\n } catch {\n // Best-effort stop; sandbox may already be stopped\n }\n }\n this._sandbox = null;\n }\n\n /**\n * Destroy the Daytona sandbox and clean up all resources.\n * Deletes the sandbox and clears all state.\n */\n async destroy(): Promise<void> {\n if (this._sandbox && this._daytona) {\n try {\n await this._daytona.delete(this._sandbox);\n } catch {\n // Ignore errors during cleanup\n }\n } else if (!this._sandbox && this._daytona) {\n // Orphan cleanup: _start() may have failed after the SDK created\n // a server-side sandbox (e.g. bad image → BUILD_FAILED).\n // Try to find and delete it so it doesn't leak.\n try {\n const orphan = await this._daytona.findOne({ labels: { 'mastra-sandbox-id': this.id } });\n if (orphan) {\n await this._daytona.delete(orphan);\n }\n } catch {\n // Best-effort — orphan may not exist or may already be gone\n }\n }\n\n this._sandbox = null;\n this._daytona = null;\n this.mounts?.clear();\n }\n\n /**\n * Check if the sandbox is ready for operations.\n */\n async isReady(): Promise<boolean> {\n return this.status === 'running' && this._sandbox !== null;\n }\n\n /**\n * Get information about the current state of the sandbox.\n */\n async getInfo(): Promise<SandboxInfo> {\n return {\n id: this.id,\n name: this.name,\n provider: this.provider,\n status: this.status,\n createdAt: this._createdAt ?? new Date(),\n mounts: this.mounts\n ? Array.from(this.mounts.entries).map(([path, entry]) => ({\n path,\n filesystem: entry.filesystem?.provider ?? entry.config?.type ?? 'unknown',\n }))\n : [],\n ...(this._sandbox && {\n resources: {\n cpuCores: this._sandbox.cpu,\n memoryMB: this._sandbox.memory * 1024,\n diskMB: this._sandbox.disk * 1024,\n },\n }),\n metadata: {\n language: this.language,\n ephemeral: this.ephemeral,\n ...(this.snapshotId && { snapshot: this.snapshotId }),\n ...(this.image && { image: this.image }),\n ...(this._sandbox && { target: this._sandbox.target }),\n },\n };\n }\n\n /**\n * Get instructions describing this Daytona sandbox.\n * Used by agents to understand the execution environment.\n */\n getInstructions(): string {\n const parts: string[] = [];\n\n const mountCount = this.mounts.entries.size;\n const mountInfo = mountCount > 0 ? ` ${mountCount} filesystem(s) mounted via FUSE.` : '';\n parts.push(`Cloud sandbox with isolated execution (${this.language} runtime).${mountInfo}`);\n\n if (this._workingDir) {\n parts.push(`Default working directory: ${this._workingDir}.`);\n }\n\n parts.push(`Command timeout: ${Math.ceil(this.timeout / 1000)}s.`);\n\n parts.push(`Running as user: ${this.sandboxUser ?? 'daytona'}.`);\n\n if (this.volumeConfigs.length > 0) {\n parts.push(`${this.volumeConfigs.length} volume(s) attached.`);\n }\n\n if (this.networkBlockAll) {\n parts.push(`Network access is blocked.`);\n }\n\n return parts.join(' ');\n }\n\n // ---------------------------------------------------------------------------\n // Command Execution\n // ---------------------------------------------------------------------------\n\n /**\n * Execute a command in the sandbox and return the result.\n */\n async executeCommand(\n command: string,\n args: string[] = [],\n options: ExecuteCommandOptions = {},\n ): Promise<CommandResult> {\n await this.ensureRunning();\n const fullCommand = args.length > 0 ? `${command} ${args.map(shellQuote).join(' ')}` : command;\n const handle = await this.processes!.spawn(fullCommand, options);\n const result = await handle.wait();\n return { ...result, command, args };\n }\n\n // ---------------------------------------------------------------------------\n // Mount Support\n // ---------------------------------------------------------------------------\n\n /**\n * Mount a filesystem at a path in the sandbox.\n * Uses FUSE tools (s3fs, gcsfuse) to mount cloud storage.\n */\n async mount(filesystem: WorkspaceFilesystem, mountPath: string): Promise<MountResult> {\n validateMountPath(mountPath);\n\n if (!this._sandbox) {\n throw new SandboxNotReadyError(this.id);\n }\n const sandbox = this._sandbox;\n\n this.logger.debug(`${LOG_PREFIX} Mounting \"${mountPath}\"...`);\n\n // Get mount config - MountManager validates this exists before calling mount()\n const config = filesystem.getMountConfig?.() as DaytonaMountConfig | undefined;\n if (!config) {\n const error = `Filesystem \"${filesystem.id}\" does not provide a mount config`;\n this.logger.error(`${LOG_PREFIX} ${error}`);\n this.mounts.set(mountPath, { filesystem, state: 'error', error });\n return { success: false, mountPath, error };\n }\n\n // Check if already mounted with matching config (e.g., when reconnecting to existing sandbox)\n const existingMount = await this.checkExistingMount(mountPath, config);\n if (existingMount === 'matching') {\n this.logger.debug(\n `${LOG_PREFIX} Detected existing mount for ${filesystem.provider} (\"${filesystem.id}\") at \"${mountPath}\" with correct config, skipping`,\n );\n this.mounts.set(mountPath, { state: 'mounted', config });\n return { success: true, mountPath };\n } else if (existingMount === 'mismatched') {\n // Different config - unmount and re-mount\n this.logger.debug(`${LOG_PREFIX} Config mismatch at \"${mountPath}\", unmounting to re-mount with new config...`);\n await this.unmount(mountPath);\n } else if (existingMount === 'unmanaged') {\n const error = `Mount path \"${mountPath}\" is already mounted by an unmanaged source`;\n this.logger.error(`${LOG_PREFIX} ${error}`);\n this.mounts.set(mountPath, { filesystem, state: 'error', config, error });\n return { success: false, mountPath, error };\n }\n\n // Mark as mounting (handles direct mount() calls; MountManager also sets this for processPending)\n this.mounts.set(mountPath, { filesystem, state: 'mounting', config });\n this.logger.debug(`${LOG_PREFIX} Config type: ${config.type}`);\n\n // Reject non-empty directories — mounting would shadow existing files.\n // Skip the check if the path is already a mount point (stuck FUSE from a failed\n // prior unmount): its contents are remote objects, not local files to protect.\n try {\n const quotedPath = shellQuote(mountPath);\n const checkResult = await runCommand(\n sandbox,\n `[ -d ${quotedPath} ] && ! mountpoint -q ${quotedPath} 2>/dev/null && ` +\n `[ \"$(ls -A ${quotedPath} 2>/dev/null)\" ] && echo \"non-empty\" || echo \"ok\"`,\n { timeout: MOUNT_COMMAND_TIMEOUT_MS },\n );\n if (checkResult.output.trim() === 'non-empty') {\n const error = `Cannot mount at ${mountPath}: directory exists and is not empty. Mounting would hide existing files. Use a different path or empty the directory first.`;\n this.logger.error(`${LOG_PREFIX} ${error}`);\n this.mounts.set(mountPath, { filesystem, state: 'error', config, error });\n return { success: false, mountPath, error };\n }\n } catch {\n // Check failed, proceed anyway\n }\n\n // Create/prepare the mount directory.\n // If the path is already a FUSE mount (stuck from a failed prior unmount), overlay\n // it with a tmpfs first. New FUSE-on-existing-FUSE fails because the kernel asks the\n // existing daemon to resolve the mount point path, which returns ENOENT. A tmpfs\n // overlay is kernel-native and doesn't involve the FUSE driver.\n this.logger.debug(`${LOG_PREFIX} Creating mount directory for \"${mountPath}\"...`);\n try {\n const quotedPath = shellQuote(mountPath);\n const mkdirResult = await runCommand(\n sandbox,\n `mountpoint -q ${quotedPath} 2>/dev/null && sudo mount -t tmpfs tmpfs ${quotedPath} 2>/dev/null; ` +\n `sudo mkdir -p ${quotedPath} 2>/dev/null; ` +\n `sudo chown $(id -u):$(id -g) ${quotedPath}`,\n { timeout: MOUNT_COMMAND_TIMEOUT_MS },\n );\n if (mkdirResult.exitCode !== 0) {\n const error = mkdirResult.output || 'Failed to create mount directory';\n this.logger.debug(`${LOG_PREFIX} mkdir error for \"${mountPath}\":`, error);\n this.mounts.set(mountPath, { filesystem, state: 'error', config, error });\n return { success: false, mountPath, error };\n }\n } catch (err) {\n const error = `Failed to create mount directory: ${err}`;\n this.mounts.set(mountPath, { filesystem, state: 'error', config, error });\n return { success: false, mountPath, error };\n }\n\n // Build mount context for SDK-agnostic mount helpers\n const mountCtx: MountContext = {\n run: async (cmd, timeoutMs) => {\n const result = await runCommand(sandbox, cmd, timeoutMs !== undefined ? { timeout: timeoutMs } : undefined);\n return {\n exitCode: result.exitCode,\n stdout: result.output,\n stderr: result.exitCode !== 0 ? result.output : '',\n };\n },\n writeFile: async (path, content) => {\n await sandbox.fs.uploadFile(Buffer.from(content), path);\n },\n logger: this.logger,\n };\n\n try {\n switch (config.type) {\n case 's3':\n this.logger.debug(`${LOG_PREFIX} Mounting S3 at \"${mountPath}\"...`);\n await mountS3(mountPath, config, mountCtx);\n this.logger.debug(`${LOG_PREFIX} Mounted S3 bucket at ${mountPath}`);\n break;\n case 'gcs':\n this.logger.debug(`${LOG_PREFIX} Mounting GCS at \"${mountPath}\"...`);\n await mountGCS(mountPath, config, mountCtx);\n this.logger.debug(`${LOG_PREFIX} Mounted GCS bucket at ${mountPath}`);\n break;\n default: {\n const error = `Unsupported mount type: ${(config as FilesystemMountConfig).type}`;\n this.mounts.set(mountPath, { filesystem, state: 'unsupported', config, error });\n return { success: false, mountPath, error };\n }\n }\n } catch (error) {\n this.logger.error(\n `${LOG_PREFIX} Error mounting \"${filesystem.provider}\" (${filesystem.id}) at \"${mountPath}\":`,\n error,\n );\n this.mounts.set(mountPath, { filesystem, state: 'error', config, error: errorToString(error) });\n\n // Clean up the directory we created since mount failed\n await runCommand(sandbox, `sudo rmdir ${shellQuote(mountPath)} 2>/dev/null || true`, {\n timeout: MOUNT_COMMAND_TIMEOUT_MS,\n });\n this.logger.debug(`${LOG_PREFIX} Cleaned up directory after failed mount: ${mountPath}`);\n return { success: false, mountPath, error: errorToString(error) };\n }\n\n // Mark as mounted\n this.mounts.set(mountPath, { state: 'mounted', config });\n\n // Write marker file so we can detect config changes on reconnect\n await this.writeMarkerFile(mountPath);\n\n this.logger.debug(`${LOG_PREFIX} Mounted \"${mountPath}\"`);\n return { success: true, mountPath };\n }\n\n /**\n * Unmount a filesystem from a path in the sandbox.\n */\n async unmount(mountPath: string): Promise<void> {\n validateMountPath(mountPath);\n\n if (!this._sandbox) {\n throw new SandboxNotReadyError(this.id);\n }\n const sandbox = this._sandbox;\n\n this.logger.debug(`${LOG_PREFIX} Unmounting \"${mountPath}\"...`);\n\n // Try fusermount first (user-space), then lazy umount as fallback.\n // Do NOT pkill the FUSE daemon — a killed daemon leaves a stale mount\n // (ENOTCONN) that blocks subsequent mkdir/stat on the path.\n const quotedPath = shellQuote(mountPath);\n await runCommand(\n sandbox,\n `sudo fusermount -u ${quotedPath} 2>/dev/null; ` +\n `sudo umount -l ${quotedPath} 2>/dev/null; ` +\n // Last resort: move a stuck FUSE mount aside so the directory can be cleaned up.\n `mountpoint -q ${quotedPath} 2>/dev/null && ` +\n `{ _p=\"/tmp/.mastra-defunct-$$\"; sudo mkdir -p \"$_p\" && sudo mount --move ${quotedPath} \"$_p\" 2>/dev/null; sudo umount -l \"$_p\" 2>/dev/null; sudo rmdir \"$_p\" 2>/dev/null; }`,\n { timeout: MOUNT_COMMAND_TIMEOUT_MS },\n );\n\n this.mounts.delete(mountPath);\n\n // Clean up marker file and mount directory in one round-trip.\n // rm -f always exits 0, so the combined exit code reflects rmdir.\n const markerPath = `/tmp/.mastra-mounts/${this.mounts.markerFilename(mountPath)}`;\n const rmdirResult = await runCommand(\n sandbox,\n `rm -f ${shellQuote(markerPath)} 2>/dev/null; sudo rmdir ${quotedPath} 2>&1`,\n {\n timeout: MOUNT_COMMAND_TIMEOUT_MS,\n },\n );\n if (rmdirResult.exitCode === 0) {\n this.logger.debug(`${LOG_PREFIX} Unmounted and removed ${mountPath}`);\n } else {\n this.logger.debug(\n `${LOG_PREFIX} Unmounted ${mountPath} (directory not removed: ${rmdirResult.output.trim() || 'not empty'})`,\n );\n }\n }\n\n /**\n * Unmount all stale mounts that are not in the expected mounts list.\n * Also cleans up orphaned directories and marker files from failed mount attempts.\n * Call this after reconnecting to an existing sandbox to clean up old mounts.\n */\n async reconcileMounts(expectedMountPaths: string[]): Promise<void> {\n if (!this._sandbox) return;\n const sandbox = this._sandbox;\n\n this.logger.debug(`${LOG_PREFIX} Reconciling mounts. Expected paths:`, expectedMountPaths);\n\n // Get current FUSE mounts\n let currentMounts: string[] = [];\n try {\n const mountsResult = await runCommand(\n sandbox,\n `grep -E 'fuse\\\\.(s3fs|gcsfuse)' /proc/mounts | awk '{print $2}'`,\n { timeout: MOUNT_COMMAND_TIMEOUT_MS },\n );\n currentMounts = mountsResult.output\n .trim()\n .split('\\n')\n .filter(p => p.length > 0);\n } catch (err) {\n this.logger.debug(`${LOG_PREFIX} Could not read /proc/mounts: ${err}`);\n return;\n }\n\n this.logger.debug(`${LOG_PREFIX} Current FUSE mounts in sandbox:`, currentMounts);\n\n // Read our marker files to know which mounts WE created\n let markerFiles: string[] = [];\n try {\n const markersResult = await runCommand(sandbox, 'ls /tmp/.mastra-mounts/ 2>/dev/null || echo \"\"', {\n timeout: MOUNT_COMMAND_TIMEOUT_MS,\n });\n markerFiles = markersResult.output\n .trim()\n .split('\\n')\n .filter(f => f.length > 0 && SAFE_MARKER_NAME.test(f));\n } catch (err) {\n this.logger.debug(`${LOG_PREFIX} Could not read marker files: ${err}`);\n }\n\n // Build a map of mount paths -> marker filenames for mounts WE created\n const managedMountPaths = new Map<string, string>();\n for (const markerFile of markerFiles) {\n const markerResult = await runCommand(sandbox, `cat \"/tmp/.mastra-mounts/${markerFile}\" 2>/dev/null || echo \"\"`, {\n timeout: MOUNT_COMMAND_TIMEOUT_MS,\n });\n const parsed = this.mounts.parseMarkerContent(markerResult.output.trim());\n if (parsed && SAFE_MOUNT_PATH.test(parsed.path)) {\n managedMountPaths.set(parsed.path, markerFile);\n }\n }\n\n // Find mounts that exist but shouldn't — only unmount if WE created them (have a marker)\n const staleMounts = currentMounts.filter(path => !expectedMountPaths.includes(path));\n\n for (const stalePath of staleMounts) {\n if (managedMountPaths.has(stalePath)) {\n this.logger.debug(`${LOG_PREFIX} Found stale managed FUSE mount at \"${stalePath}\", unmounting...`);\n try {\n await this.unmount(stalePath);\n } catch (err) {\n this.logger.debug(`${LOG_PREFIX} Failed to unmount stale mount at \"${stalePath}\": ${err}`);\n }\n } else {\n this.logger.debug(`${LOG_PREFIX} Found external FUSE mount at \"${stalePath}\", leaving untouched`);\n }\n }\n\n // Clean up orphaned marker files and empty directories from failed mounts\n try {\n const expectedMarkerFiles = new Set(expectedMountPaths.map(p => this.mounts.markerFilename(p)));\n\n // Build a reverse map: markerFile -> mountPath\n const markerToPath = new Map<string, string>();\n for (const [path, file] of managedMountPaths) {\n markerToPath.set(file, path);\n }\n\n for (const markerFile of markerFiles) {\n // If this marker file doesn't correspond to an expected mount path, clean it up\n if (!expectedMarkerFiles.has(markerFile)) {\n const mountPath = markerToPath.get(markerFile);\n\n if (mountPath) {\n // Only clean up directory if not currently FUSE mounted\n if (!currentMounts.includes(mountPath)) {\n this.logger.debug(`${LOG_PREFIX} Cleaning up orphaned marker and directory for ${mountPath}`);\n await runCommand(\n sandbox,\n `rm -f \"/tmp/.mastra-mounts/${markerFile}\" 2>/dev/null; sudo rmdir ${shellQuote(mountPath)} 2>/dev/null`,\n { timeout: MOUNT_COMMAND_TIMEOUT_MS },\n );\n }\n } else {\n // Malformed marker file - just delete it\n this.logger.debug(`${LOG_PREFIX} Removing malformed marker file: ${markerFile}`);\n await runCommand(sandbox, `rm -f \"/tmp/.mastra-mounts/${markerFile}\" 2>/dev/null || true`, {\n timeout: MOUNT_COMMAND_TIMEOUT_MS,\n });\n }\n }\n }\n } catch {\n // Ignore errors during orphan cleanup\n this.logger.debug(`${LOG_PREFIX} Error during orphan cleanup (non-fatal)`);\n }\n }\n\n /**\n * Write marker file for detecting config changes on reconnect.\n * Stores both the mount path and config hash in the file.\n */\n private async writeMarkerFile(mountPath: string): Promise<void> {\n if (!this._sandbox) return;\n\n const markerContent = this.mounts.getMarkerContent(mountPath);\n if (!markerContent) return;\n\n const filename = this.mounts.markerFilename(mountPath);\n const markerPath = `/tmp/.mastra-mounts/${filename}`;\n try {\n await runCommand(this._sandbox, 'mkdir -p /tmp/.mastra-mounts', { timeout: MOUNT_COMMAND_TIMEOUT_MS });\n await this._sandbox.fs.uploadFile(Buffer.from(markerContent, 'utf-8'), markerPath);\n } catch {\n // Non-fatal - marker is just for optimization\n this.logger.debug(`${LOG_PREFIX} Warning: Could not write marker file at ${markerPath}`);\n }\n }\n\n /**\n * Check if a path is already mounted and whether the config matches.\n *\n * @param mountPath - The mount path to check\n * @param newConfig - The new config to compare against the stored config\n * @returns 'not_mounted' | 'matching' | 'mismatched' | 'unmanaged'\n */\n private async checkExistingMount(\n mountPath: string,\n newConfig: DaytonaMountConfig,\n ): Promise<'not_mounted' | 'matching' | 'mismatched' | 'unmanaged'> {\n if (!this._sandbox) throw new SandboxNotReadyError(this.id);\n const sandbox = this._sandbox;\n\n // Check if path is a mount point\n try {\n const mountCheck = await runCommand(\n sandbox,\n `mountpoint -q ${shellQuote(mountPath)} && echo \"mounted\" || echo \"not mounted\"`,\n { timeout: MOUNT_COMMAND_TIMEOUT_MS },\n );\n if (mountCheck.output.trim() !== 'mounted') {\n return 'not_mounted';\n }\n } catch {\n return 'not_mounted';\n }\n\n // Path is mounted — check if config matches via marker file\n const filename = this.mounts.markerFilename(mountPath);\n const markerPath = `/tmp/.mastra-mounts/${filename}`;\n let parsed;\n try {\n const markerResult = await runCommand(sandbox, `cat ${shellQuote(markerPath)} 2>/dev/null || echo \"\"`, {\n timeout: MOUNT_COMMAND_TIMEOUT_MS,\n });\n parsed = this.mounts.parseMarkerContent(markerResult.output.trim());\n } catch {\n // Marker doesn't exist or can't be read - treat as unmanaged\n return 'unmanaged';\n }\n\n if (!parsed) return 'unmanaged';\n\n // Compute hash of the NEW config and compare with stored hash\n const newConfigHash = this.mounts.computeConfigHash(newConfig);\n this.logger.debug(\n `${LOG_PREFIX} Marker check - stored hash: \"${parsed.configHash}\", new config hash: \"${newConfigHash}\"`,\n );\n\n if (parsed.path === mountPath && parsed.configHash === newConfigHash) {\n return 'matching';\n }\n\n return 'mismatched';\n }\n\n // ---------------------------------------------------------------------------\n // Internal Helpers\n // ---------------------------------------------------------------------------\n\n /**\n * Try to find and reconnect to an existing Daytona sandbox.\n *\n * Uses two strategies:\n * 1. `get()` by sandbox name — calls the getSandbox API directly, which\n * returns sandboxes in ANY state (including stopped). This is the\n * primary path and fixes reconnection after stop/start cycles.\n * 2. `findOne()` by label — falls back to label-based search. Note: the\n * SDK's list() API only returns started sandboxes by default (no states\n * param in v0.143.0), so this only finds running sandboxes.\n *\n * Returns the sandbox if found and usable, or null if a fresh one should\n * be created.\n */\n private async detectWorkingDir(): Promise<void> {\n if (!this._sandbox) return;\n try {\n const result = await runCommand(this._sandbox, 'pwd', { timeout: MOUNT_COMMAND_TIMEOUT_MS });\n const dir = result.output?.trim();\n if (dir) {\n this._workingDir = dir;\n this.logger.debug(`${LOG_PREFIX} Detected working directory: ${dir}`);\n }\n } catch {\n this.logger.debug(`${LOG_PREFIX} Could not detect working directory, will omit from instructions`);\n }\n }\n\n private async findExistingSandbox(): Promise<Sandbox | null> {\n const DEAD_STATES: SandboxState[] = [\n SandboxState.DESTROYED,\n SandboxState.DESTROYING,\n SandboxState.ERROR,\n SandboxState.BUILD_FAILED,\n ];\n\n let sandbox: Sandbox | null = null;\n\n // Strategy 1: lookup by name (works for stopped sandboxes)\n if (this.sandboxName) {\n try {\n sandbox = await this._daytona!.get(this.sandboxName);\n } catch (error) {\n if (error instanceof DaytonaNotFoundError) {\n // Not found by name — fall through to label lookup\n } else if (error instanceof DaytonaError && (error.statusCode === 401 || error.statusCode === 403)) {\n throw error; // Auth failure — propagate immediately\n } else {\n // Transient/network error (ETIMEDOUT, 5xx, etc.) — fall through\n this.logger.debug(`${LOG_PREFIX} Transient error looking up sandbox by name: ${error}`);\n }\n }\n }\n\n // Strategy 2: fallback to label-based lookup\n if (!sandbox) {\n try {\n sandbox = await this._daytona!.findOne({ labels: { 'mastra-sandbox-id': this.id } });\n } catch (error) {\n if (\n error instanceof DaytonaNotFoundError ||\n (error instanceof Error && error.message.includes('No sandbox found'))\n ) {\n // Not found by label either — create a fresh sandbox\n return null;\n }\n if (error instanceof DaytonaError && (error.statusCode === 401 || error.statusCode === 403)) {\n throw error; // Auth failure — propagate immediately\n }\n // Transient/network error — fall through to create fresh sandbox\n this.logger.debug(`${LOG_PREFIX} Transient error looking up sandbox by label: ${error}`);\n return null;\n }\n }\n\n const state = sandbox.state;\n\n if (state && DEAD_STATES.includes(state)) {\n this.logger.debug(`${LOG_PREFIX} Existing sandbox ${sandbox.id} is dead (${state}), deleting and creating fresh`);\n try {\n await this._daytona!.delete(sandbox);\n } catch {\n // Best-effort cleanup of dead sandbox\n }\n return null;\n }\n\n if (state !== SandboxState.STARTED) {\n this.logger.debug(`${LOG_PREFIX} Restarting sandbox ${sandbox.id} (state: ${state})`);\n await this.waitForStableStateAndStart(sandbox);\n }\n\n return sandbox;\n }\n\n /**\n * Transitional states where the Daytona API will reject start() with\n * \"State change in progress\". We poll until the sandbox reaches a stable\n * state before attempting start().\n */\n private static readonly TRANSITIONAL_STATES: SandboxState[] = [\n SandboxState.STARTING,\n SandboxState.STOPPING,\n SandboxState.CREATING,\n SandboxState.RESTORING,\n SandboxState.ARCHIVING,\n SandboxState.RESIZING,\n SandboxState.PULLING_SNAPSHOT,\n SandboxState.BUILDING_SNAPSHOT,\n ];\n\n /**\n * Wait for the sandbox to leave a transitional state, then start it if needed.\n * Polls every 2s for up to 120s. If the sandbox reaches STARTED on its own\n * (e.g. it was STARTING), we skip the start() call. If start() still fails\n * with \"State change in progress\", we retry with backoff.\n */\n private async waitForStableStateAndStart(sandbox: Sandbox): Promise<void> {\n const MAX_WAIT_MS = 120_000;\n const POLL_INTERVAL_MS = 2_000;\n const deadline = Date.now() + MAX_WAIT_MS;\n\n let current = sandbox;\n\n // Phase 1: Poll until the reported state is no longer transitional\n while (current.state && DaytonaSandbox.TRANSITIONAL_STATES.includes(current.state) && Date.now() < deadline) {\n this.logger.debug(`${LOG_PREFIX} Sandbox ${current.id} is in transitional state (${current.state}), waiting...`);\n await new Promise(r => setTimeout(r, POLL_INTERVAL_MS));\n current = await this._daytona!.get(current.id);\n }\n\n if (current.state === SandboxState.STARTED) {\n // Reached STARTED on its own — update the reference and return\n Object.assign(sandbox, current);\n return;\n }\n\n // Phase 2: Attempt start() with retries for \"State change in progress\"\n while (Date.now() < deadline) {\n try {\n await this._daytona!.start(current);\n return;\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n if (msg.includes('State change in progress') && Date.now() < deadline) {\n this.logger.debug(`${LOG_PREFIX} start() returned \"State change in progress\", retrying...`);\n await new Promise(r => setTimeout(r, POLL_INTERVAL_MS));\n current = await this._daytona!.get(current.id);\n if (current.state === SandboxState.STARTED) {\n Object.assign(sandbox, current);\n return;\n }\n continue;\n }\n throw error;\n }\n }\n\n // Last-ditch attempt after deadline\n await this._daytona!.start(current);\n }\n\n /**\n * Check if an error indicates the sandbox is dead/gone.\n * Uses DaytonaNotFoundError from the SDK when available,\n * with string fallback for edge cases.\n *\n * String patterns observed in @daytonaio/sdk@0.143.0 error messages.\n * Update if SDK error messages change in future versions.\n */\n private isSandboxDeadError(error: unknown): boolean {\n if (!error) return false;\n if (error instanceof DaytonaNotFoundError) return true;\n const errorStr = String(error);\n return SANDBOX_DEAD_PATTERNS.some(pattern => pattern.test(errorStr));\n }\n\n /**\n * Handle sandbox timeout by clearing the instance and resetting state.\n */\n private handleSandboxTimeout(): void {\n this._sandbox = null;\n\n // Reset mounted entries to pending so they get re-mounted on restart\n if (this.mounts) {\n for (const [path, entry] of this.mounts.entries) {\n if (entry.state === 'mounted' || entry.state === 'mounting') {\n this.mounts.set(path, { state: 'pending' });\n }\n }\n }\n\n this.status = 'stopped';\n }\n\n // ---------------------------------------------------------------------------\n // Retry on Dead\n // ---------------------------------------------------------------------------\n\n /**\n * Execute a function, retrying once if the sandbox is found to be dead.\n * Used by DaytonaProcessManager to handle stale sandboxes transparently.\n */\n async retryOnDead<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n if (this.isSandboxDeadError(error) && !this._isRetrying) {\n this.handleSandboxTimeout();\n this._isRetrying = true;\n try {\n await this.ensureRunning();\n return await fn();\n } finally {\n this._isRetrying = false;\n }\n }\n throw error;\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/utils/compact.ts","../src/utils/shell-quote.ts","../src/sandbox/mounts/types.ts","../src/sandbox/mounts/s3.ts","../src/sandbox/mounts/gcs.ts","../src/sandbox/process-manager.ts","../src/sandbox/index.ts"],"names":["createHash","ProcessHandle","SandboxProcessManager","MastraSandbox","SandboxNotReadyError","Daytona","SandboxState","DaytonaNotFoundError"],"mappings":";;;;;;;;;AAGO,SAAS,QAA0B,GAAA,EAAW;AACnD,EAAA,OAAO,MAAA,CAAO,WAAA,CAAY,MAAA,CAAO,OAAA,CAAQ,GAAG,CAAA,CAAE,MAAA,CAAO,CAAC,GAAG,CAAC,CAAA,KAAM,CAAA,KAAM,MAAS,CAAC,CAAA;AAClF;;;ACCO,SAAS,WAAW,GAAA,EAAqB;AAE9C,EAAA,IAAI,wBAAA,CAAyB,IAAA,CAAK,GAAG,CAAA,EAAG,OAAO,GAAA;AAE/C,EAAA,OAAO,GAAA,GAAM,GAAA,CAAI,OAAA,CAAQ,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K,MAAA,GAAS,SAAA;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,MAAM,YAAe,EAAA,EAAkC;AACrD,IAAA,IAAI;AACF,MAAA,OAAO,MAAM,EAAA,EAAG;AAAA,IAClB,SAAS,KAAA,EAAO;AACd,MAAA,IAAI,KAAK,kBAAA,CAAmB,KAAK,CAAA,IAAK,CAAC,KAAK,WAAA,EAAa;AACvD,QAAA,IAAA,CAAK,oBAAA,EAAqB;AAC1B,QAAA,IAAA,CAAK,WAAA,GAAc,IAAA;AACnB,QAAA,IAAI;AACF,UAAA,MAAM,KAAK,aAAA,EAAc;AACzB,UAAA,OAAO,MAAM,EAAA,EAAG;AAAA,QAClB,CAAA,SAAE;AACA,UAAA,IAAA,CAAK,WAAA,GAAc,KAAA;AAAA,QACrB;AAAA,MACF;AACA,MAAA,MAAM,KAAA;AAAA,IACR;AAAA,EACF;AACF","file":"index.cjs","sourcesContent":["/**\n * Returns a shallow copy of the object with all undefined values removed.\n */\nexport function compact<T extends object>(obj: T): T {\n return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined)) as T;\n}\n","/**\n * Shell-quote a single argument for safe use in a command string.\n *\n * Arguments containing only safe characters are returned as-is.\n * All others are wrapped in single quotes with embedded single quotes escaped.\n */\nexport function shellQuote(arg: string): string {\n // Safe characters that don't need quoting\n if (/^[a-zA-Z0-9._\\-/@:=]+$/.test(arg)) return arg;\n // Wrap in single quotes, escaping any embedded single quotes\n return \"'\" + arg.replace(/'/g, \"'\\\\''\") + \"'\";\n}\n","/**\n * Shared types for Daytona mount operations.\n */\n\nimport type { Sandbox } from '@daytonaio/sdk';\n\nimport type { DaytonaGCSMountConfig } from './gcs';\nimport type { DaytonaS3MountConfig } from './s3';\n\nexport const LOG_PREFIX = '[@mastra/daytona]';\n\n/**\n * Union of mount configs supported by Daytona sandbox.\n */\nexport type DaytonaMountConfig = DaytonaS3MountConfig | DaytonaGCSMountConfig;\n\n/**\n * Context for mount operations.\n * Abstracts over the Daytona SDK so mount helpers stay SDK-agnostic.\n */\nexport interface MountContext {\n run: (cmd: string, timeoutMs?: number) => Promise<{ exitCode: number; stdout: string; stderr: string }>;\n writeFile: (path: string, content: string) => Promise<void>;\n logger: {\n debug: (message: string, ...args: unknown[]) => void;\n info: (message: string, ...args: unknown[]) => void;\n warn: (message: string, ...args: unknown[]) => void;\n error: (message: string, ...args: unknown[]) => void;\n };\n}\n\n/**\n * Validate a bucket name before interpolating into shell commands.\n * Covers S3, GCS, and S3-compatible (R2, MinIO) naming rules.\n */\nconst SAFE_BUCKET_NAME = /^[a-z0-9][a-z0-9.\\-]{1,61}[a-z0-9]$/;\n\nexport function validateBucketName(bucket: string): void {\n if (!SAFE_BUCKET_NAME.test(bucket)) {\n throw new Error(\n `Invalid bucket name: \"${bucket}\". Bucket names must be 3-63 characters, lowercase alphanumeric, hyphens, or dots.`,\n );\n }\n}\n\n/**\n * Validate an endpoint URL before interpolating into shell commands.\n * Only http and https schemes are allowed.\n */\nexport function validateEndpoint(endpoint: string): void {\n let parsed: URL;\n try {\n parsed = new URL(endpoint);\n } catch {\n throw new Error(`Invalid endpoint URL: \"${endpoint}\"`);\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new Error(`Invalid endpoint URL scheme: \"${parsed.protocol}\". Only http: and https: are allowed.`);\n }\n}\n\n/**\n * Result of running a command in the Daytona sandbox.\n *\n * Note: Daytona's `executeCommand` returns a single combined string (stdout + stderr).\n * There is no separate stderr stream. If you need stderr isolated, redirect it in the\n * shell command itself (e.g. `2>/dev/null` or `2>&1`).\n */\nexport interface CommandResult {\n exitCode: number;\n /** Combined stdout/stderr output from the command. */\n output: string;\n}\n\n/**\n * Run a command in the Daytona sandbox.\n *\n * Thin wrapper around `sandbox.process.executeCommand` that converts timeout\n * from milliseconds to seconds and null-coalesces the output string.\n *\n * Does NOT throw on non-zero exit codes — callers should check `exitCode`.\n */\nexport async function runCommand(\n sandbox: Sandbox,\n command: string,\n options?: { timeout?: number },\n): Promise<CommandResult> {\n const result = await sandbox.process.executeCommand(\n command,\n undefined, // cwd\n undefined, // env\n options?.timeout !== undefined ? Math.ceil(options.timeout / 1000) : undefined,\n );\n\n return {\n exitCode: result.exitCode,\n output: result.result ?? '',\n };\n}\n","import { createHash } from 'node:crypto';\n\nimport type { FilesystemMountConfig } from '@mastra/core/workspace';\n\nimport { shellQuote } from '../../utils/shell-quote';\nimport { LOG_PREFIX, validateBucketName, validateEndpoint } from './types';\nimport type { MountContext } from './types';\n\n/**\n * S3 mount config for Daytona (mounted via s3fs-fuse).\n *\n * If credentials are not provided, the bucket will be mounted as read-only\n * using the `public_bucket=1` option (for public AWS S3 buckets only).\n *\n * Note: S3-compatible services (R2, MinIO, etc.) always require credentials.\n */\nexport interface DaytonaS3MountConfig extends FilesystemMountConfig {\n type: 's3';\n /** S3 bucket name */\n bucket: string;\n /** AWS region */\n region: string;\n /** S3 endpoint for S3-compatible storage (MinIO, R2, etc.) */\n endpoint?: string;\n /** AWS access key ID (optional - omit for public buckets) */\n accessKeyId?: string;\n /** AWS secret access key (optional - omit for public buckets) */\n secretAccessKey?: string;\n /** Mount as read-only (even if credentials have write access) */\n readOnly?: boolean;\n}\n\n/**\n * Mount an S3 bucket using s3fs-fuse.\n */\nexport async function mountS3(mountPath: string, config: DaytonaS3MountConfig, ctx: MountContext): Promise<void> {\n const { run, writeFile, logger } = ctx;\n\n validateBucketName(config.bucket);\n if (config.endpoint) {\n validateEndpoint(config.endpoint);\n }\n\n const quotedMountPath = shellQuote(mountPath);\n\n // Validate credentials before any network calls — this gives the user a clear,\n // immediate error instead of a confusing connectivity failure.\n const hasAccessKey = !!config.accessKeyId;\n const hasSecretKey = !!config.secretAccessKey;\n if (hasAccessKey !== hasSecretKey) {\n throw new Error('Both accessKeyId and secretAccessKey must be provided together.');\n }\n const hasCredentials = hasAccessKey && hasSecretKey;\n\n if (!hasCredentials && config.endpoint) {\n throw new Error(\n `S3-compatible storage requires credentials. ` +\n `Detected endpoint: ${config.endpoint}. ` +\n `The public_bucket option only works for AWS S3 public buckets, not R2, MinIO, etc.`,\n );\n }\n\n // For S3-compatible storage (R2, MinIO, etc.), check connectivity to the custom endpoint.\n // AWS S3 endpoints are whitelisted in Daytona's proxy so no check needed for the default case.\n if (config.endpoint) {\n const endpoint = config.endpoint.replace(/\\/$/, '');\n const connectivityCheck = await run(`curl -sS --max-time 5 ${shellQuote(endpoint)} 2>&1`, 10_000);\n const checkOutput = connectivityCheck.stdout.trim();\n if (\n connectivityCheck.exitCode !== 0 ||\n checkOutput.toLowerCase().includes('restricted') ||\n checkOutput.toLowerCase().includes('blocked')\n ) {\n throw new Error(\n `Cannot reach ${endpoint} from this sandbox. ` +\n `S3-compatible storage mounting requires network access to the configured endpoint, ` +\n `which may be blocked on Daytona's restricted tiers. ` +\n `Upgrade to a tier with unrestricted internet access, or contact Daytona support to remove the network restriction.` +\n (checkOutput ? `\\n\\nSandbox network response: ${checkOutput}` : ''),\n );\n }\n }\n\n // Install s3fs if not present\n const checkResult = await run('which s3fs 2>/dev/null || echo \"not found\"', 30_000);\n if (checkResult.stdout.includes('not found')) {\n logger.warn(`${LOG_PREFIX} s3fs not found, attempting runtime installation...`);\n logger.info(`${LOG_PREFIX} Tip: For faster startup, pre-install s3fs in your sandbox image`);\n\n await run('sudo apt-get update -qq 2>&1', 60_000);\n\n // The fuse package's post-install script may fail in containers (e.g. can't run modprobe,\n // can't set SUID). Use || true so the overall command succeeds even if dpkg exits non-zero,\n // then verify the binary is actually present below.\n await run('sudo apt-get install -y s3fs fuse 2>&1 || sudo apt-get install -y s3fs-fuse fuse 2>&1 || true', 120_000);\n\n // Verify installation\n const s3fsCheck = await run('which s3fs 2>/dev/null || echo \"not found\"', 30_000);\n if (s3fsCheck.stdout.includes('not found')) {\n throw new Error('Failed to install s3fs: binary not found after install attempt');\n }\n }\n\n // The fuse post-install script may fail to set the SUID bit on fusermount.\n // Set it explicitly so non-root processes can call fusermount.\n await run('sudo chmod u+s /usr/bin/fusermount3 /usr/bin/fusermount 2>/dev/null || true', 30_000);\n\n // Get uid/gid for proper file ownership\n const idResult = await run('id -u && id -g', 30_000);\n const [uid, gid] = idResult.stdout.trim().split('\\n');\n const validUidGid = uid && gid && /^\\d+$/.test(uid) && /^\\d+$/.test(gid);\n if (!validUidGid) {\n logger.warn(\n `${LOG_PREFIX} Unexpected uid/gid format: \"${idResult.stdout.trim()}\" — mounted files will be owned by root`,\n );\n }\n\n // Use a mount-specific credentials path to avoid races with concurrent mounts\n const mountHash = createHash('md5').update(mountPath).digest('hex').slice(0, 8);\n const credentialsPath = `/tmp/.passwd-s3fs-${mountHash}`;\n\n // Allow non-root processes to use FUSE and the allow_other mount option.\n // These are no-ops if already configured.\n await run(\n `sudo chmod a+rw /dev/fuse 2>/dev/null || true; ` +\n `sudo bash -c 'grep -q \"^user_allow_other\" /etc/fuse.conf 2>/dev/null || echo \"user_allow_other\" >> /etc/fuse.conf' 2>/dev/null || true`,\n );\n\n if (hasCredentials) {\n await run(`sudo rm -f ${shellQuote(credentialsPath)}`, 30_000);\n await writeFile(credentialsPath, `${config.accessKeyId}:${config.secretAccessKey}`);\n await run(`chmod 600 ${shellQuote(credentialsPath)}`, 30_000);\n }\n\n const mountOptions: string[] = [];\n\n if (hasCredentials) {\n mountOptions.push(`passwd_file=${credentialsPath}`);\n } else {\n mountOptions.push('public_bucket=1');\n logger.debug(`${LOG_PREFIX} No credentials provided, mounting as public bucket (read-only)`);\n }\n\n // allow_other: let other users (e.g. root for rmdir) access the mount.\n // Requires user_allow_other in /etc/fuse.conf for non-root mounts.\n mountOptions.push('allow_other');\n\n if (validUidGid) {\n mountOptions.push(`uid=${uid}`, `gid=${gid}`);\n }\n\n if (config.endpoint) {\n const endpoint = config.endpoint.replace(/\\/$/, '');\n mountOptions.push(`url=${shellQuote(endpoint)}`, 'use_path_request_style', 'sigv4', 'nomultipart');\n }\n\n if (config.readOnly) {\n mountOptions.push('ro');\n logger.debug(`${LOG_PREFIX} Mounting as read-only`);\n }\n\n // Run s3fs as the sandbox user (not root) so the FUSE connection is registered\n // in the container's user namespace — allowing fusermount -u to unmount it later.\n const mountCmd = `s3fs ${shellQuote(config.bucket)} ${quotedMountPath} -o ${mountOptions.join(' -o ')}`;\n logger.debug(`${LOG_PREFIX} Mounting S3:`, hasCredentials ? mountCmd.replace(credentialsPath, '***') : mountCmd);\n\n const result = await run(mountCmd, 60_000);\n logger.debug(`${LOG_PREFIX} s3fs result:`, {\n exitCode: result.exitCode,\n stdout: result.stdout,\n stderr: result.stderr,\n });\n if (result.exitCode !== 0) {\n throw new Error(`Failed to mount S3 bucket: ${result.stderr || result.stdout}`);\n }\n}\n","import { createHash } from 'node:crypto';\n\nimport type { FilesystemMountConfig } from '@mastra/core/workspace';\n\nimport { shellQuote } from '../../utils/shell-quote';\nimport { LOG_PREFIX, validateBucketName } from './types';\nimport type { MountContext } from './types';\n\n/**\n * GCS mount config for Daytona (mounted via gcsfuse).\n *\n * If credentials are not provided, the bucket will be mounted as read-only\n * using anonymous access (for public buckets only).\n */\nexport interface DaytonaGCSMountConfig extends FilesystemMountConfig {\n type: 'gcs';\n /** GCS bucket name */\n bucket: string;\n /** Service account key JSON (optional - omit for public buckets) */\n serviceAccountKey?: string;\n}\n\n/**\n * Mount a GCS bucket using gcsfuse.\n */\nexport async function mountGCS(mountPath: string, config: DaytonaGCSMountConfig, ctx: MountContext): Promise<void> {\n const { run, writeFile, logger } = ctx;\n\n validateBucketName(config.bucket);\n\n const quotedMountPath = shellQuote(mountPath);\n\n // gcsfuse needs to reach Google Cloud Storage APIs at runtime.\n // Daytona's free/restricted tiers block access to Google services.\n // Fail fast with a clear message instead of hanging on the mount command.\n const connectivityCheck = await run('curl -sS --max-time 5 http://storage.googleapis.com 2>&1', 10_000);\n const checkOutput = connectivityCheck.stdout.trim();\n // Daytona's restricted tiers return HTTP 200 with a plain-text restriction message\n // for HTTP requests, or reset the connection for HTTPS. Detect either case.\n if (\n connectivityCheck.exitCode !== 0 ||\n checkOutput.toLowerCase().includes('restricted') ||\n checkOutput.toLowerCase().includes('blocked')\n ) {\n throw new Error(\n `Cannot reach Google Cloud Storage from this sandbox. ` +\n `GCS mounting requires network access to storage.googleapis.com, ` +\n `which may be blocked on Daytona's restricted tiers. ` +\n `Upgrade to a tier with unrestricted internet access, or contact Daytona support to remove the network restriction.` +\n (checkOutput ? `\\n\\nSandbox network response: ${checkOutput}` : ''),\n );\n }\n\n // Install gcsfuse if not present\n const checkResult = await run('which gcsfuse 2>/dev/null || echo \"not found\"', 30_000);\n if (checkResult.stdout.includes('not found')) {\n logger.warn(`${LOG_PREFIX} gcsfuse not found, attempting runtime installation...`);\n logger.info(`${LOG_PREFIX} Tip: For faster startup, pre-install gcsfuse in your sandbox image`);\n\n // Ensure curl and gpg are available for downloading the gcsfuse apt key.\n // Do NOT pre-install fuse here — the fuse package post-install script fails in containers\n // (can't run modprobe), leaving dpkg in a broken state that prevents gcsfuse from installing.\n // The gcsfuse apt package handles the fuse/fuse3 dependency automatically when installed.\n await run('sudo apt-get update -qq 2>&1', 60_000);\n const prepResult = await run('sudo apt-get install -y curl gnupg 2>&1', 120_000);\n if (prepResult.exitCode !== 0) {\n throw new Error(\n `Failed to install gcsfuse prerequisites (curl, gnupg): ${prepResult.stderr || prepResult.stdout}`,\n );\n }\n\n // Detect distro ID and codename from /etc/os-release (more reliable than lsb_release).\n // Google's gcsfuse apt repo only has packages for certain codenames (e.g. bookworm, jammy).\n // If the detected codename has no repo (e.g. trixie, noble), fall back to a known-good\n // codename for the distro family: bookworm for Debian, jammy for Ubuntu.\n const distroIdResult = await run(\n 'cat /etc/os-release 2>/dev/null | grep \"^ID=\" | cut -d= -f2 || echo debian',\n 30_000,\n );\n const distroId = distroIdResult.stdout.trim().replace(/\"/g, '') || 'debian';\n\n // Pick the appropriate known-good fallback for this distro family\n const fallbackCodename = distroId === 'ubuntu' ? 'jammy' : 'bookworm';\n\n const codenameResult = await run(\n `cat /etc/os-release 2>/dev/null | grep \"^VERSION_CODENAME=\" | cut -d= -f2 || echo ${fallbackCodename}`,\n 30_000,\n );\n const detectedCodename = codenameResult.stdout.trim() || fallbackCodename;\n if (!/^[a-z0-9][a-z0-9-]*$/.test(detectedCodename)) {\n throw new Error(`Invalid distro codename for gcsfuse repo: \"${detectedCodename}\"`);\n }\n\n logger.debug(`${LOG_PREFIX} Detected distro: ${distroId}/${detectedCodename}, fallback: ${fallbackCodename}`);\n\n // Set up the gcsfuse apt repository. Use separate curl + gpg steps (not piped)\n // so a curl failure propagates as non-zero exit rather than being masked by gpg.\n const repoSetup = await run(\n 'sudo mkdir -p /etc/apt/keyrings && ' +\n 'curl -fsSL https://packages.cloud.google.com/apt/doc/apt-key.gpg -o /tmp/gcsfuse-key.gpg && ' +\n 'sudo gpg --batch --yes --dearmor -o /etc/apt/keyrings/gcsfuse.gpg /tmp/gcsfuse-key.gpg && ' +\n `echo \"deb [signed-by=/etc/apt/keyrings/gcsfuse.gpg] https://packages.cloud.google.com/apt gcsfuse-${detectedCodename} main\" | sudo tee /etc/apt/sources.list.d/gcsfuse.list`,\n 30_000,\n );\n if (repoSetup.exitCode !== 0) {\n throw new Error(`Failed to set up gcsfuse apt repository: ${repoSetup.stderr || repoSetup.stdout}`);\n }\n\n // apt-get update may fail on unrelated repos (e.g. broken keys); use || true and verify install separately\n await run('sudo apt-get update -qq 2>&1 || true', 60_000);\n\n let installResult = await run('sudo apt-get install -y gcsfuse 2>&1', 120_000);\n\n // Fallback: if install failed with detected codename (e.g. trixie, noble — no repo yet),\n // retry with a known-good codename for the distro family.\n if (installResult.exitCode !== 0 && detectedCodename !== fallbackCodename) {\n logger.warn(\n `${LOG_PREFIX} gcsfuse install failed for \"${detectedCodename}\", retrying with \"${fallbackCodename}\" fallback`,\n );\n await run(\n 'sudo rm -f /etc/apt/sources.list.d/gcsfuse.list && ' +\n `echo \"deb [signed-by=/etc/apt/keyrings/gcsfuse.gpg] https://packages.cloud.google.com/apt gcsfuse-${fallbackCodename} main\" | sudo tee /etc/apt/sources.list.d/gcsfuse.list`,\n 10_000,\n );\n await run('sudo apt-get update -qq 2>&1 || true', 60_000);\n installResult = await run('sudo apt-get install -y gcsfuse 2>&1', 120_000);\n }\n\n // Verify installation by checking the binary directly.\n // dpkg may report a non-zero exit if fuse's post-install script fails in containers\n // (can't run modprobe), but gcsfuse is still unpacked and usable in that case.\n const verifyResult = await run('which gcsfuse 2>/dev/null || echo \"not found\"', 30_000);\n if (verifyResult.stdout.includes('not found')) {\n throw new Error(`Failed to install gcsfuse: ${installResult.stderr || installResult.stdout}`);\n }\n if (installResult.exitCode !== 0) {\n logger.warn(\n `${LOG_PREFIX} gcsfuse install reported dpkg errors (likely fuse post-install in container) but binary is present — proceeding`,\n );\n }\n }\n\n // Get uid/gid for proper file ownership\n const idResult = await run('id -u && id -g', 30_000);\n const [uid, gid] = idResult.stdout.trim().split('\\n');\n const validUidGid = uid && gid && /^\\d+$/.test(uid) && /^\\d+$/.test(gid);\n if (!validUidGid) {\n logger.warn(\n `${LOG_PREFIX} Unexpected uid/gid format: \"${idResult.stdout.trim()}\" — mounted files will be owned by root`,\n );\n }\n // Note: gcsfuse uses --uid/--gid flags, not -o uid=X style\n const uidGidFlags = validUidGid ? `--uid=${uid} --gid=${gid}` : '';\n\n // Allow non-root processes to use FUSE and the allow_other mount option.\n // These are no-ops if already configured.\n await run(\n `sudo chmod a+rw /dev/fuse 2>/dev/null || true; ` +\n `sudo bash -c 'grep -q \"^user_allow_other\" /etc/fuse.conf 2>/dev/null || echo \"user_allow_other\" >> /etc/fuse.conf' 2>/dev/null || true`,\n );\n\n const hasCredentials = !!config.serviceAccountKey;\n // Run gcsfuse as the sandbox user (not root) so the FUSE connection is registered\n // in the container's user namespace — allowing fusermount -u to unmount it later.\n let mountCmd: string;\n\n if (hasCredentials) {\n // Use a mount-specific key path to avoid races with concurrent mounts\n const mountHash = createHash('md5').update(mountPath).digest('hex').slice(0, 8);\n const keyPath = `/tmp/gcs-key-${mountHash}.json`;\n await run(`sudo rm -f ${shellQuote(keyPath)}`, 30_000);\n await writeFile(keyPath, config.serviceAccountKey!);\n await run(`chmod 600 ${shellQuote(keyPath)}`, 30_000);\n\n mountCmd = `gcsfuse --key-file=${shellQuote(keyPath)} -o allow_other ${uidGidFlags} ${shellQuote(config.bucket)} ${quotedMountPath}`;\n } else {\n logger.debug(`${LOG_PREFIX} No credentials provided, mounting GCS as public bucket (read-only)`);\n mountCmd = `gcsfuse --anonymous-access -o allow_other ${uidGidFlags} ${shellQuote(config.bucket)} ${quotedMountPath}`;\n }\n\n logger.debug(`${LOG_PREFIX} Mounting GCS:`, mountCmd);\n\n const result = await run(mountCmd, 60_000);\n logger.debug(`${LOG_PREFIX} gcsfuse result:`, {\n exitCode: result.exitCode,\n stdout: result.stdout,\n stderr: result.stderr,\n });\n if (result.exitCode !== 0) {\n throw new Error(`Failed to mount GCS bucket: ${result.stderr || result.stdout}`);\n }\n}\n","/**\n * Daytona Process Manager\n *\n * Implements SandboxProcessManager for Daytona cloud sandboxes.\n * Wraps the Daytona SDK's session API (createSession, executeSessionCommand,\n * getSessionCommandLogs, deleteSession) for background process management.\n *\n * Each spawn() creates a dedicated session with a single command.\n * The user command is wrapped in a subshell `(command)` so that:\n * - `exit N` exits the subshell, not the session shell\n * - Heredocs are contained within the subshell\n * - The session command finishes cleanly\n */\n\nimport type { Sandbox } from '@daytonaio/sdk';\nimport { ProcessHandle, SandboxProcessManager } from '@mastra/core/workspace';\nimport type { CommandResult, ProcessInfo, SpawnProcessOptions } from '@mastra/core/workspace';\nimport { shellQuote } from '../utils/shell-quote';\nimport type { DaytonaSandbox } from './index';\n\n// =============================================================================\n// Daytona Process Handle\n// =============================================================================\n\n/**\n * Wraps a Daytona session + command pair to conform to Mastra's ProcessHandle.\n * Not exported — internal to this module.\n */\nclass DaytonaProcessHandle extends ProcessHandle {\n readonly pid: string;\n\n private readonly _cmdId: string;\n private readonly _sandbox: Sandbox;\n private readonly _startTime: number;\n private readonly _timeout?: number;\n\n private _exitCode: number | undefined;\n private _waitPromise: Promise<CommandResult> | null = null;\n private _streamingPromise: Promise<void> | null = null;\n private _killed = false;\n\n constructor(sessionId: string, cmdId: string, sandbox: Sandbox, startTime: number, options?: SpawnProcessOptions) {\n super(options);\n this.pid = sessionId;\n this._cmdId = cmdId;\n this._sandbox = sandbox;\n this._startTime = startTime;\n this._timeout = options?.timeout;\n }\n\n get exitCode(): number | undefined {\n return this._exitCode;\n }\n\n /** @internal Set by the process manager after streaming starts. */\n set streamingPromise(p: Promise<void>) {\n this._streamingPromise = p;\n\n // Auto-resolve exit code when streaming ends (so exitCode is available without wait())\n p.then(() => this._resolveExitCode()).catch(() => this._resolveExitCode());\n }\n\n /** Fetch the exit code from Daytona and set _exitCode. No-op if already set. */\n private async _resolveExitCode(): Promise<void> {\n if (this._exitCode !== undefined) return;\n try {\n const cmd = await this._sandbox.process.getSessionCommand(this.pid, this._cmdId);\n this._exitCode = cmd.exitCode ?? 0;\n } catch {\n if (this._exitCode === undefined) {\n this._exitCode = 1;\n }\n }\n }\n\n async wait(): Promise<CommandResult> {\n // Idempotent — cache the promise so repeated calls return the same result\n if (!this._waitPromise) {\n this._waitPromise = this._doWait();\n }\n return this._waitPromise;\n }\n\n private async _doWait(): Promise<CommandResult> {\n // Race streaming against timeout (if configured)\n const streamDone = this._streamingPromise ?? Promise.resolve();\n\n if (this._timeout) {\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutId = setTimeout(() => reject(new Error(`Command timed out after ${this._timeout}ms`)), this._timeout);\n });\n\n try {\n await Promise.race([streamDone, timeoutPromise]);\n } catch (error) {\n // On timeout, kill the process and return partial output\n if (error instanceof Error && error.message.includes('timed out')) {\n await this.kill();\n this._exitCode = 124; // Standard timeout exit code\n return {\n success: false,\n exitCode: 124,\n stdout: this.stdout,\n stderr: this.stderr || error.message,\n executionTimeMs: Date.now() - this._startTime,\n };\n }\n throw error;\n } finally {\n clearTimeout(timeoutId);\n }\n } else {\n // No timeout — just wait for streaming to complete\n await streamDone.catch(() => {});\n }\n\n // If killed during wait, return with kill exit code\n if (this._killed) {\n return {\n success: false,\n exitCode: this._exitCode ?? 137,\n stdout: this.stdout,\n stderr: this.stderr,\n executionTimeMs: Date.now() - this._startTime,\n };\n }\n\n // Ensure exit code is resolved\n await this._resolveExitCode();\n\n return {\n success: this._exitCode === 0,\n exitCode: this._exitCode ?? 1,\n stdout: this.stdout,\n stderr: this.stderr,\n executionTimeMs: Date.now() - this._startTime,\n };\n }\n\n async kill(): Promise<boolean> {\n if (this._exitCode !== undefined) return false;\n this._killed = true;\n this._exitCode = 137; // SIGKILL\n try {\n await this._sandbox.process.deleteSession(this.pid);\n } catch {\n // Session may already be gone\n }\n return true;\n }\n\n async sendStdin(data: string): Promise<void> {\n if (this._exitCode !== undefined) {\n throw new Error(`Process ${this.pid} has already exited with code ${this._exitCode}`);\n }\n await this._sandbox.process.sendSessionCommandInput(this.pid, this._cmdId, data);\n }\n}\n\n// =============================================================================\n// Daytona Process Manager\n// =============================================================================\n\nexport interface DaytonaProcessManagerOptions {\n env?: Record<string, string | undefined>;\n /** Default timeout in milliseconds for commands that don't specify one. */\n defaultTimeout?: number;\n}\n\n/**\n * Daytona implementation of SandboxProcessManager.\n * Uses the Daytona SDK's session API with one session per spawned process.\n */\nexport class DaytonaProcessManager extends SandboxProcessManager<DaytonaSandbox> {\n private _spawnCounter = 0;\n private readonly _defaultTimeout?: number;\n\n constructor(opts: DaytonaProcessManagerOptions = {}) {\n super({ env: opts.env });\n this._defaultTimeout = opts.defaultTimeout;\n }\n\n async spawn(command: string, options: SpawnProcessOptions = {}): Promise<ProcessHandle> {\n // Apply default timeout if the caller didn't specify one\n const effectiveOptions = {\n ...options,\n timeout: options.timeout ?? this._defaultTimeout,\n };\n return this.sandbox.retryOnDead(async () => {\n const sandbox = this.sandbox.daytona;\n\n // Merge default env with per-spawn env\n const mergedEnv = { ...this.env, ...effectiveOptions.env };\n const envs = Object.fromEntries(\n Object.entries(mergedEnv).filter((entry): entry is [string, string] => entry[1] !== undefined),\n );\n\n // Build command with baked-in env and cwd, wrapped in subshell\n const sessionCommand = buildSpawnCommand(command, effectiveOptions.cwd, envs);\n\n // Unique session ID per spawn — used as the PID\n const sessionId = `mastra-proc-${Date.now().toString(36)}-${++this._spawnCounter}`;\n\n await sandbox.process.createSession(sessionId);\n\n const { cmdId } = await sandbox.process.executeSessionCommand(sessionId, {\n command: sessionCommand,\n runAsync: true,\n });\n\n const handle = new DaytonaProcessHandle(sessionId, cmdId, sandbox, Date.now(), effectiveOptions);\n\n // Start streaming logs — route to handle's emitters\n const streamingPromise = sandbox.process\n .getSessionCommandLogs(\n sessionId,\n cmdId,\n (chunk: string) => handle.emitStdout(chunk),\n (chunk: string) => handle.emitStderr(chunk),\n )\n .catch(() => {\n // Stream ends when session is deleted (e.g., after kill) — swallow the error\n });\n\n handle.streamingPromise = streamingPromise;\n\n this._tracked.set(handle.pid, handle);\n return handle;\n });\n }\n\n async list(): Promise<ProcessInfo[]> {\n const result: ProcessInfo[] = [];\n for (const [pid, handle] of this._tracked) {\n result.push({\n pid,\n command: handle.command,\n running: handle.exitCode === undefined,\n exitCode: handle.exitCode,\n });\n }\n return result;\n }\n}\n\n// =============================================================================\n// Command Building\n// =============================================================================\n\n/**\n * Build a shell command string that bakes in cwd and env vars.\n * Wraps the user command in a subshell `(command)` so that:\n * - `exit N` exits the subshell, not the session shell\n * - Heredocs work correctly within the subshell\n *\n * @example\n * buildSpawnCommand('npm test', '/app', { NODE_ENV: 'test' })\n * // → \"export NODE_ENV='test' && cd '/app' && (npm test)\"\n */\nfunction buildSpawnCommand(command: string, cwd: string | undefined, envs: Record<string, string>): string {\n const parts: string[] = [];\n\n for (const [k, v] of Object.entries(envs)) {\n parts.push(`export ${k}=${shellQuote(v)}`);\n }\n\n if (cwd) {\n parts.push(`cd ${shellQuote(cwd)}`);\n }\n\n // Wrap in subshell to isolate exit codes and heredocs\n parts.push(`(${command})`);\n\n return parts.join(' && ');\n}\n","/**\n * Daytona Sandbox Provider\n *\n * A Daytona sandbox implementation for Mastra workspaces.\n * Supports command execution, environment variables, resource configuration,\n * snapshots, Daytona volumes, and FUSE-based cloud filesystem mounting (S3, GCS).\n *\n * @see https://www.daytona.io/docs\n */\n\nimport { Daytona, DaytonaNotFoundError, SandboxState } from '@daytonaio/sdk';\nimport type {\n CreateSandboxFromImageParams,\n CreateSandboxFromSnapshotParams,\n Sandbox,\n VolumeMount,\n} from '@daytonaio/sdk';\nimport type {\n SandboxInfo,\n ProviderStatus,\n MastraSandboxOptions,\n WorkspaceFilesystem,\n MountResult,\n FilesystemMountConfig,\n MountManager,\n CommandResult,\n ExecuteCommandOptions,\n} from '@mastra/core/workspace';\nimport { MastraSandbox, SandboxNotReadyError } from '@mastra/core/workspace';\n\nimport { compact } from '../utils/compact';\nimport { shellQuote } from '../utils/shell-quote';\nimport { mountS3, mountGCS, LOG_PREFIX, runCommand } from './mounts';\nimport type { DaytonaMountConfig, MountContext } from './mounts';\nimport { DaytonaProcessManager } from './process-manager';\nimport type { DaytonaResources } from './types';\n\n/** Allowlist pattern for mount paths — absolute path with safe characters only. */\nconst SAFE_MOUNT_PATH = /^\\/[a-zA-Z0-9_.\\-/]+$/;\n\n/** Default timeout for mount lifecycle shell commands (mkdir, unmount, proc reads, etc.) */\nconst MOUNT_COMMAND_TIMEOUT_MS = 30_000;\n\n/** Convert an unknown error to a readable string. */\nfunction errorToString(error: unknown): string {\n if (error instanceof Error) return error.message;\n if (typeof error === 'string') return error;\n if (error && typeof error === 'object' && 'message' in error) {\n const maybeError = error as { message?: unknown };\n if (typeof maybeError.message === 'string') {\n return maybeError.message;\n }\n }\n try {\n return JSON.stringify(error);\n } catch {\n return String(error);\n }\n}\n\nfunction validateMountPath(mountPath: string): void {\n if (!SAFE_MOUNT_PATH.test(mountPath)) {\n throw new Error(\n `Invalid mount path: ${mountPath}. Must be an absolute path with alphanumeric, dash, dot, underscore, or slash characters only.`,\n );\n }\n const segments = mountPath.split('/');\n if (mountPath.includes('//') || segments.some(segment => segment === '.' || segment === '..')) {\n throw new Error(`Invalid mount path: ${mountPath}. Path traversal segments are not allowed.`);\n }\n}\n\n/** Allowlist for marker filenames from ls output — e.g. \"mount-abc123\" */\nconst SAFE_MARKER_NAME = /^mount-[a-z0-9]+$/;\n\n/** Patterns indicating the sandbox is dead/gone (@daytonaio/sdk@0.143.0). */\nconst SANDBOX_DEAD_PATTERNS: RegExp[] = [\n /sandbox is not running/i,\n /sandbox already destroyed/i,\n /sandbox.*not found/i,\n /failed to resolve container IP/i,\n /is the sandbox started/i,\n];\n\n// =============================================================================\n// Daytona Sandbox Options\n// =============================================================================\n\n/**\n * Daytona sandbox provider configuration.\n */\nexport interface DaytonaSandboxOptions extends Omit<MastraSandboxOptions, 'processes'> {\n /** Unique identifier for this sandbox instance */\n id?: string;\n /** API key for authentication. Falls back to DAYTONA_API_KEY env var. */\n apiKey?: string;\n /** API URL. Falls back to DAYTONA_API_URL env var or https://app.daytona.io/api. */\n apiUrl?: string;\n /** Target runner region. Falls back to DAYTONA_TARGET env var. */\n target?: string;\n /**\n * Default execution timeout in milliseconds.\n * @default 300_000 // 5 minutes\n */\n timeout?: number;\n /**\n * Sandbox runtime language.\n * @default 'typescript'\n */\n language?: 'typescript' | 'javascript' | 'python';\n /** Resource allocation for the sandbox */\n resources?: DaytonaResources;\n /** Environment variables to set in the sandbox */\n env?: Record<string, string>;\n /** Custom metadata labels */\n labels?: Record<string, string>;\n /** Pre-built snapshot ID to create sandbox from. Takes precedence over resources/image. */\n snapshot?: string;\n /**\n * Docker image to use for sandbox creation. When set, triggers image-based creation.\n * Can optionally be combined with `resources` for custom resource allocation.\n * Has no effect when `snapshot` is set.\n */\n image?: string;\n /**\n * Whether the sandbox should be ephemeral. If true, autoDeleteInterval will be set to 0\n * (delete immediately on stop).\n * @default false\n */\n ephemeral?: boolean;\n /**\n * Auto-stop interval in minutes (0 = disabled).\n * @default 15\n */\n autoStopInterval?: number;\n /**\n * Auto-archive interval in minutes (0 = maximum interval, which is 7 days).\n * @default 7 days\n */\n autoArchiveInterval?: number;\n /**\n * Daytona volumes to attach at creation.\n * Volumes are configured at sandbox creation time, not mounted dynamically.\n */\n volumes?: Array<VolumeMount>;\n /** Sandbox display name */\n name?: string;\n /** OS user to use for the sandbox */\n user?: string;\n /** Whether the sandbox port preview is public */\n public?: boolean;\n /**\n * Auto-delete interval in minutes (negative = disabled, 0 = delete immediately on stop).\n * @default disabled\n */\n autoDeleteInterval?: number;\n /** Whether to block all network access for the sandbox */\n networkBlockAll?: boolean;\n /** Comma-separated list of allowed CIDR network addresses for the sandbox */\n networkAllowList?: string;\n}\n\n// =============================================================================\n// Daytona Sandbox Implementation\n// =============================================================================\n\n/**\n * Daytona sandbox provider for Mastra workspaces.\n *\n * Features:\n * - Isolated cloud sandbox via Daytona SDK\n * - Multi-runtime support (TypeScript, JavaScript, Python)\n * - Resource configuration (CPU, memory, disk)\n * - Volume attachment at creation time\n * - FUSE-based cloud filesystem mounting (S3, GCS)\n * - Automatic sandbox timeout handling with retry\n *\n * @example Basic usage\n * ```typescript\n * import { Workspace } from '@mastra/core/workspace';\n * import { DaytonaSandbox } from '@mastra/daytona';\n *\n * const sandbox = new DaytonaSandbox({\n * timeout: 60000,\n * language: 'typescript',\n * });\n *\n * const workspace = new Workspace({ sandbox });\n * const result = await workspace.executeCode('console.log(\"Hello!\")');\n * ```\n *\n * @example With resources and volumes\n * ```typescript\n * const sandbox = new DaytonaSandbox({\n * resources: { cpu: 2, memory: 4, disk: 6 },\n * volumes: [{ volumeId: 'vol-123', mountPath: '/data' }],\n * env: { NODE_ENV: 'production' },\n * });\n * ```\n */\nexport class DaytonaSandbox extends MastraSandbox {\n readonly id: string;\n readonly name = 'DaytonaSandbox';\n readonly provider = 'daytona';\n\n declare readonly mounts: MountManager; // Non-optional (initialized by base class when mount() exists)\n\n status: ProviderStatus = 'pending';\n\n private _daytona: Daytona | null = null;\n private _sandbox: Sandbox | null = null;\n private _createdAt: Date | null = null;\n private _workingDir: string | null = null;\n private _isRetrying = false;\n\n private readonly timeout: number;\n private readonly language: 'typescript' | 'javascript' | 'python';\n private readonly resources?: DaytonaResources;\n private readonly env: Record<string, string>;\n private readonly labels: Record<string, string>;\n private readonly snapshotId?: string;\n private readonly image?: string;\n private readonly ephemeral: boolean;\n private readonly autoStopInterval?: number;\n private readonly autoArchiveInterval?: number;\n private readonly autoDeleteInterval?: number;\n private readonly volumeConfigs: Array<VolumeMount>;\n private readonly sandboxName?: string;\n private _daytonaSandboxId?: string;\n private readonly sandboxUser?: string;\n private readonly sandboxPublic?: boolean;\n private readonly networkBlockAll?: boolean;\n private readonly networkAllowList?: string;\n private readonly connectionOpts: { apiKey?: string; apiUrl?: string; target?: string };\n\n constructor(options: DaytonaSandboxOptions = {}) {\n super({\n ...options,\n name: 'DaytonaSandbox',\n processes: new DaytonaProcessManager({\n env: options.env,\n defaultTimeout: options.timeout ?? 300_000,\n }),\n });\n\n this.id = options.id ?? this.generateId();\n this.timeout = options.timeout ?? 300_000;\n this.language = options.language ?? 'typescript';\n this.resources = options.resources;\n this.env = options.env ?? {};\n this.labels = options.labels ?? {};\n this.snapshotId = options.snapshot;\n this.image = options.image;\n this.ephemeral = options.ephemeral ?? false;\n this.autoStopInterval = options.autoStopInterval ?? 15;\n this.autoArchiveInterval = options.autoArchiveInterval;\n this.autoDeleteInterval = options.autoDeleteInterval;\n this.volumeConfigs = options.volumes ?? [];\n this.sandboxName = options.name ?? this.id;\n this.sandboxUser = options.user;\n this.sandboxPublic = options.public;\n this.networkBlockAll = options.networkBlockAll;\n this.networkAllowList = options.networkAllowList;\n\n this.connectionOpts = {\n ...(options.apiKey !== undefined && { apiKey: options.apiKey }),\n ...(options.apiUrl !== undefined && { apiUrl: options.apiUrl }),\n ...(options.target !== undefined && { target: options.target }),\n };\n }\n\n private generateId(): string {\n return `daytona-sandbox-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;\n }\n\n /**\n * Get the underlying Daytona Sandbox instance for direct access to Daytona APIs.\n *\n * Use this when you need to access Daytona features not exposed through the\n * WorkspaceSandbox interface (e.g., filesystem API, git operations, LSP).\n *\n * @throws {SandboxNotReadyError} If the sandbox has not been started\n *\n * @example Direct file operations\n * ```typescript\n * await sandbox.start();\n * const daytonaSandbox = sandbox.daytona;\n * await daytonaSandbox.fs.uploadFile(Buffer.from('Hello'), '/tmp/test.txt');\n * ```\n */\n get daytona(): Sandbox {\n if (!this._sandbox) {\n throw new SandboxNotReadyError(this.id);\n }\n return this._sandbox;\n }\n\n /** @deprecated Use `daytona` instead. */\n get instance(): Sandbox {\n return this.daytona;\n }\n\n // ---------------------------------------------------------------------------\n // Lifecycle\n // ---------------------------------------------------------------------------\n\n /**\n * Start the Daytona sandbox.\n * Reconnects to an existing sandbox with the same logical ID if one exists,\n * otherwise creates a new sandbox instance.\n */\n async start(): Promise<void> {\n if (this._sandbox) {\n return;\n }\n\n // Create Daytona client if not exists\n if (!this._daytona) {\n this._daytona = new Daytona(this.connectionOpts);\n }\n\n // Try to reconnect to an existing sandbox with the same logical ID\n const existing = await this.findExistingSandbox();\n if (existing) {\n this._sandbox = existing;\n this._daytonaSandboxId = existing.id;\n this._createdAt = existing.createdAt ? new Date(existing.createdAt) : new Date();\n this.logger.debug(`${LOG_PREFIX} Reconnected to existing sandbox ${existing.id} for: ${this.id}`);\n\n // Reconcile FUSE mounts — clean up stale mounts from a previous session\n const expectedPaths = Array.from(this.mounts.entries.keys());\n this.logger.debug(`${LOG_PREFIX} Running mount reconciliation...`);\n await this.reconcileMounts(expectedPaths);\n this.logger.debug(`${LOG_PREFIX} Mount reconciliation complete`);\n await this.detectWorkingDir();\n return;\n }\n\n this.logger.debug(`${LOG_PREFIX} Creating sandbox for: ${this.id}`);\n\n // Base params shared by both creation modes\n const baseParams = compact({\n language: this.language,\n labels: { ...this.labels, 'mastra-sandbox-id': this.id },\n ephemeral: this.ephemeral,\n autoStopInterval: this.autoStopInterval,\n autoArchiveInterval: this.autoArchiveInterval,\n autoDeleteInterval: this.autoDeleteInterval,\n volumes: this.volumeConfigs.length > 0 ? this.volumeConfigs : undefined,\n name: this.sandboxName,\n user: this.sandboxUser,\n public: this.sandboxPublic,\n networkBlockAll: this.networkBlockAll,\n networkAllowList: this.networkAllowList,\n });\n\n // Snapshot takes precedence. Image alone (with optional resources) triggers image-based creation.\n // Resources without image fall back to snapshot-based creation (resources are ignored).\n if (this.resources && !this.image) {\n this.logger.warn(\n `${LOG_PREFIX} 'resources' option requires 'image' to take effect — falling back to snapshot-based creation without custom resources`,\n );\n }\n\n const createParams: CreateSandboxFromSnapshotParams | CreateSandboxFromImageParams =\n this.image && !this.snapshotId\n ? (compact({\n ...baseParams,\n image: this.image,\n resources: this.resources,\n }) satisfies CreateSandboxFromImageParams)\n : (compact({ ...baseParams, snapshot: this.snapshotId }) satisfies CreateSandboxFromSnapshotParams);\n\n // Create sandbox\n this._sandbox = await this._daytona.create(createParams);\n this._daytonaSandboxId = this._sandbox.id;\n\n this.logger.debug(`${LOG_PREFIX} Created sandbox ${this._sandbox.id} for logical ID: ${this.id}`);\n this._createdAt = new Date();\n await this.detectWorkingDir();\n }\n\n /**\n * Stop the Daytona sandbox.\n * Unmounts all filesystems, then stops the sandbox.\n */\n async stop(): Promise<void> {\n for (const mountPath of [...this.mounts.entries.keys()]) {\n try {\n await this.unmount(mountPath);\n } catch {\n // Best-effort unmount; sandbox may already be dead\n }\n }\n\n if (this._sandbox && this._daytona) {\n try {\n await this._daytona.stop(this._sandbox);\n } catch {\n // Best-effort stop; sandbox may already be stopped\n }\n }\n this._sandbox = null;\n }\n\n /**\n * Destroy the Daytona sandbox and clean up all resources.\n * Deletes the sandbox and clears all state.\n */\n async destroy(): Promise<void> {\n if (this._sandbox && this._daytona) {\n try {\n await this._daytona.delete(this._sandbox);\n } catch {\n // Ignore errors during cleanup\n }\n } else if (!this._sandbox && this._daytona) {\n // Orphan cleanup: _start() may have failed after the SDK created\n // a server-side sandbox (e.g. bad image → BUILD_FAILED).\n // Try to find and delete it so it doesn't leak.\n const lookupKey = this._daytonaSandboxId ?? this.sandboxName;\n if (lookupKey) {\n try {\n const orphan = await this._daytona.get(lookupKey);\n await this._daytona.delete(orphan);\n } catch {\n // Best-effort — orphan may not exist or may already be gone\n }\n }\n }\n\n this._sandbox = null;\n this._daytonaSandboxId = undefined;\n this._daytona = null;\n this.mounts?.clear();\n }\n\n /**\n * Check if the sandbox is ready for operations.\n */\n async isReady(): Promise<boolean> {\n return this.status === 'running' && this._sandbox !== null;\n }\n\n /**\n * Get information about the current state of the sandbox.\n */\n async getInfo(): Promise<SandboxInfo> {\n return {\n id: this.id,\n name: this.name,\n provider: this.provider,\n status: this.status,\n createdAt: this._createdAt ?? new Date(),\n mounts: this.mounts\n ? Array.from(this.mounts.entries).map(([path, entry]) => ({\n path,\n filesystem: entry.filesystem?.provider ?? entry.config?.type ?? 'unknown',\n }))\n : [],\n ...(this._sandbox && {\n resources: {\n cpuCores: this._sandbox.cpu,\n memoryMB: this._sandbox.memory * 1024,\n diskMB: this._sandbox.disk * 1024,\n },\n }),\n metadata: {\n language: this.language,\n ephemeral: this.ephemeral,\n ...(this.snapshotId && { snapshot: this.snapshotId }),\n ...(this.image && { image: this.image }),\n ...(this._sandbox && { target: this._sandbox.target }),\n },\n };\n }\n\n /**\n * Get instructions describing this Daytona sandbox.\n * Used by agents to understand the execution environment.\n */\n getInstructions(): string {\n const parts: string[] = [];\n\n const mountCount = this.mounts.entries.size;\n const mountInfo = mountCount > 0 ? ` ${mountCount} filesystem(s) mounted via FUSE.` : '';\n parts.push(`Cloud sandbox with isolated execution (${this.language} runtime).${mountInfo}`);\n\n if (this._workingDir) {\n parts.push(`Default working directory: ${this._workingDir}.`);\n }\n\n parts.push(`Command timeout: ${Math.ceil(this.timeout / 1000)}s.`);\n\n parts.push(`Running as user: ${this.sandboxUser ?? 'daytona'}.`);\n\n if (this.volumeConfigs.length > 0) {\n parts.push(`${this.volumeConfigs.length} volume(s) attached.`);\n }\n\n if (this.networkBlockAll) {\n parts.push(`Network access is blocked.`);\n }\n\n return parts.join(' ');\n }\n\n // ---------------------------------------------------------------------------\n // Command Execution\n // ---------------------------------------------------------------------------\n\n /**\n * Execute a command in the sandbox and return the result.\n */\n async executeCommand(\n command: string,\n args: string[] = [],\n options: ExecuteCommandOptions = {},\n ): Promise<CommandResult> {\n await this.ensureRunning();\n const fullCommand = args.length > 0 ? `${command} ${args.map(shellQuote).join(' ')}` : command;\n const handle = await this.processes!.spawn(fullCommand, options);\n const result = await handle.wait();\n return { ...result, command, args };\n }\n\n // ---------------------------------------------------------------------------\n // Mount Support\n // ---------------------------------------------------------------------------\n\n /**\n * Mount a filesystem at a path in the sandbox.\n * Uses FUSE tools (s3fs, gcsfuse) to mount cloud storage.\n */\n async mount(filesystem: WorkspaceFilesystem, mountPath: string): Promise<MountResult> {\n validateMountPath(mountPath);\n\n if (!this._sandbox) {\n throw new SandboxNotReadyError(this.id);\n }\n const sandbox = this._sandbox;\n\n this.logger.debug(`${LOG_PREFIX} Mounting \"${mountPath}\"...`);\n\n // Get mount config - MountManager validates this exists before calling mount()\n const config = filesystem.getMountConfig?.() as DaytonaMountConfig | undefined;\n if (!config) {\n const error = `Filesystem \"${filesystem.id}\" does not provide a mount config`;\n this.logger.error(`${LOG_PREFIX} ${error}`);\n this.mounts.set(mountPath, { filesystem, state: 'error', error });\n return { success: false, mountPath, error };\n }\n\n // Check if already mounted with matching config (e.g., when reconnecting to existing sandbox)\n const existingMount = await this.checkExistingMount(mountPath, config);\n if (existingMount === 'matching') {\n this.logger.debug(\n `${LOG_PREFIX} Detected existing mount for ${filesystem.provider} (\"${filesystem.id}\") at \"${mountPath}\" with correct config, skipping`,\n );\n this.mounts.set(mountPath, { state: 'mounted', config });\n return { success: true, mountPath };\n } else if (existingMount === 'mismatched') {\n // Different config - unmount and re-mount\n this.logger.debug(`${LOG_PREFIX} Config mismatch at \"${mountPath}\", unmounting to re-mount with new config...`);\n await this.unmount(mountPath);\n } else if (existingMount === 'unmanaged') {\n const error = `Mount path \"${mountPath}\" is already mounted by an unmanaged source`;\n this.logger.error(`${LOG_PREFIX} ${error}`);\n this.mounts.set(mountPath, { filesystem, state: 'error', config, error });\n return { success: false, mountPath, error };\n }\n\n // Mark as mounting (handles direct mount() calls; MountManager also sets this for processPending)\n this.mounts.set(mountPath, { filesystem, state: 'mounting', config });\n this.logger.debug(`${LOG_PREFIX} Config type: ${config.type}`);\n\n // Reject non-empty directories — mounting would shadow existing files.\n // Skip the check if the path is already a mount point (stuck FUSE from a failed\n // prior unmount): its contents are remote objects, not local files to protect.\n try {\n const quotedPath = shellQuote(mountPath);\n const checkResult = await runCommand(\n sandbox,\n `[ -d ${quotedPath} ] && ! mountpoint -q ${quotedPath} 2>/dev/null && ` +\n `[ \"$(ls -A ${quotedPath} 2>/dev/null)\" ] && echo \"non-empty\" || echo \"ok\"`,\n { timeout: MOUNT_COMMAND_TIMEOUT_MS },\n );\n if (checkResult.output.trim() === 'non-empty') {\n const error = `Cannot mount at ${mountPath}: directory exists and is not empty. Mounting would hide existing files. Use a different path or empty the directory first.`;\n this.logger.error(`${LOG_PREFIX} ${error}`);\n this.mounts.set(mountPath, { filesystem, state: 'error', config, error });\n return { success: false, mountPath, error };\n }\n } catch {\n // Check failed, proceed anyway\n }\n\n // Create/prepare the mount directory.\n // If the path is already a FUSE mount (stuck from a failed prior unmount), overlay\n // it with a tmpfs first. New FUSE-on-existing-FUSE fails because the kernel asks the\n // existing daemon to resolve the mount point path, which returns ENOENT. A tmpfs\n // overlay is kernel-native and doesn't involve the FUSE driver.\n this.logger.debug(`${LOG_PREFIX} Creating mount directory for \"${mountPath}\"...`);\n try {\n const quotedPath = shellQuote(mountPath);\n const mkdirResult = await runCommand(\n sandbox,\n `mountpoint -q ${quotedPath} 2>/dev/null && sudo mount -t tmpfs tmpfs ${quotedPath} 2>/dev/null; ` +\n `sudo mkdir -p ${quotedPath} 2>/dev/null; ` +\n `sudo chown $(id -u):$(id -g) ${quotedPath}`,\n { timeout: MOUNT_COMMAND_TIMEOUT_MS },\n );\n if (mkdirResult.exitCode !== 0) {\n const error = mkdirResult.output || 'Failed to create mount directory';\n this.logger.debug(`${LOG_PREFIX} mkdir error for \"${mountPath}\":`, error);\n this.mounts.set(mountPath, { filesystem, state: 'error', config, error });\n return { success: false, mountPath, error };\n }\n } catch (err) {\n const error = `Failed to create mount directory: ${err}`;\n this.mounts.set(mountPath, { filesystem, state: 'error', config, error });\n return { success: false, mountPath, error };\n }\n\n // Build mount context for SDK-agnostic mount helpers\n const mountCtx: MountContext = {\n run: async (cmd, timeoutMs) => {\n const result = await runCommand(sandbox, cmd, timeoutMs !== undefined ? { timeout: timeoutMs } : undefined);\n return {\n exitCode: result.exitCode,\n stdout: result.output,\n stderr: result.exitCode !== 0 ? result.output : '',\n };\n },\n writeFile: async (path, content) => {\n await sandbox.fs.uploadFile(Buffer.from(content), path);\n },\n logger: this.logger,\n };\n\n try {\n switch (config.type) {\n case 's3':\n this.logger.debug(`${LOG_PREFIX} Mounting S3 at \"${mountPath}\"...`);\n await mountS3(mountPath, config, mountCtx);\n this.logger.debug(`${LOG_PREFIX} Mounted S3 bucket at ${mountPath}`);\n break;\n case 'gcs':\n this.logger.debug(`${LOG_PREFIX} Mounting GCS at \"${mountPath}\"...`);\n await mountGCS(mountPath, config, mountCtx);\n this.logger.debug(`${LOG_PREFIX} Mounted GCS bucket at ${mountPath}`);\n break;\n default: {\n const error = `Unsupported mount type: ${(config as FilesystemMountConfig).type}`;\n this.mounts.set(mountPath, { filesystem, state: 'unsupported', config, error });\n return { success: false, mountPath, error };\n }\n }\n } catch (error) {\n this.logger.error(\n `${LOG_PREFIX} Error mounting \"${filesystem.provider}\" (${filesystem.id}) at \"${mountPath}\":`,\n error,\n );\n this.mounts.set(mountPath, { filesystem, state: 'error', config, error: errorToString(error) });\n\n // Clean up the directory we created since mount failed\n await runCommand(sandbox, `sudo rmdir ${shellQuote(mountPath)} 2>/dev/null || true`, {\n timeout: MOUNT_COMMAND_TIMEOUT_MS,\n });\n this.logger.debug(`${LOG_PREFIX} Cleaned up directory after failed mount: ${mountPath}`);\n return { success: false, mountPath, error: errorToString(error) };\n }\n\n // Mark as mounted\n this.mounts.set(mountPath, { state: 'mounted', config });\n\n // Write marker file so we can detect config changes on reconnect\n await this.writeMarkerFile(mountPath);\n\n this.logger.debug(`${LOG_PREFIX} Mounted \"${mountPath}\"`);\n return { success: true, mountPath };\n }\n\n /**\n * Unmount a filesystem from a path in the sandbox.\n */\n async unmount(mountPath: string): Promise<void> {\n validateMountPath(mountPath);\n\n if (!this._sandbox) {\n throw new SandboxNotReadyError(this.id);\n }\n const sandbox = this._sandbox;\n\n this.logger.debug(`${LOG_PREFIX} Unmounting \"${mountPath}\"...`);\n\n // Try fusermount first (user-space), then lazy umount as fallback.\n // Do NOT pkill the FUSE daemon — a killed daemon leaves a stale mount\n // (ENOTCONN) that blocks subsequent mkdir/stat on the path.\n const quotedPath = shellQuote(mountPath);\n await runCommand(\n sandbox,\n `sudo fusermount -u ${quotedPath} 2>/dev/null; ` +\n `sudo umount -l ${quotedPath} 2>/dev/null; ` +\n // Last resort: move a stuck FUSE mount aside so the directory can be cleaned up.\n `mountpoint -q ${quotedPath} 2>/dev/null && ` +\n `{ _p=\"/tmp/.mastra-defunct-$$\"; sudo mkdir -p \"$_p\" && sudo mount --move ${quotedPath} \"$_p\" 2>/dev/null; sudo umount -l \"$_p\" 2>/dev/null; sudo rmdir \"$_p\" 2>/dev/null; }`,\n { timeout: MOUNT_COMMAND_TIMEOUT_MS },\n );\n\n this.mounts.delete(mountPath);\n\n // Clean up marker file and mount directory in one round-trip.\n // rm -f always exits 0, so the combined exit code reflects rmdir.\n const markerPath = `/tmp/.mastra-mounts/${this.mounts.markerFilename(mountPath)}`;\n const rmdirResult = await runCommand(\n sandbox,\n `rm -f ${shellQuote(markerPath)} 2>/dev/null; sudo rmdir ${quotedPath} 2>&1`,\n {\n timeout: MOUNT_COMMAND_TIMEOUT_MS,\n },\n );\n if (rmdirResult.exitCode === 0) {\n this.logger.debug(`${LOG_PREFIX} Unmounted and removed ${mountPath}`);\n } else {\n this.logger.debug(\n `${LOG_PREFIX} Unmounted ${mountPath} (directory not removed: ${rmdirResult.output.trim() || 'not empty'})`,\n );\n }\n }\n\n /**\n * Unmount all stale mounts that are not in the expected mounts list.\n * Also cleans up orphaned directories and marker files from failed mount attempts.\n * Call this after reconnecting to an existing sandbox to clean up old mounts.\n */\n async reconcileMounts(expectedMountPaths: string[]): Promise<void> {\n if (!this._sandbox) return;\n const sandbox = this._sandbox;\n\n this.logger.debug(`${LOG_PREFIX} Reconciling mounts. Expected paths:`, expectedMountPaths);\n\n // Get current FUSE mounts\n let currentMounts: string[] = [];\n try {\n const mountsResult = await runCommand(\n sandbox,\n `grep -E 'fuse\\\\.(s3fs|gcsfuse)' /proc/mounts | awk '{print $2}'`,\n { timeout: MOUNT_COMMAND_TIMEOUT_MS },\n );\n currentMounts = mountsResult.output\n .trim()\n .split('\\n')\n .filter(p => p.length > 0);\n } catch (err) {\n this.logger.debug(`${LOG_PREFIX} Could not read /proc/mounts: ${err}`);\n return;\n }\n\n this.logger.debug(`${LOG_PREFIX} Current FUSE mounts in sandbox:`, currentMounts);\n\n // Read our marker files to know which mounts WE created\n let markerFiles: string[] = [];\n try {\n const markersResult = await runCommand(sandbox, 'ls /tmp/.mastra-mounts/ 2>/dev/null || echo \"\"', {\n timeout: MOUNT_COMMAND_TIMEOUT_MS,\n });\n markerFiles = markersResult.output\n .trim()\n .split('\\n')\n .filter(f => f.length > 0 && SAFE_MARKER_NAME.test(f));\n } catch (err) {\n this.logger.debug(`${LOG_PREFIX} Could not read marker files: ${err}`);\n }\n\n // Build a map of mount paths -> marker filenames for mounts WE created\n const managedMountPaths = new Map<string, string>();\n for (const markerFile of markerFiles) {\n const markerResult = await runCommand(sandbox, `cat \"/tmp/.mastra-mounts/${markerFile}\" 2>/dev/null || echo \"\"`, {\n timeout: MOUNT_COMMAND_TIMEOUT_MS,\n });\n const parsed = this.mounts.parseMarkerContent(markerResult.output.trim());\n if (parsed && SAFE_MOUNT_PATH.test(parsed.path)) {\n managedMountPaths.set(parsed.path, markerFile);\n }\n }\n\n // Find mounts that exist but shouldn't — only unmount if WE created them (have a marker)\n const staleMounts = currentMounts.filter(path => !expectedMountPaths.includes(path));\n\n for (const stalePath of staleMounts) {\n if (managedMountPaths.has(stalePath)) {\n this.logger.debug(`${LOG_PREFIX} Found stale managed FUSE mount at \"${stalePath}\", unmounting...`);\n try {\n await this.unmount(stalePath);\n } catch (err) {\n this.logger.debug(`${LOG_PREFIX} Failed to unmount stale mount at \"${stalePath}\": ${err}`);\n }\n } else {\n this.logger.debug(`${LOG_PREFIX} Found external FUSE mount at \"${stalePath}\", leaving untouched`);\n }\n }\n\n // Clean up orphaned marker files and empty directories from failed mounts\n try {\n const expectedMarkerFiles = new Set(expectedMountPaths.map(p => this.mounts.markerFilename(p)));\n\n // Build a reverse map: markerFile -> mountPath\n const markerToPath = new Map<string, string>();\n for (const [path, file] of managedMountPaths) {\n markerToPath.set(file, path);\n }\n\n for (const markerFile of markerFiles) {\n // If this marker file doesn't correspond to an expected mount path, clean it up\n if (!expectedMarkerFiles.has(markerFile)) {\n const mountPath = markerToPath.get(markerFile);\n\n if (mountPath) {\n // Only clean up directory if not currently FUSE mounted\n if (!currentMounts.includes(mountPath)) {\n this.logger.debug(`${LOG_PREFIX} Cleaning up orphaned marker and directory for ${mountPath}`);\n await runCommand(\n sandbox,\n `rm -f \"/tmp/.mastra-mounts/${markerFile}\" 2>/dev/null; sudo rmdir ${shellQuote(mountPath)} 2>/dev/null`,\n { timeout: MOUNT_COMMAND_TIMEOUT_MS },\n );\n }\n } else {\n // Malformed marker file - just delete it\n this.logger.debug(`${LOG_PREFIX} Removing malformed marker file: ${markerFile}`);\n await runCommand(sandbox, `rm -f \"/tmp/.mastra-mounts/${markerFile}\" 2>/dev/null || true`, {\n timeout: MOUNT_COMMAND_TIMEOUT_MS,\n });\n }\n }\n }\n } catch {\n // Ignore errors during orphan cleanup\n this.logger.debug(`${LOG_PREFIX} Error during orphan cleanup (non-fatal)`);\n }\n }\n\n /**\n * Write marker file for detecting config changes on reconnect.\n * Stores both the mount path and config hash in the file.\n */\n private async writeMarkerFile(mountPath: string): Promise<void> {\n if (!this._sandbox) return;\n\n const markerContent = this.mounts.getMarkerContent(mountPath);\n if (!markerContent) return;\n\n const filename = this.mounts.markerFilename(mountPath);\n const markerPath = `/tmp/.mastra-mounts/${filename}`;\n try {\n await runCommand(this._sandbox, 'mkdir -p /tmp/.mastra-mounts', { timeout: MOUNT_COMMAND_TIMEOUT_MS });\n await this._sandbox.fs.uploadFile(Buffer.from(markerContent, 'utf-8'), markerPath);\n } catch {\n // Non-fatal - marker is just for optimization\n this.logger.debug(`${LOG_PREFIX} Warning: Could not write marker file at ${markerPath}`);\n }\n }\n\n /**\n * Check if a path is already mounted and whether the config matches.\n *\n * @param mountPath - The mount path to check\n * @param newConfig - The new config to compare against the stored config\n * @returns 'not_mounted' | 'matching' | 'mismatched' | 'unmanaged'\n */\n private async checkExistingMount(\n mountPath: string,\n newConfig: DaytonaMountConfig,\n ): Promise<'not_mounted' | 'matching' | 'mismatched' | 'unmanaged'> {\n if (!this._sandbox) throw new SandboxNotReadyError(this.id);\n const sandbox = this._sandbox;\n\n // Check if path is a mount point\n try {\n const mountCheck = await runCommand(\n sandbox,\n `mountpoint -q ${shellQuote(mountPath)} && echo \"mounted\" || echo \"not mounted\"`,\n { timeout: MOUNT_COMMAND_TIMEOUT_MS },\n );\n if (mountCheck.output.trim() !== 'mounted') {\n return 'not_mounted';\n }\n } catch {\n return 'not_mounted';\n }\n\n // Path is mounted — check if config matches via marker file\n const filename = this.mounts.markerFilename(mountPath);\n const markerPath = `/tmp/.mastra-mounts/${filename}`;\n let parsed;\n try {\n const markerResult = await runCommand(sandbox, `cat ${shellQuote(markerPath)} 2>/dev/null || echo \"\"`, {\n timeout: MOUNT_COMMAND_TIMEOUT_MS,\n });\n parsed = this.mounts.parseMarkerContent(markerResult.output.trim());\n } catch {\n // Marker doesn't exist or can't be read - treat as unmanaged\n return 'unmanaged';\n }\n\n if (!parsed) return 'unmanaged';\n\n // Compute hash of the NEW config and compare with stored hash\n const newConfigHash = this.mounts.computeConfigHash(newConfig);\n this.logger.debug(\n `${LOG_PREFIX} Marker check - stored hash: \"${parsed.configHash}\", new config hash: \"${newConfigHash}\"`,\n );\n\n if (parsed.path === mountPath && parsed.configHash === newConfigHash) {\n return 'matching';\n }\n\n return 'mismatched';\n }\n\n // ---------------------------------------------------------------------------\n // Internal Helpers\n // ---------------------------------------------------------------------------\n\n /**\n * Try to find and reconnect to an existing Daytona sandbox by ID.\n * Returns the sandbox if found and usable, or null if a fresh one should\n * be created.\n */\n private async detectWorkingDir(): Promise<void> {\n if (!this._sandbox) return;\n try {\n const result = await runCommand(this._sandbox, 'pwd', { timeout: MOUNT_COMMAND_TIMEOUT_MS });\n const dir = result.output?.trim();\n if (dir) {\n this._workingDir = dir;\n this.logger.debug(`${LOG_PREFIX} Detected working directory: ${dir}`);\n }\n } catch {\n this.logger.debug(`${LOG_PREFIX} Could not detect working directory, will omit from instructions`);\n }\n }\n\n private async findExistingSandbox(): Promise<Sandbox | null> {\n const DEAD_STATES: SandboxState[] = [\n SandboxState.DESTROYED,\n SandboxState.DESTROYING,\n SandboxState.ERROR,\n SandboxState.BUILD_FAILED,\n ];\n\n // Prefer the stored Daytona ID (same-process stop→start); fall back to name\n // for cross-process reconnection (e.g. process restart).\n const lookupKey = this._daytonaSandboxId ?? this.sandboxName;\n if (!lookupKey) {\n return null;\n }\n\n let sandbox: Sandbox;\n\n try {\n sandbox = await this._daytona!.get(lookupKey);\n } catch (error) {\n if (error instanceof DaytonaNotFoundError) {\n this._daytonaSandboxId = undefined;\n return null;\n }\n // Any other error (auth, transient, network) — propagate so the caller\n // can handle or retry rather than silently creating a duplicate sandbox.\n throw error;\n }\n\n const state = sandbox.state;\n\n if (state && DEAD_STATES.includes(state)) {\n this.logger.debug(`${LOG_PREFIX} Existing sandbox ${sandbox.id} is dead (${state}), deleting and creating fresh`);\n try {\n await this._daytona!.delete(sandbox);\n } catch {\n // Best-effort cleanup of dead sandbox\n }\n return null;\n }\n\n if (state !== SandboxState.STARTED) {\n this.logger.debug(`${LOG_PREFIX} Restarting sandbox ${sandbox.id} (state: ${state})`);\n await this.waitForStableStateAndStart(sandbox);\n }\n\n return sandbox;\n }\n\n /**\n * Transitional states where the Daytona API will reject start() with\n * \"State change in progress\". We poll until the sandbox reaches a stable\n * state before attempting start().\n */\n private static readonly TRANSITIONAL_STATES: SandboxState[] = [\n SandboxState.STARTING,\n SandboxState.STOPPING,\n SandboxState.CREATING,\n SandboxState.RESTORING,\n SandboxState.ARCHIVING,\n SandboxState.RESIZING,\n SandboxState.PULLING_SNAPSHOT,\n SandboxState.BUILDING_SNAPSHOT,\n ];\n\n /**\n * Wait for the sandbox to leave a transitional state, then start it if needed.\n * Polls every 2s for up to 120s. If the sandbox reaches STARTED on its own\n * (e.g. it was STARTING), we skip the start() call. If start() still fails\n * with \"State change in progress\", we retry with backoff.\n */\n private async waitForStableStateAndStart(sandbox: Sandbox): Promise<void> {\n const MAX_WAIT_MS = 120_000;\n const POLL_INTERVAL_MS = 2_000;\n const deadline = Date.now() + MAX_WAIT_MS;\n\n let current = sandbox;\n\n // Phase 1: Poll until the reported state is no longer transitional\n while (current.state && DaytonaSandbox.TRANSITIONAL_STATES.includes(current.state) && Date.now() < deadline) {\n this.logger.debug(`${LOG_PREFIX} Sandbox ${current.id} is in transitional state (${current.state}), waiting...`);\n await new Promise(r => setTimeout(r, POLL_INTERVAL_MS));\n current = await this._daytona!.get(current.id);\n }\n\n if (current.state === SandboxState.STARTED) {\n // Reached STARTED on its own — update the reference and return\n Object.assign(sandbox, current);\n return;\n }\n\n // Phase 2: Attempt start() with retries for \"State change in progress\"\n while (Date.now() < deadline) {\n try {\n await this._daytona!.start(current);\n return;\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n if (msg.includes('State change in progress') && Date.now() < deadline) {\n this.logger.debug(`${LOG_PREFIX} start() returned \"State change in progress\", retrying...`);\n await new Promise(r => setTimeout(r, POLL_INTERVAL_MS));\n current = await this._daytona!.get(current.id);\n if (current.state === SandboxState.STARTED) {\n Object.assign(sandbox, current);\n return;\n }\n continue;\n }\n throw error;\n }\n }\n\n // Last-ditch attempt after deadline\n await this._daytona!.start(current);\n }\n\n /**\n * Check if an error indicates the sandbox is dead/gone.\n * Uses DaytonaNotFoundError from the SDK when available,\n * with string fallback for edge cases.\n *\n * String patterns observed in @daytonaio/sdk@0.143.0 error messages.\n * Update if SDK error messages change in future versions.\n */\n private isSandboxDeadError(error: unknown): boolean {\n if (!error) return false;\n if (error instanceof DaytonaNotFoundError) return true;\n const errorStr = String(error);\n return SANDBOX_DEAD_PATTERNS.some(pattern => pattern.test(errorStr));\n }\n\n /**\n * Handle sandbox timeout by clearing the instance and resetting state.\n */\n private handleSandboxTimeout(): void {\n this._sandbox = null;\n\n // Reset mounted entries to pending so they get re-mounted on restart\n if (this.mounts) {\n for (const [path, entry] of this.mounts.entries) {\n if (entry.state === 'mounted' || entry.state === 'mounting') {\n this.mounts.set(path, { state: 'pending' });\n }\n }\n }\n\n this.status = 'stopped';\n }\n\n // ---------------------------------------------------------------------------\n // Retry on Dead\n // ---------------------------------------------------------------------------\n\n /**\n * Execute a function, retrying once if the sandbox is found to be dead.\n * Used by DaytonaProcessManager to handle stale sandboxes transparently.\n */\n async retryOnDead<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n if (this.isSandboxDeadError(error) && !this._isRetrying) {\n this.handleSandboxTimeout();\n this._isRetrying = true;\n try {\n await this.ensureRunning();\n return await fn();\n } finally {\n this._isRetrying = false;\n }\n }\n throw error;\n }\n }\n}\n"]}