@mastra/e2b 0.1.0 → 0.1.1-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/LICENSE.md +15 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/sandbox/index.d.ts +1 -1
- package/dist/sandbox/index.d.ts.map +1 -1
- package/package.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# @mastra/e2b
|
|
2
2
|
|
|
3
|
+
## 0.1.1-alpha.0
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Removed working directory from sandbox instructions to avoid breaking prompt caching. ([#13520](https://github.com/mastra-ai/mastra/pull/13520))
|
|
8
|
+
|
|
9
|
+
- Remove internal `processes` field from sandbox provider options ([#13597](https://github.com/mastra-ai/mastra/pull/13597))
|
|
10
|
+
|
|
11
|
+
The `processes` field is no longer exposed in constructor options for E2B, Daytona, and Blaxel sandbox providers. This field is managed internally and was not intended to be user-configurable.
|
|
12
|
+
|
|
13
|
+
- Updated dependencies [[`504fc8b`](https://github.com/mastra-ai/mastra/commit/504fc8b9d0ddab717577ad3bf9c95ea4bd5377bd), [`f9c150b`](https://github.com/mastra-ai/mastra/commit/f9c150b7595ad05ad9cc9a11098e2944361e8c22), [`88de7e8`](https://github.com/mastra-ai/mastra/commit/88de7e8dfe4b7e1951a9e441bb33136e705ce24e), [`edee4b3`](https://github.com/mastra-ai/mastra/commit/edee4b37dff0af515fc7cc0e8d71ee39e6a762f0), [`3790c75`](https://github.com/mastra-ai/mastra/commit/3790c7578cc6a47d854eb12d89e6b1912867fe29), [`e7a235b`](https://github.com/mastra-ai/mastra/commit/e7a235be6472e0c870ed6c791ddb17c492dc188b), [`d51d298`](https://github.com/mastra-ai/mastra/commit/d51d298953967aab1f58ec965b644d109214f085), [`6dbeeb9`](https://github.com/mastra-ai/mastra/commit/6dbeeb94a8b1eebb727300d1a98961f882180794), [`d5f0d8d`](https://github.com/mastra-ai/mastra/commit/d5f0d8d6a03e515ddaa9b5da19b7e44b8357b07b), [`09c3b18`](https://github.com/mastra-ai/mastra/commit/09c3b1802ff14e243a8a8baea327440bc8cc2e32), [`b896379`](https://github.com/mastra-ai/mastra/commit/b8963791c6afa79484645fcec596a201f936b9a2), [`85c84eb`](https://github.com/mastra-ai/mastra/commit/85c84ebb78aebfcba9d209c8e152b16d7a00cb71), [`a89272a`](https://github.com/mastra-ai/mastra/commit/a89272a5d71939b9fcd284e6a6dc1dd091a6bdcf), [`ee9c8df`](https://github.com/mastra-ai/mastra/commit/ee9c8df644f19d055af5f496bf4942705f5a47b7), [`77b4a25`](https://github.com/mastra-ai/mastra/commit/77b4a254e51907f8ff3a3ba95596a18e93ae4b35), [`276246e`](https://github.com/mastra-ai/mastra/commit/276246e0b9066a1ea48bbc70df84dbe528daaf99), [`08ecfdb`](https://github.com/mastra-ai/mastra/commit/08ecfdbdad6fb8285deef86a034bdf4a6047cfca), [`d5f628c`](https://github.com/mastra-ai/mastra/commit/d5f628ca86c6f6f3ff1035d52f635df32dd81cab), [`524c0f3`](https://github.com/mastra-ai/mastra/commit/524c0f3c434c3d9d18f66338dcef383d6161b59c), [`c18a0e9`](https://github.com/mastra-ai/mastra/commit/c18a0e9cef1e4ca004b2963d35e4cfc031971eac), [`4bd21ea`](https://github.com/mastra-ai/mastra/commit/4bd21ea43d44d0a0427414fc047577f9f0aa3bec), [`115a7a4`](https://github.com/mastra-ai/mastra/commit/115a7a47db5e9896fec12ae6507501adb9ec89bf), [`22a48ae`](https://github.com/mastra-ai/mastra/commit/22a48ae2513eb54d8d79dad361fddbca97a155e8), [`3c6ef79`](https://github.com/mastra-ai/mastra/commit/3c6ef798481e00d6d22563be2de98818fd4dd5e0), [`9311c17`](https://github.com/mastra-ai/mastra/commit/9311c17d7a0640d9c4da2e71b814dc67c57c6369), [`7edf78f`](https://github.com/mastra-ai/mastra/commit/7edf78f80422c43e84585f08ba11df0d4d0b73c5), [`1c4221c`](https://github.com/mastra-ai/mastra/commit/1c4221cf6032ec98d0e094d4ee11da3e48490d96), [`d25b9ea`](https://github.com/mastra-ai/mastra/commit/d25b9eabd400167255a97b690ffbc4ee4097ded5), [`fe1ce5c`](https://github.com/mastra-ai/mastra/commit/fe1ce5c9211c03d561606fda95cbfe7df1d9a9b5), [`b03c0e0`](https://github.com/mastra-ai/mastra/commit/b03c0e0389a799523929a458b0509c9e4244d562), [`0a8366b`](https://github.com/mastra-ai/mastra/commit/0a8366b0a692fcdde56c4d526e4cf03c502ae4ac), [`85664e9`](https://github.com/mastra-ai/mastra/commit/85664e9fd857320fbc245e301f764f45f66f32a3), [`bc79650`](https://github.com/mastra-ai/mastra/commit/bc796500c6e0334faa158a96077e3fb332274869), [`9257d01`](https://github.com/mastra-ai/mastra/commit/9257d01d1366d81f84c582fe02b5e200cf9621f4), [`3a3a59e`](https://github.com/mastra-ai/mastra/commit/3a3a59e8ffaa6a985fe3d9a126a3f5ade11a6724), [`3108d4e`](https://github.com/mastra-ai/mastra/commit/3108d4e649c9fddbf03253a6feeb388a5fa9fa5a), [`0c33b2c`](https://github.com/mastra-ai/mastra/commit/0c33b2c9db537f815e1c59e2c898ffce2e395a79), [`191e5bd`](https://github.com/mastra-ai/mastra/commit/191e5bd29b82f5bda35243945790da7bc7b695c2), [`f77cd94`](https://github.com/mastra-ai/mastra/commit/f77cd94c44eabed490384e7d19232a865e13214c), [`e8135c7`](https://github.com/mastra-ai/mastra/commit/e8135c7e300dac5040670eec7eab896ac6092e30), [`daca48f`](https://github.com/mastra-ai/mastra/commit/daca48f0fb17b7ae0b62a2ac40cf0e491b2fd0b7), [`257d14f`](https://github.com/mastra-ai/mastra/commit/257d14faca5931f2e4186fc165b6f0b1f915deee), [`352f25d`](https://github.com/mastra-ai/mastra/commit/352f25da316b24cdd5b410fd8dddf6a8b763da2a), [`93477d0`](https://github.com/mastra-ai/mastra/commit/93477d0769b8a13ea5ed73d508d967fb23eaeed9), [`31c78b3`](https://github.com/mastra-ai/mastra/commit/31c78b3eb28f58a8017f1dcc795c33214d87feac), [`0bc0720`](https://github.com/mastra-ai/mastra/commit/0bc07201095791858087cc56f353fcd65e87ab54), [`36516ac`](https://github.com/mastra-ai/mastra/commit/36516aca1021cbeb42e74751b46a2614101f37c8), [`e947652`](https://github.com/mastra-ai/mastra/commit/e9476527fdecb4449e54570e80dfaf8466901254), [`3c6ef79`](https://github.com/mastra-ai/mastra/commit/3c6ef798481e00d6d22563be2de98818fd4dd5e0), [`9257d01`](https://github.com/mastra-ai/mastra/commit/9257d01d1366d81f84c582fe02b5e200cf9621f4), [`ec248f6`](https://github.com/mastra-ai/mastra/commit/ec248f6b56e8a037c066c49b2178e2507471d988)]:
|
|
14
|
+
- @mastra/core@1.9.0-alpha.0
|
|
15
|
+
|
|
3
16
|
## 0.1.0
|
|
4
17
|
|
|
5
18
|
### Minor Changes
|
package/LICENSE.md
CHANGED
|
@@ -1,3 +1,18 @@
|
|
|
1
|
+
Portions of this software are licensed as follows:
|
|
2
|
+
|
|
3
|
+
- All content that resides under any directory named "ee/" within this
|
|
4
|
+
repository, including but not limited to:
|
|
5
|
+
- `packages/core/src/auth/ee/`
|
|
6
|
+
- `packages/server/src/server/auth/ee/`
|
|
7
|
+
is licensed under the license defined in `ee/LICENSE`.
|
|
8
|
+
|
|
9
|
+
- All third-party components incorporated into the Mastra Software are
|
|
10
|
+
licensed under the original license provided by the owner of the
|
|
11
|
+
applicable component.
|
|
12
|
+
|
|
13
|
+
- Content outside of the above-mentioned directories or restrictions is
|
|
14
|
+
available under the "Apache License 2.0" as defined below.
|
|
15
|
+
|
|
1
16
|
# Apache License 2.0
|
|
2
17
|
|
|
3
18
|
Copyright (c) 2025 Kepler Software, Inc.
|
package/dist/index.cjs
CHANGED
|
@@ -502,7 +502,7 @@ var E2BSandbox = class extends workspace.MastraSandbox {
|
|
|
502
502
|
_getDefaultInstructions() {
|
|
503
503
|
const mountCount = this.mounts.entries.size;
|
|
504
504
|
const mountInfo = mountCount > 0 ? ` ${mountCount} filesystem(s) mounted via FUSE.` : "";
|
|
505
|
-
return `Cloud sandbox
|
|
505
|
+
return `Cloud sandbox.${mountInfo}`;
|
|
506
506
|
}
|
|
507
507
|
// ---------------------------------------------------------------------------
|
|
508
508
|
// Mounting
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/template.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","../src/provider.ts"],"names":["createHash","Template","ProcessHandle","SandboxProcessManager","MastraSandbox","SandboxNotReadyError","Sandbox","template","buildResult"],"mappings":";;;;;;;AAiEO,IAAM,0BAAA,GAA6B,IAAA;AAgCnC,SAAS,8BAAA,GAA0D;AACxE,EAAA,MAAM,WAAA,GAAc,CAAC,MAAA,EAAQ,MAAM,CAAA;AACnC,EAAA,MAAM,MAAA,GAAS,EAAE,OAAA,EAAS,0BAAA,EAA4B,WAAA,EAAY;AAElE,EAAA,MAAM,IAAA,GAAOA,kBAAW,QAAQ,CAAA,CAC7B,OAAO,IAAA,CAAK,SAAA,CAAU,QAAQ,MAAA,CAAO,IAAA,CAAK,MAAM,CAAA,CAAE,IAAA,EAAM,CAAC,CAAA,CACzD,OAAO,KAAK,CAAA,CACZ,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA;AAEd,EAAA,MAAM,WAAWC,YAAA,EAAS,CAAE,aAAa,MAAM,CAAA,CAAE,WAAW,WAAW,CAAA;AAKvE,EAAA,OAAO;AAAA,IACL,QAAA;AAAA,IACA,EAAA,EAAI,UAAU,IAAI,CAAA,CAAA;AAAA,IAClB;AAAA,GACF;AACF;;;AC9GO,IAAM,UAAA,GAAa,eAAA;AAmC1B,IAAM,gBAAA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AA,EAAqC,SAAS,GAAA,EAAO;AAAA,MAC7F,GAAA,EAAK;AAAA,QACH,IAAA,EAAM,QAAA;AAAA,QACN,WAAA,EAAa,uBAAA;AAAA,QACb,oBAAA,EAAsB,EAAE,IAAA,EAAM,QAAA;AAAS,OACzC;AAAA,MACA,QAAA,EAAU;AAAA,QACR,IAAA,EAAM,QAAA;AAAA,QACN,WAAA,EAAa,iBAAA;AAAA,QACb,oBAAA,EAAsB;AAAA,OACxB;AAAA,MACA,MAAA,EAAQ,EAAE,IAAA,EAAM,QAAA,EAAU,aAAa,4BAAA,EAA6B;AAAA,MACpE,MAAA,EAAQ,EAAE,IAAA,EAAM,QAAA,EAAU,aAAa,6BAAA,EAA8B;AAAA,MACrE,MAAA,EAAQ,EAAE,IAAA,EAAM,QAAA,EAAU,aAAa,aAAA,EAAc;AAAA,MACrD,WAAA,EAAa,EAAE,IAAA,EAAM,QAAA,EAAU,aAAa,kBAAA;AAAmB;AACjE,GACF;AAAA,EACA,aAAA,EAAe,CAAA,MAAA,KAAU,IAAI,UAAA,CAAW,MAAM;AAChD","file":"index.cjs","sourcesContent":["/**\n * E2B Template Utilities\n *\n * Helper functions for creating and managing E2B sandbox templates.\n */\nimport { createHash } from 'node:crypto';\nimport { Template } from 'e2b';\nimport type { TemplateBuilder } from 'e2b';\n\n// =============================================================================\n// Template Types\n// =============================================================================\n\n/**\n * Template specification for E2B sandbox.\n *\n * Can be:\n * - `string` - Existing template ID (e.g., 'base', 'my-custom-template')\n * - `TemplateBuilder` - A built template object from Template()\n * - `(base: TemplateBuilder) => TemplateBuilder` - Callback to customize the base template\n *\n * @example Using template ID\n * ```typescript\n * new E2BSandbox({ template: 'my-custom-template' })\n * ```\n *\n * @example Using Template builder\n * ```typescript\n * import { Template } from 'e2b';\n *\n * new E2BSandbox({\n * template: Template()\n * .fromUbuntuImage('22.04')\n * .aptInstall(['s3fs', 'curl'])\n * .setEnvs({ NODE_ENV: 'production' })\n * })\n * ```\n *\n * @example Customizing default mountable template\n * ```typescript\n * new E2BSandbox({\n * template: base => base\n * .aptInstall(['nodejs', 'npm'])\n * .runCmd('npm install -g typescript')\n * })\n * ```\n */\nexport type TemplateSpec = string | TemplateBuilder | ((base: TemplateBuilder) => TemplateBuilder);\n\n/**\n * Result from createMountableTemplate containing both the template and its ID.\n */\nexport interface MountableTemplateResult {\n /** The template builder with mount dependencies */\n template: TemplateBuilder;\n /** Deterministic template ID for caching */\n id: string;\n /** List of apt packages installed in the template */\n aptPackages: string[];\n}\n\n/**\n * Version of the default mountable template.\n * Increment this when changing the default template dependencies.\n */\nexport const MOUNTABLE_TEMPLATE_VERSION = 'v1';\n\n/**\n * Create a base template with FUSE mounting dependencies pre-installed.\n *\n * This template includes s3fs and fuse packages required for mounting\n * cloud filesystems (S3, GCS, R2) into the sandbox.\n *\n * The returned `id` is deterministic, allowing E2BSandbox to check if\n * the template already exists before building it.\n *\n * @example Basic usage\n * ```typescript\n * const { template, id } = createMountableTemplate();\n * // First time: builds and caches the template\n * // Subsequent times: reuses existing template\n * const sandbox = new E2BSandbox({ template });\n * ```\n *\n * @example With customization\n * ```typescript\n * const { template } = createMountableTemplate();\n * const customTemplate = template\n * .aptInstall(['nodejs', 'npm'])\n * .runCmd('npm install -g typescript');\n *\n * // Note: customized templates get a unique ID, not the cached one\n * const sandbox = new E2BSandbox({ template: customTemplate });\n * ```\n *\n * @returns Object with template builder and deterministic ID\n */\nexport function createDefaultMountableTemplate(): MountableTemplateResult {\n const aptPackages = ['s3fs', 'fuse'];\n const config = { version: MOUNTABLE_TEMPLATE_VERSION, aptPackages };\n\n const hash = createHash('sha256')\n .update(JSON.stringify(config, Object.keys(config).sort()))\n .digest('hex')\n .slice(0, 16);\n\n const template = Template().fromTemplate('base').aptInstall(aptPackages);\n\n // Note: gcsfuse requires adding Google's apt repo which can be flaky\n // For now, we'll install it at mount time if needed\n\n return {\n template,\n id: `mastra-${hash}`,\n aptPackages,\n };\n}\n","/**\n * Shared types for E2B mount operations.\n */\n\nimport type { Sandbox } from 'e2b';\n\nexport const LOG_PREFIX = '[@mastra/e2b]';\n\nimport type { E2BGCSMountConfig } from './gcs';\nimport type { E2BS3MountConfig } from './s3';\n\n/**\n * Union of mount configs supported by E2B sandbox.\n */\nexport type E2BMountConfig = E2BS3MountConfig | E2BGCSMountConfig;\n\n/**\n * Context for mount operations.\n */\nexport interface MountContext {\n sandbox: Sandbox;\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 * Result of a mount operation.\n */\nexport interface MountOperationResult {\n success: boolean;\n error?: string;\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 */\nexport function validateEndpoint(endpoint: string): void {\n try {\n new URL(endpoint);\n } catch {\n throw new Error(`Invalid endpoint URL: \"${endpoint}\"`);\n }\n}\n","import type { FilesystemMountConfig } from '@mastra/core/workspace';\n\nimport { LOG_PREFIX, validateBucketName, validateEndpoint } from './types';\nimport type { MountContext } from './types';\n\n/**\n * S3 mount config for E2B (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 E2BS3MountConfig 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, 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: E2BS3MountConfig, ctx: MountContext): Promise<void> {\n const { sandbox, logger } = ctx;\n\n // Validate inputs before interpolating into shell commands\n validateBucketName(config.bucket);\n if (config.endpoint) {\n validateEndpoint(config.endpoint);\n }\n\n // Check if s3fs is installed\n const checkResult = await sandbox.commands.run('which s3fs || echo \"not found\"');\n if (checkResult.stdout.includes('not found')) {\n logger.warn(`${LOG_PREFIX} s3fs not found, attempting runtime installation...`);\n logger.info(\n `${LOG_PREFIX} Tip: For faster startup, use createMountableTemplate() to pre-install s3fs in your sandbox template`,\n );\n\n await sandbox.commands.run('sudo apt-get update 2>&1', { timeoutMs: 60000 });\n\n const installResult = await sandbox.commands.run(\n 'sudo apt-get install -y s3fs fuse 2>&1 || sudo apt-get install -y s3fs-fuse fuse 2>&1',\n { timeoutMs: 120000 },\n );\n\n if (installResult.exitCode !== 0) {\n throw new Error(\n `Failed to install s3fs. ` +\n `For S3 mounting, your template needs s3fs and fuse packages.\\n\\n` +\n `Option 1: Use createMountableTemplate() helper:\\n` +\n ` import { E2BSandbox, createMountableTemplate } from '@mastra/e2b';\\n` +\n ` const sandbox = new E2BSandbox({ template: createMountableTemplate() });\\n\\n` +\n `Option 2: Customize the base template:\\n` +\n ` new E2BSandbox({ template: base => base.aptInstall(['your-packages']) })\\n\\n` +\n `Error details: ${installResult.stderr || installResult.stdout}`,\n );\n }\n }\n\n // Get user's uid/gid for proper file ownership\n const idResult = await sandbox.commands.run('id -u && id -g');\n const [uid, gid] = idResult.stdout.trim().split('\\n');\n\n // Determine if we have credentials or using public bucket mode\n const hasCredentials = config.accessKeyId && config.secretAccessKey;\n const credentialsPath = '/tmp/.passwd-s3fs';\n\n // S3-compatible services (R2, MinIO, etc.) require credentials\n // public_bucket=1 only works for truly public AWS S3 buckets\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 if (hasCredentials) {\n // Write credentials file (remove old one first to avoid permission issues)\n const credentialsContent = `${config.accessKeyId}:${config.secretAccessKey}`;\n await sandbox.commands.run(`sudo rm -f ${credentialsPath}`);\n await sandbox.files.write(credentialsPath, credentialsContent);\n await sandbox.commands.run(`chmod 600 ${credentialsPath}`);\n }\n\n // Build mount options\n const mountOptions: string[] = [];\n\n if (hasCredentials) {\n mountOptions.push(`passwd_file=${credentialsPath}`);\n } else {\n // Public bucket mode - read-only access without credentials\n mountOptions.push('public_bucket=1');\n logger.debug(`${LOG_PREFIX} No credentials provided, mounting as public bucket (read-only)`);\n }\n\n mountOptions.push('allow_other'); // Allow non-root users to access the mount\n\n // Set uid/gid so mounted files are owned by user, not root\n if (uid && gid) {\n mountOptions.push(`uid=${uid}`, `gid=${gid}`);\n }\n\n if (config.endpoint) {\n // For S3-compatible storage (MinIO, R2, etc.)\n const endpoint = config.endpoint.replace(/\\/$/, '');\n mountOptions.push(`url=${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 // Mount with sudo (required for /dev/fuse access)\n const mountCmd = `sudo s3fs ${config.bucket} ${mountPath} -o ${mountOptions.join(' -o ')}`;\n logger.debug(`${LOG_PREFIX} Mounting S3:`, hasCredentials ? mountCmd.replace(credentialsPath, '***') : mountCmd);\n\n try {\n const result = await sandbox.commands.run(mountCmd, { timeoutMs: 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 } catch (error: unknown) {\n const errorObj = error as { result?: { exitCode: number; stdout: string; stderr: string } };\n const stderr = errorObj.result?.stderr || '';\n const stdout = errorObj.result?.stdout || '';\n logger.error(`${LOG_PREFIX} s3fs error:`, { stderr, stdout, error: String(error) });\n throw new Error(`Failed to mount S3 bucket: ${stderr || stdout || error}`);\n }\n}\n","import type { FilesystemMountConfig } from '@mastra/core/workspace';\n\nimport { LOG_PREFIX, validateBucketName } from './types';\nimport type { MountContext } from './types';\n\n/**\n * GCS mount config for E2B (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 E2BGCSMountConfig 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: E2BGCSMountConfig, ctx: MountContext): Promise<void> {\n const { sandbox, logger } = ctx;\n\n // Validate inputs before interpolating into shell commands\n validateBucketName(config.bucket);\n\n // Install gcsfuse if not present\n const checkResult = await sandbox.commands.run('which gcsfuse || echo \"not found\"');\n if (checkResult.stdout.includes('not found')) {\n // Detect Ubuntu codename for the gcsfuse repo (default to jammy if unknown)\n const codenameResult = await sandbox.commands.run('lsb_release -cs 2>/dev/null || echo jammy');\n const codename = codenameResult.stdout.trim() || 'jammy';\n\n // Use signed-by keyring instead of deprecated apt-key\n await sandbox.commands.run(\n 'curl -fsSL https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo gpg --dearmor -o /etc/apt/keyrings/gcsfuse.gpg && ' +\n `echo \"deb [signed-by=/etc/apt/keyrings/gcsfuse.gpg] https://packages.cloud.google.com/apt gcsfuse-${codename} main\" | sudo tee /etc/apt/sources.list.d/gcsfuse.list && ` +\n 'sudo apt-get update && sudo apt-get install -y gcsfuse',\n { timeoutMs: 120_000 },\n );\n }\n\n // Get user's uid/gid for proper file ownership\n const idResult = await sandbox.commands.run('id -u && id -g');\n const [uid, gid] = idResult.stdout.trim().split('\\n');\n\n // Build gcsfuse flags\n // Note: gcsfuse uses --uid/--gid flags, not -o uid=X style\n const uidGidFlags = uid && gid ? `--uid=${uid} --gid=${gid}` : '';\n\n const hasCredentials = !!config.serviceAccountKey;\n let mountCmd: string;\n\n if (hasCredentials) {\n // Write service account key with root ownership so sudo gcsfuse can read it\n const keyPath = '/tmp/gcs-key.json';\n await sandbox.commands.run(`sudo rm -f ${keyPath}`);\n await sandbox.files.write(keyPath, config.serviceAccountKey!);\n // Make readable by root (sudo gcsfuse runs as root)\n await sandbox.commands.run(`sudo chown root:root ${keyPath} && sudo chmod 600 ${keyPath}`);\n\n // Mount with credentials using --key-file flag\n // Use sudo for /dev/fuse access (same as s3fs)\n // -o allow_other lets non-root users access the FUSE mount\n mountCmd = `sudo gcsfuse --key-file=${keyPath} -o allow_other ${uidGidFlags} ${config.bucket} ${mountPath}`;\n } else {\n // Public bucket mode - read-only access without credentials\n // Use --anonymous-access flag (not -o option)\n // Use sudo for /dev/fuse access (same as s3fs)\n logger.debug(`${LOG_PREFIX} No credentials provided, mounting GCS as public bucket (read-only)`);\n\n mountCmd = `sudo gcsfuse --anonymous-access -o allow_other ${uidGidFlags} ${config.bucket} ${mountPath}`;\n }\n\n logger.debug(`${LOG_PREFIX} Mounting GCS:`, mountCmd);\n\n try {\n const result = await sandbox.commands.run(mountCmd, { timeoutMs: 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 } catch (error: unknown) {\n const errorObj = error as { result?: { exitCode: number; stdout: string; stderr: string } };\n const stderr = errorObj.result?.stderr || '';\n const stdout = errorObj.result?.stdout || '';\n logger.error(`${LOG_PREFIX} gcsfuse error:`, { stderr, stdout, error: String(error) });\n throw new Error(`Failed to mount GCS bucket: ${stderr || stdout || error}`);\n }\n}\n","/**\n * E2B Process Manager\n *\n * Implements SandboxProcessManager for E2B cloud sandboxes.\n * Wraps the E2B SDK's commands API (background mode, sendStdin, kill, list).\n */\n\nimport { ProcessHandle, SandboxProcessManager } from '@mastra/core/workspace';\nimport type { CommandResult, ProcessInfo, SpawnProcessOptions } from '@mastra/core/workspace';\nimport type { CommandHandle as E2BCommandHandle, Sandbox } from 'e2b';\nimport type { E2BSandbox } from './index';\n\n// =============================================================================\n// E2B Process Handle\n// =============================================================================\n\n/**\n * Wraps an E2B CommandHandle to conform to Mastra's ProcessHandle.\n * Not exported — internal to this module.\n *\n * Listener dispatch is handled by the base class. The manager's spawn()/get()\n * methods wire E2B's constructor-time callbacks to handle.emitStdout/emitStderr.\n */\nclass E2BProcessHandle extends ProcessHandle {\n readonly pid: number;\n\n private readonly _e2bHandle: E2BCommandHandle;\n private readonly _sandbox: Sandbox;\n private readonly _startTime: number;\n\n constructor(e2bHandle: E2BCommandHandle, sandbox: Sandbox, startTime: number, options?: SpawnProcessOptions) {\n super(options);\n this.pid = e2bHandle.pid;\n this._e2bHandle = e2bHandle;\n this._sandbox = sandbox;\n this._startTime = startTime;\n }\n\n /** Delegates to E2B's handle so exitCode reflects server-side state without needing wait(). */\n get exitCode(): number | undefined {\n return this._e2bHandle.exitCode;\n }\n\n async wait(): Promise<CommandResult> {\n try {\n const result = await this._e2bHandle.wait();\n return {\n success: result.exitCode === 0,\n exitCode: result.exitCode,\n stdout: this.stdout,\n stderr: this.stderr,\n executionTimeMs: Date.now() - this._startTime,\n };\n } catch (error) {\n // E2B throws CommandExitError for non-zero exit codes (has .exitCode directly)\n // Some E2B errors also carry stdout/stderr in error.result\n const errorObj = error as {\n exitCode?: number;\n result?: { exitCode: number; stdout: string; stderr: string };\n };\n const exitCode = errorObj.result?.exitCode ?? errorObj.exitCode ?? this.exitCode ?? 1;\n\n // Emit any output attached to the error (E2B sometimes puts it in .result)\n if (errorObj.result?.stdout) this.emitStdout(errorObj.result.stdout);\n if (errorObj.result?.stderr) this.emitStderr(errorObj.result.stderr);\n\n return {\n success: false,\n exitCode,\n stdout: this.stdout,\n stderr: this.stderr || (error instanceof Error ? error.message : String(error)),\n executionTimeMs: Date.now() - this._startTime,\n };\n }\n }\n\n async kill(): Promise<boolean> {\n if (this.exitCode !== undefined) return false;\n return this._e2bHandle.kill();\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.commands.sendStdin(this.pid, data);\n }\n}\n\n// =============================================================================\n// E2B Process Manager\n// =============================================================================\n\n/**\n * E2B implementation of SandboxProcessManager.\n * Uses the E2B SDK's commands.run() with background: true.\n */\nexport class E2BProcessManager extends SandboxProcessManager<E2BSandbox> {\n async spawn(command: string, options: SpawnProcessOptions = {}): Promise<ProcessHandle> {\n return this.sandbox.retryOnDead(async () => {\n const e2b = this.sandbox.e2b;\n\n // Merge default env with per-spawn env\n const mergedEnv = { ...this.env, ...options.env };\n const envs = Object.fromEntries(\n Object.entries(mergedEnv).filter((entry): entry is [string, string] => entry[1] !== undefined),\n );\n\n // Deferred reference — E2B requires callbacks at run() time, but data\n // arrives asynchronously after the promise resolves, so handle is always\n // assigned by the time the first callback fires.\n let handle: E2BProcessHandle;\n\n const e2bHandle = await e2b.commands.run(command, {\n background: true,\n stdin: true,\n cwd: options.cwd,\n envs,\n timeoutMs: options.timeout,\n onStdout: (data: string) => handle.emitStdout(data),\n onStderr: (data: string) => handle.emitStderr(data),\n });\n\n handle = new E2BProcessHandle(e2bHandle, e2b, Date.now(), options);\n this._tracked.set(handle.pid, handle);\n return handle;\n });\n }\n\n /**\n * List processes by querying E2B's commands API.\n * E2B manages all state server-side — no local tracking needed.\n */\n async list(): Promise<ProcessInfo[]> {\n const e2b = this.sandbox.e2b;\n const procs = await e2b.commands.list();\n return procs.map(proc => ({\n pid: proc.pid,\n command: [proc.cmd, ...proc.args].join(' '),\n running: true, // E2B only lists running processes\n }));\n }\n\n /**\n * Get a handle to a process by PID.\n * Checks base class tracking first, then falls back to commands.connect()\n * for processes spawned externally or before reconnection.\n */\n async get(pid: number): Promise<ProcessHandle | undefined> {\n const tracked = this._tracked.get(pid);\n if (tracked) return tracked;\n\n // Fall back to connect() for unknown PIDs (e.g., pre-existing processes)\n const e2b = this.sandbox.e2b;\n let handle: E2BProcessHandle;\n try {\n const e2bHandle = await e2b.commands.connect(pid, {\n onStdout: (data: string) => handle.emitStdout(data),\n onStderr: (data: string) => handle.emitStderr(data),\n });\n handle = new E2BProcessHandle(e2bHandle, e2b, Date.now());\n this._tracked.set(pid, handle);\n return handle;\n } catch {\n return undefined;\n }\n }\n}\n","/**\n * E2B Sandbox Provider\n *\n * A simplified E2B sandbox implementation that supports mounting\n * cloud filesystems (S3, GCS, R2) via FUSE.\n *\n * @see https://e2b.dev/docs\n */\n\nimport type { RequestContext } from '@mastra/core/di';\nimport type {\n SandboxInfo,\n WorkspaceFilesystem,\n MountResult,\n FilesystemMountConfig,\n ProviderStatus,\n MountManager,\n MastraSandboxOptions,\n} from '@mastra/core/workspace';\n\n/**\n * Inlined from `@mastra/core/workspace` to avoid requiring a newer core peer dep.\n */\ntype InstructionsOption = string | ((opts: { defaultInstructions: string; requestContext?: RequestContext }) => string);\nimport { MastraSandbox, SandboxNotReadyError } from '@mastra/core/workspace';\nimport { Sandbox, Template } from 'e2b';\nimport type { TemplateBuilder, TemplateClass } from 'e2b';\nimport { createDefaultMountableTemplate } from '../utils/template';\nimport type { TemplateSpec } from '../utils/template';\nimport { mountS3, mountGCS, LOG_PREFIX } from './mounts';\nimport type { E2BMountConfig, E2BS3MountConfig, E2BGCSMountConfig, MountContext } from './mounts';\nimport { E2BProcessManager } from './process-manager';\n\n/** Allowlist pattern for mount paths — absolute path with safe characters only. */\nconst SAFE_MOUNT_PATH = /^\\/[a-zA-Z0-9_.\\-/]+$/;\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}\n\n/** Allowlist for marker filenames from ls output — e.g. \"mount-abc123\" */\nconst SAFE_MARKER_NAME = /^mount-[a-z0-9]+$/;\n\n// =============================================================================\n// E2B Sandbox Options\n// =============================================================================\n\n/**\n * E2B sandbox provider configuration.\n */\nexport interface E2BSandboxOptions extends MastraSandboxOptions {\n /** Unique identifier for this sandbox instance */\n id?: string;\n /**\n * Sandbox template specification.\n *\n * - `string` - Use an existing template by ID\n * - `TemplateBuilder` - Use a custom template (e.g., from `createMountableTemplate()`)\n * - `(base) => base.aptInstall([...])` - Customize the default mountable template\n *\n * If not provided and mounting is used, a default template with s3fs will be built.\n * For best performance, pre-build your template and use the template ID.\n *\n * @see createDefaultMountableTemplate\n */\n template?: TemplateSpec;\n /** Execution timeout in milliseconds\n *\n * @default 300_000 // 5 minutes\n */\n timeout?: number;\n /** Environment variables to set in the sandbox */\n env?: Record<string, string>;\n /** Custom metadata */\n metadata?: Record<string, unknown>;\n\n /** Domain for self-hosted E2B. Falls back to E2B_DOMAIN env var. */\n domain?: string;\n /** API URL for self-hosted E2B. Falls back to E2B_API_URL env var. */\n apiUrl?: string;\n /** API key for authentication. Falls back to E2B_API_KEY env var. */\n apiKey?: string;\n /** Access token for authentication. Falls back to E2B_ACCESS_TOKEN env var. */\n accessToken?: string;\n /**\n * Custom instructions that override the default instructions\n * returned by `getInstructions()`.\n *\n * - `string` — Fully replaces the default instructions.\n * Pass an empty string to suppress instructions entirely.\n * - `(opts) => string` — Receives the default instructions and\n * optional request context so you can extend or customise per-request.\n */\n instructions?: InstructionsOption;\n}\n\n// =============================================================================\n// E2B Sandbox Implementation\n// =============================================================================\n\n/**\n * Simplified E2B sandbox implementation.\n *\n * Features:\n * - Single sandbox instance lifecycle\n * - Supports mounting cloud filesystems (S3, GCS, R2) via FUSE\n * - Automatic sandbox timeout handling with retry\n *\n * @example Basic usage\n * ```typescript\n * import { Workspace } from '@mastra/core/workspace';\n * import { E2BSandbox } from '@mastra/e2b';\n *\n * const sandbox = new E2BSandbox({\n * timeout: 60000,\n * });\n *\n * const workspace = new Workspace({ sandbox });\n * const result = await workspace.executeCode('console.log(\"Hello!\")');\n * ```\n *\n * @example With S3 filesystem mounting\n * ```typescript\n * import { Workspace } from '@mastra/core/workspace';\n * import { E2BSandbox } from '@mastra/e2b';\n * import { S3Filesystem } from '@mastra/s3';\n *\n * const workspace = new Workspace({\n * mounts: {\n * '/bucket': new S3Filesystem({\n * bucket: 'my-bucket',\n * region: 'us-east-1',\n * }),\n * },\n * sandbox: new E2BSandbox({ timeout: 60000 }),\n * });\n *\n * ```\n */\nexport class E2BSandbox extends MastraSandbox {\n readonly id: string;\n readonly name = 'E2BSandbox';\n readonly provider = 'e2b';\n status: ProviderStatus = 'pending';\n\n declare readonly mounts: MountManager; // Non-optional (initialized by BaseSandbox)\n declare readonly processes: E2BProcessManager;\n\n private _sandbox: Sandbox | null = null;\n private _createdAt: Date | null = null;\n private _isRetrying = false;\n private readonly timeout: number;\n private readonly templateSpec?: TemplateSpec;\n private readonly env: Record<string, string>;\n private readonly metadata: Record<string, unknown>;\n private readonly connectionOpts: Record<string, string>;\n private readonly _instructionsOverride?: InstructionsOption;\n\n /** Resolved template ID after building (if needed) */\n private _resolvedTemplateId?: string;\n\n /** Promise for template preparation (started in constructor) */\n private _templatePreparePromise?: Promise<string>;\n\n constructor(options: E2BSandboxOptions = {}) {\n super({\n ...options,\n name: 'E2BSandbox',\n processes: new E2BProcessManager({ env: options.env ?? {} }),\n });\n\n this.id = options.id ?? this.generateId();\n this.timeout = options.timeout ?? 300_000; // 5 minutes;\n this.templateSpec = options.template;\n this.env = options.env ?? {};\n this.metadata = options.metadata ?? {};\n this.connectionOpts = {\n ...(options.domain && { domain: options.domain }),\n ...(options.apiUrl && { apiUrl: options.apiUrl }),\n ...(options.apiKey && { apiKey: options.apiKey }),\n ...(options.accessToken && { accessToken: options.accessToken }),\n };\n\n this._instructionsOverride = options.instructions;\n\n // Start template preparation immediately in background\n // This way template build (if needed) begins before start() is called\n this._templatePreparePromise = this.resolveTemplate().catch(err => {\n this.logger.debug(`${LOG_PREFIX} Template preparation error (will retry on start):`, err);\n return ''; // Return empty string, will be retried in start()\n });\n }\n\n /**\n * Get the underlying E2B Sandbox instance for direct access to E2B APIs.\n *\n * Use this when you need to access E2B features not exposed through the\n * WorkspaceSandbox interface (e.g., files API, ports, etc.).\n *\n * @throws {SandboxNotReadyError} If the sandbox has not been started\n *\n * @example Direct file operations\n * ```typescript\n * const e2b = sandbox.e2b;\n * await e2b.files.write('/tmp/test.txt', 'Hello');\n * const content = await e2b.files.read('/tmp/test.txt');\n * const files = await e2b.files.list('/tmp');\n * ```\n *\n * @example Access ports\n * ```typescript\n * const e2b = sandbox.e2b;\n * const url = e2b.getHost(3000);\n * ```\n */\n get e2b(): Sandbox {\n if (!this._sandbox) {\n throw new SandboxNotReadyError(this.id);\n }\n return this._sandbox;\n }\n\n // ---------------------------------------------------------------------------\n // Lifecycle\n // ---------------------------------------------------------------------------\n\n /**\n * Start the E2B sandbox.\n * Handles template preparation, existing sandbox reconnection, and new sandbox creation.\n *\n * Status management and mount processing are handled by the base class.\n */\n async start(): Promise<void> {\n // Already have a sandbox instance\n if (this._sandbox) {\n return;\n }\n\n // Await template preparation (started in constructor) and existing sandbox search in parallel\n const [existingSandbox, templateId] = await Promise.all([\n this.findExistingSandbox(),\n this._templatePreparePromise || this.resolveTemplate(),\n ]);\n\n if (existingSandbox) {\n this._sandbox = existingSandbox;\n this._createdAt = new Date();\n this.logger.debug(`${LOG_PREFIX} Reconnected to existing sandbox for: ${this.id}`);\n\n // Clean up stale mounts from previous config\n // (processPending is called by base class after start completes)\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 return;\n }\n\n // If template preparation failed earlier, retry now\n let resolvedTemplateId = templateId;\n if (!resolvedTemplateId) {\n this.logger.debug(`${LOG_PREFIX} Template preparation failed earlier, retrying...`);\n resolvedTemplateId = await this.resolveTemplate();\n }\n\n // Create a new sandbox with our logical ID in metadata\n // Using betaCreate with autoPause so sandbox pauses on timeout instead of being destroyed\n this.logger.debug(`${LOG_PREFIX} Creating new sandbox for: ${this.id} with template: ${resolvedTemplateId}`);\n\n try {\n this._sandbox = await Sandbox.betaCreate(resolvedTemplateId, {\n ...this.connectionOpts,\n autoPause: true,\n metadata: {\n ...this.metadata,\n 'mastra-sandbox-id': this.id,\n },\n timeoutMs: this.timeout,\n });\n } catch (createError) {\n // If template not found (404), rebuild it and retry\n const errorStr = String(createError);\n if (errorStr.includes('404') && errorStr.includes('not found') && !this.templateSpec) {\n this.logger.debug(`${LOG_PREFIX} Template not found, rebuilding: ${templateId}`);\n this._resolvedTemplateId = undefined; // Clear cached ID to force rebuild\n const rebuiltTemplateId = await this.buildDefaultTemplate();\n\n this.logger.debug(`${LOG_PREFIX} Retrying sandbox creation with rebuilt template: ${rebuiltTemplateId}`);\n this._sandbox = await Sandbox.betaCreate(rebuiltTemplateId, {\n ...this.connectionOpts,\n autoPause: true,\n metadata: {\n ...this.metadata,\n 'mastra-sandbox-id': this.id,\n },\n timeoutMs: this.timeout,\n });\n } else {\n throw createError;\n }\n }\n\n this.logger.debug(`${LOG_PREFIX} Created sandbox ${this._sandbox.sandboxId} for logical ID: ${this.id}`);\n this._createdAt = new Date();\n // Note: processPending is called by base class after start completes\n }\n\n /**\n * Stop the E2B sandbox.\n * Unmounts all filesystems and releases the sandbox reference.\n * Status management is handled by the base class.\n */\n async stop(): Promise<void> {\n // Kill all background processes before stopping\n try {\n const procs = await this.processes.list();\n await Promise.all(procs.map(p => this.processes.kill(p.pid)));\n } catch {\n // Best-effort: sandbox may already be dead\n }\n\n // Unmount all filesystems before stopping\n // Collect keys first since unmount() mutates the map\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 this._sandbox = null;\n }\n\n /**\n * Destroy the E2B sandbox and clean up all resources.\n * Unmounts filesystems, kills the sandbox, and clears mount state.\n * Status management is handled by the base class.\n */\n async destroy(): Promise<void> {\n if (this._sandbox) {\n // Kill all background processes\n try {\n const procs = await this.processes.list();\n await Promise.all(procs.map(p => this.processes.kill(p.pid)));\n } catch {\n // Best-effort: sandbox may already be dead\n }\n\n // Unmount all filesystems\n // Collect keys first since unmount() mutates the map\n for (const mountPath of [...this.mounts.entries.keys()]) {\n try {\n await this.unmount(mountPath);\n } catch {\n // Ignore errors during cleanup\n }\n }\n\n try {\n await this._sandbox.kill();\n } catch {\n // Ignore errors during destroy\n }\n\n this._sandbox = null;\n }\n\n this.mounts.clear();\n }\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: Array.from(this.mounts.entries).map(([path, entry]) => ({\n path,\n filesystem: entry.filesystem?.provider ?? entry.config?.type ?? 'unknown',\n })),\n metadata: {\n ...this.metadata,\n },\n };\n }\n\n /**\n * Get instructions describing this E2B sandbox.\n * Used by agents to understand the execution environment.\n */\n getInstructions(opts?: { requestContext?: RequestContext }): string {\n if (this._instructionsOverride === undefined) return this._getDefaultInstructions();\n if (typeof this._instructionsOverride === 'string') return this._instructionsOverride;\n const defaultInstructions = this._getDefaultInstructions();\n return this._instructionsOverride({ defaultInstructions, requestContext: opts?.requestContext });\n }\n\n private _getDefaultInstructions(): string {\n const mountCount = this.mounts.entries.size;\n const mountInfo = mountCount > 0 ? ` ${mountCount} filesystem(s) mounted via FUSE.` : '';\n return `Cloud sandbox with /home/user as working directory.${mountInfo}`;\n }\n\n // ---------------------------------------------------------------------------\n // Mounting\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\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 E2BMountConfig | 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, unmounting to re-mount with new config...`);\n await this.unmount(mountPath);\n }\n this.logger.debug(`${LOG_PREFIX} Config type: ${config.type}`);\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\n // Check if directory exists and is non-empty (would shadow existing files)\n try {\n const checkResult = await this._sandbox.commands.run(\n `[ -d \"${mountPath}\" ] && [ \"$(ls -A \"${mountPath}\" 2>/dev/null)\" ] && echo \"non-empty\" || echo \"ok\"`,\n );\n if (checkResult.stdout.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 mount directory with sudo (for paths outside home dir like /data)\n // Then chown to current user so mount works without issues\n try {\n this.logger.debug(`${LOG_PREFIX} Creating mount directory for ${mountPath}...`);\n const mkdirCommand = `sudo mkdir -p \"${mountPath}\" && sudo chown $(id -u):$(id -g) \"${mountPath}\"`;\n\n this.logger.debug(`${LOG_PREFIX} Running command: ${mkdirCommand}`);\n const mkdirResult = await this._sandbox.commands.run(mkdirCommand);\n\n this.logger.debug(`${LOG_PREFIX} Created mount directory for mount path \"${mountPath}\":`, mkdirResult);\n } catch (mkdirError) {\n this.logger.debug(`${LOG_PREFIX} mkdir error for \"${mountPath}\":`, mkdirError);\n this.mounts.set(mountPath, { filesystem, state: 'error', config, error: String(mkdirError) });\n return { success: false, mountPath, error: String(mkdirError) };\n }\n\n // Create mount context for mount operations\n const mountCtx: MountContext = {\n sandbox: this._sandbox,\n logger: this.logger,\n };\n\n try {\n switch (config.type) {\n case 's3':\n this.logger.debug(`${LOG_PREFIX} Mounting S3 bucket at ${mountPath}...`);\n await mountS3(mountPath, config as E2BS3MountConfig, 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 bucket at ${mountPath}...`);\n await mountGCS(mountPath, config as E2BGCSMountConfig, mountCtx);\n this.logger.debug(`${LOG_PREFIX} Mounted GCS bucket at ${mountPath}`);\n break;\n default:\n this.mounts.set(mountPath, {\n filesystem,\n state: 'unsupported',\n config,\n error: `Unsupported mount type: ${(config as FilesystemMountConfig).type}`,\n });\n return {\n success: false,\n mountPath,\n error: `Unsupported mount type: ${(config as FilesystemMountConfig).type}`,\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: String(error) });\n\n // Clean up the directory we created since mount failed\n try {\n await this._sandbox!.commands.run(`sudo rmdir \"${mountPath}\" 2>/dev/null || true`);\n this.logger.debug(`${LOG_PREFIX} Cleaned up directory after failed mount: ${mountPath}`);\n } catch {\n // Ignore cleanup errors\n }\n\n return { success: false, mountPath, error: String(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\n this.logger.debug(`${LOG_PREFIX} Unmounting ${mountPath}...`);\n\n try {\n // Use fusermount for FUSE mounts, fall back to umount\n const result = await this._sandbox.commands.run(\n `sudo fusermount -u \"${mountPath}\" 2>/dev/null || sudo umount \"${mountPath}\"`,\n );\n if (result.exitCode !== 0) {\n this.logger.debug(`${LOG_PREFIX} Unmount warning: ${result.stderr || result.stdout}`);\n }\n } catch (error) {\n this.logger.debug(`${LOG_PREFIX} Unmount error:`, error);\n // Try lazy unmount as last resort\n await this._sandbox.commands.run(`sudo umount -l \"${mountPath}\" 2>/dev/null || true`);\n }\n\n this.mounts.delete(mountPath);\n\n // Clean up marker file\n const filename = this.mounts.markerFilename(mountPath);\n const markerPath = `/tmp/.mastra-mounts/${filename}`;\n await this._sandbox.commands.run(`rm -f \"${markerPath}\" 2>/dev/null || true`);\n\n // Remove empty mount directory (only if empty, rmdir fails on non-empty)\n // Use sudo since mount directories outside home (like /data) were created with sudo\n const rmdirResult = await this._sandbox.commands.run(`sudo rmdir \"${mountPath}\" 2>&1`);\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.stderr?.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) {\n throw new SandboxNotReadyError(this.id);\n }\n\n this.logger.debug(`${LOG_PREFIX} Reconciling mounts. Expected paths:`, expectedMountPaths);\n\n // Get current FUSE mounts in the sandbox\n const mountsResult = await this._sandbox.commands.run(\n `grep -E 'fuse\\\\.(s3fs|gcsfuse)' /proc/mounts | awk '{print $2}'`,\n );\n const currentMounts = mountsResult.stdout\n .trim()\n .split('\\n')\n .filter(p => p.length > 0);\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 const markersResult = await this._sandbox.commands.run(`ls /tmp/.mastra-mounts/ 2>/dev/null || echo \"\"`);\n const markerFiles = markersResult.stdout\n .trim()\n .split('\\n')\n .filter(f => f.length > 0 && SAFE_MARKER_NAME.test(f));\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 this._sandbox.commands.run(\n `cat \"/tmp/.mastra-mounts/${markerFile}\" 2>/dev/null || echo \"\"`,\n );\n const parsed = this.mounts.parseMarkerContent(markerResult.stdout.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 await this.unmount(stalePath);\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\n // Remove marker file\n await this._sandbox.commands.run(`rm -f \"/tmp/.mastra-mounts/${markerFile}\" 2>/dev/null || true`);\n\n // Try to remove the directory (will fail if not empty or doesn't exist, which is fine)\n await this._sandbox.commands.run(`sudo rmdir \"${mountPath}\" 2>/dev/null || true`);\n }\n } else {\n // Malformed marker file - just delete it\n this.logger.debug(`${LOG_PREFIX} Removing malformed marker file: ${markerFile}`);\n await this._sandbox.commands.run(`rm -f \"/tmp/.mastra-mounts/${markerFile}\" 2>/dev/null || true`);\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 // Deprecated\n // ---------------------------------------------------------------------------\n\n /** @deprecated Use `e2b` instead. */\n get instance(): Sandbox {\n return this.e2b;\n }\n\n /** @deprecated Use `status === 'running'` instead. */\n async isReady(): Promise<boolean> {\n return this.status === 'running' && this._sandbox !== null;\n }\n\n // ---------------------------------------------------------------------------\n // Internal Helpers\n // ---------------------------------------------------------------------------\n\n private generateId(): string {\n return `e2b-sandbox-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;\n }\n\n /**\n * Find an existing sandbox with matching mastra-sandbox-id metadata.\n * Returns the connected sandbox if found, null otherwise.\n */\n private async findExistingSandbox(): Promise<Sandbox | null> {\n try {\n // Query E2B for existing sandbox with our logical ID in metadata\n const paginator = Sandbox.list({\n ...this.connectionOpts,\n query: {\n metadata: { 'mastra-sandbox-id': this.id },\n state: ['running', 'paused'],\n },\n });\n\n const sandboxes = await paginator.nextItems();\n\n this.logger.debug(`${LOG_PREFIX} sandboxes:`, sandboxes);\n\n // Sandbox.list only returns running/paused sandboxes, so no need to filter\n if (sandboxes.length > 0) {\n const existingSandbox = sandboxes[0]!;\n this.logger.debug(\n `${LOG_PREFIX} Found existing sandbox for ${this.id}: ${existingSandbox.sandboxId} (state: ${existingSandbox.state})`,\n );\n return await Sandbox.connect(existingSandbox.sandboxId, this.connectionOpts);\n }\n } catch (e) {\n this.logger.debug(`${LOG_PREFIX} Error querying for existing sandbox:`, e);\n // Continue to create new sandbox\n }\n\n return null;\n }\n\n /**\n * Resolve the template specification to a template ID.\n *\n * - String: Use as-is (template ID)\n * - TemplateBuilder: Build and return the template ID\n * - Function: Apply to base mountable template, then build\n * - undefined: Use default mountable template (cached)\n */\n private async resolveTemplate(): Promise<string> {\n // If already resolved, return cached ID\n if (this._resolvedTemplateId) {\n return this._resolvedTemplateId;\n }\n\n // No template specified - use default mountable template with caching\n if (!this.templateSpec) {\n const { template, id } = createDefaultMountableTemplate();\n\n // Check if template already exists (cached from previous runs)\n const exists = await Template.exists(id, this.connectionOpts);\n if (exists) {\n this.logger.debug(`${LOG_PREFIX} Using cached mountable template: ${id}`);\n this._resolvedTemplateId = id;\n return id;\n }\n\n // Build the template (first time only)\n this.logger.debug(`${LOG_PREFIX} Building default mountable template: ${id}...`);\n const buildResult = await Template.build(template as TemplateClass, id, this.connectionOpts);\n this._resolvedTemplateId = buildResult.templateId;\n this.logger.debug(`${LOG_PREFIX} Template built and cached: ${buildResult.templateId}`);\n return buildResult.templateId;\n }\n\n // String template ID - use directly\n if (typeof this.templateSpec === 'string') {\n this._resolvedTemplateId = this.templateSpec;\n return this.templateSpec;\n }\n\n // TemplateBuilder or function - need to build\n let template: TemplateBuilder;\n let templateName: string;\n\n if (typeof this.templateSpec === 'function') {\n // Apply customization function to base mountable template\n const { template: baseTemplate } = createDefaultMountableTemplate();\n template = this.templateSpec(baseTemplate);\n // Custom templates get unique names since they're modified\n templateName = `mastra-custom-${this.id.replace(/[^a-zA-Z0-9-]/g, '-')}`;\n } else {\n // Use provided TemplateBuilder directly\n template = this.templateSpec;\n templateName = `mastra-${this.id.replace(/[^a-zA-Z0-9-]/g, '-')}`;\n }\n\n // Build the template\n this.logger.debug(`${LOG_PREFIX} Building custom template: ${templateName}...`);\n const buildResult = await Template.build(template as TemplateClass, templateName, this.connectionOpts);\n this._resolvedTemplateId = buildResult.templateId;\n this.logger.debug(`${LOG_PREFIX} Template built: ${buildResult.templateId}`);\n\n return buildResult.templateId;\n }\n\n /**\n * Build the default mountable template (bypasses exists check).\n */\n private async buildDefaultTemplate(): Promise<string> {\n const { template, id } = createDefaultMountableTemplate();\n this.logger.debug(`${LOG_PREFIX} Building default mountable template: ${id}...`);\n const buildResult = await Template.build(template as TemplateClass, id, this.connectionOpts);\n this._resolvedTemplateId = buildResult.templateId;\n this.logger.debug(`${LOG_PREFIX} Template built: ${buildResult.templateId}`);\n return buildResult.templateId;\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 this._sandbox.commands.run('mkdir -p /tmp/.mastra-mounts');\n await this._sandbox.files.write(markerPath, markerContent);\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 if the config matches.\n */\n private async checkExistingMount(\n mountPath: string,\n newConfig: E2BMountConfig,\n ): Promise<'not_mounted' | 'matching' | 'mismatched'> {\n if (!this._sandbox) throw new SandboxNotReadyError(this.id);\n\n // Check if path is a mount point\n const mountCheck = await this._sandbox.commands.run(\n `mountpoint -q \"${mountPath}\" && echo \"mounted\" || echo \"not mounted\"`,\n );\n\n if (mountCheck.stdout.trim() !== 'mounted') {\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\n try {\n const markerResult = await this._sandbox.commands.run(`cat \"${markerPath}\" 2>/dev/null || echo \"\"`);\n const parsed = this.mounts.parseMarkerContent(markerResult.stdout.trim());\n\n if (!parsed) {\n return 'mismatched';\n }\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 } catch {\n // Marker doesn't exist or can't be read - treat as mismatched\n }\n\n return 'mismatched';\n }\n\n /**\n * Check if an error indicates the sandbox itself is dead/gone.\n * Does NOT include code execution timeouts (those are the user's code taking too long).\n * Does NOT include \"port is not open\" - that needs sandbox kill, not reconnect.\n */\n private isSandboxDeadError(error: unknown): boolean {\n if (!error) return false;\n const errorStr = String(error);\n return (\n errorStr.includes('sandbox was not found') ||\n errorStr.includes('Sandbox is probably not running') ||\n errorStr.includes('Sandbox not found') ||\n errorStr.includes('sandbox has been killed')\n );\n }\n\n /**\n * Handle sandbox timeout by clearing the instance and resetting state.\n *\n * Bypasses the normal stop() lifecycle because the sandbox is already dead —\n * we can't unmount filesystems or run cleanup commands. Instead we reset\n * mount states to 'pending' so they get re-mounted when start() runs again.\n */\n private handleSandboxTimeout(): void {\n this._sandbox = null;\n\n // Reset mounted entries to pending so they get re-mounted on restart\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 this.status = 'stopped';\n }\n\n /**\n * Execute an operation with automatic retry if the sandbox is found to be dead.\n *\n * When the E2B sandbox times out or crashes mid-operation, this method\n * resets sandbox state, restarts it, and retries the operation once.\n *\n * @internal Used by E2BProcessManager to handle dead sandboxes during spawn.\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","/**\n * E2B sandbox provider descriptor for MastraEditor.\n *\n * @example\n * ```typescript\n * import { e2bSandboxProvider } from '@mastra/e2b';\n *\n * const editor = new MastraEditor({\n * sandboxes: [e2bSandboxProvider],\n * });\n * ```\n */\nimport type { SandboxProvider } from '@mastra/core/editor';\nimport { E2BSandbox } from './sandbox';\n\n/**\n * Serializable subset of E2BSandboxOptions for editor storage.\n * Non-serializable options (TemplateBuilder callbacks, runtime objects) are excluded.\n */\ninterface E2BProviderConfig {\n template?: string;\n timeout?: number;\n env?: Record<string, string>;\n metadata?: Record<string, unknown>;\n domain?: string;\n apiUrl?: string;\n apiKey?: string;\n accessToken?: string;\n}\n\nexport const e2bSandboxProvider: SandboxProvider<E2BProviderConfig> = {\n id: 'e2b',\n name: 'E2B Sandbox',\n description: 'Cloud sandbox powered by E2B',\n configSchema: {\n type: 'object',\n properties: {\n template: { type: 'string', description: 'Sandbox template ID' },\n timeout: { type: 'number', description: 'Execution timeout in milliseconds', default: 300000 },\n env: {\n type: 'object',\n description: 'Environment variables',\n additionalProperties: { type: 'string' },\n },\n metadata: {\n type: 'object',\n description: 'Custom metadata',\n additionalProperties: true,\n },\n domain: { type: 'string', description: 'Domain for self-hosted E2B' },\n apiUrl: { type: 'string', description: 'API URL for self-hosted E2B' },\n apiKey: { type: 'string', description: 'E2B API key' },\n accessToken: { type: 'string', description: 'E2B access token' },\n },\n },\n createSandbox: config => new E2BSandbox(config),\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/utils/template.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","../src/provider.ts"],"names":["createHash","Template","ProcessHandle","SandboxProcessManager","MastraSandbox","SandboxNotReadyError","Sandbox","template","buildResult"],"mappings":";;;;;;;AAiEO,IAAM,0BAAA,GAA6B,IAAA;AAgCnC,SAAS,8BAAA,GAA0D;AACxE,EAAA,MAAM,WAAA,GAAc,CAAC,MAAA,EAAQ,MAAM,CAAA;AACnC,EAAA,MAAM,MAAA,GAAS,EAAE,OAAA,EAAS,0BAAA,EAA4B,WAAA,EAAY;AAElE,EAAA,MAAM,IAAA,GAAOA,kBAAW,QAAQ,CAAA,CAC7B,OAAO,IAAA,CAAK,SAAA,CAAU,QAAQ,MAAA,CAAO,IAAA,CAAK,MAAM,CAAA,CAAE,IAAA,EAAM,CAAC,CAAA,CACzD,OAAO,KAAK,CAAA,CACZ,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA;AAEd,EAAA,MAAM,WAAWC,YAAA,EAAS,CAAE,aAAa,MAAM,CAAA,CAAE,WAAW,WAAW,CAAA;AAKvE,EAAA,OAAO;AAAA,IACL,QAAA;AAAA,IACA,EAAA,EAAI,UAAU,IAAI,CAAA,CAAA;AAAA,IAClB;AAAA,GACF;AACF;;;AC9GO,IAAM,UAAA,GAAa,eAAA;AAmC1B,IAAM,gBAAA,GAAmB,qCAAA;AAElB,SAAS,mBAAmB,MAAA,EAAsB;AACvD,EAAA,IAAI,CAA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EAAM,QAAA;AAAA,QACN,WAAA,EAAa,uBAAA;AAAA,QACb,oBAAA,EAAsB,EAAE,IAAA,EAAM,QAAA;AAAS,OACzC;AAAA,MACA,QAAA,EAAU;AAAA,QACR,IAAA,EAAM,QAAA;AAAA,QACN,WAAA,EAAa,iBAAA;AAAA,QACb,oBAAA,EAAsB;AAAA,OACxB;AAAA,MACA,MAAA,EAAQ,EAAE,IAAA,EAAM,QAAA,EAAU,aAAa,4BAAA,EAA6B;AAAA,MACpE,MAAA,EAAQ,EAAE,IAAA,EAAM,QAAA,EAAU,aAAa,6BAAA,EAA8B;AAAA,MACrE,MAAA,EAAQ,EAAE,IAAA,EAAM,QAAA,EAAU,aAAa,aAAA,EAAc;AAAA,MACrD,WAAA,EAAa,EAAE,IAAA,EAAM,QAAA,EAAU,aAAa,kBAAA;AAAmB;AACjE,GACF;AAAA,EACA,aAAA,EAAe,CAAA,MAAA,KAAU,IAAI,UAAA,CAAW,MAAM;AAChD","file":"index.cjs","sourcesContent":["/**\n * E2B Template Utilities\n *\n * Helper functions for creating and managing E2B sandbox templates.\n */\nimport { createHash } from 'node:crypto';\nimport { Template } from 'e2b';\nimport type { TemplateBuilder } from 'e2b';\n\n// =============================================================================\n// Template Types\n// =============================================================================\n\n/**\n * Template specification for E2B sandbox.\n *\n * Can be:\n * - `string` - Existing template ID (e.g., 'base', 'my-custom-template')\n * - `TemplateBuilder` - A built template object from Template()\n * - `(base: TemplateBuilder) => TemplateBuilder` - Callback to customize the base template\n *\n * @example Using template ID\n * ```typescript\n * new E2BSandbox({ template: 'my-custom-template' })\n * ```\n *\n * @example Using Template builder\n * ```typescript\n * import { Template } from 'e2b';\n *\n * new E2BSandbox({\n * template: Template()\n * .fromUbuntuImage('22.04')\n * .aptInstall(['s3fs', 'curl'])\n * .setEnvs({ NODE_ENV: 'production' })\n * })\n * ```\n *\n * @example Customizing default mountable template\n * ```typescript\n * new E2BSandbox({\n * template: base => base\n * .aptInstall(['nodejs', 'npm'])\n * .runCmd('npm install -g typescript')\n * })\n * ```\n */\nexport type TemplateSpec = string | TemplateBuilder | ((base: TemplateBuilder) => TemplateBuilder);\n\n/**\n * Result from createMountableTemplate containing both the template and its ID.\n */\nexport interface MountableTemplateResult {\n /** The template builder with mount dependencies */\n template: TemplateBuilder;\n /** Deterministic template ID for caching */\n id: string;\n /** List of apt packages installed in the template */\n aptPackages: string[];\n}\n\n/**\n * Version of the default mountable template.\n * Increment this when changing the default template dependencies.\n */\nexport const MOUNTABLE_TEMPLATE_VERSION = 'v1';\n\n/**\n * Create a base template with FUSE mounting dependencies pre-installed.\n *\n * This template includes s3fs and fuse packages required for mounting\n * cloud filesystems (S3, GCS, R2) into the sandbox.\n *\n * The returned `id` is deterministic, allowing E2BSandbox to check if\n * the template already exists before building it.\n *\n * @example Basic usage\n * ```typescript\n * const { template, id } = createMountableTemplate();\n * // First time: builds and caches the template\n * // Subsequent times: reuses existing template\n * const sandbox = new E2BSandbox({ template });\n * ```\n *\n * @example With customization\n * ```typescript\n * const { template } = createMountableTemplate();\n * const customTemplate = template\n * .aptInstall(['nodejs', 'npm'])\n * .runCmd('npm install -g typescript');\n *\n * // Note: customized templates get a unique ID, not the cached one\n * const sandbox = new E2BSandbox({ template: customTemplate });\n * ```\n *\n * @returns Object with template builder and deterministic ID\n */\nexport function createDefaultMountableTemplate(): MountableTemplateResult {\n const aptPackages = ['s3fs', 'fuse'];\n const config = { version: MOUNTABLE_TEMPLATE_VERSION, aptPackages };\n\n const hash = createHash('sha256')\n .update(JSON.stringify(config, Object.keys(config).sort()))\n .digest('hex')\n .slice(0, 16);\n\n const template = Template().fromTemplate('base').aptInstall(aptPackages);\n\n // Note: gcsfuse requires adding Google's apt repo which can be flaky\n // For now, we'll install it at mount time if needed\n\n return {\n template,\n id: `mastra-${hash}`,\n aptPackages,\n };\n}\n","/**\n * Shared types for E2B mount operations.\n */\n\nimport type { Sandbox } from 'e2b';\n\nexport const LOG_PREFIX = '[@mastra/e2b]';\n\nimport type { E2BGCSMountConfig } from './gcs';\nimport type { E2BS3MountConfig } from './s3';\n\n/**\n * Union of mount configs supported by E2B sandbox.\n */\nexport type E2BMountConfig = E2BS3MountConfig | E2BGCSMountConfig;\n\n/**\n * Context for mount operations.\n */\nexport interface MountContext {\n sandbox: Sandbox;\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 * Result of a mount operation.\n */\nexport interface MountOperationResult {\n success: boolean;\n error?: string;\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 */\nexport function validateEndpoint(endpoint: string): void {\n try {\n new URL(endpoint);\n } catch {\n throw new Error(`Invalid endpoint URL: \"${endpoint}\"`);\n }\n}\n","import type { FilesystemMountConfig } from '@mastra/core/workspace';\n\nimport { LOG_PREFIX, validateBucketName, validateEndpoint } from './types';\nimport type { MountContext } from './types';\n\n/**\n * S3 mount config for E2B (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 E2BS3MountConfig 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, 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: E2BS3MountConfig, ctx: MountContext): Promise<void> {\n const { sandbox, logger } = ctx;\n\n // Validate inputs before interpolating into shell commands\n validateBucketName(config.bucket);\n if (config.endpoint) {\n validateEndpoint(config.endpoint);\n }\n\n // Check if s3fs is installed\n const checkResult = await sandbox.commands.run('which s3fs || echo \"not found\"');\n if (checkResult.stdout.includes('not found')) {\n logger.warn(`${LOG_PREFIX} s3fs not found, attempting runtime installation...`);\n logger.info(\n `${LOG_PREFIX} Tip: For faster startup, use createMountableTemplate() to pre-install s3fs in your sandbox template`,\n );\n\n await sandbox.commands.run('sudo apt-get update 2>&1', { timeoutMs: 60000 });\n\n const installResult = await sandbox.commands.run(\n 'sudo apt-get install -y s3fs fuse 2>&1 || sudo apt-get install -y s3fs-fuse fuse 2>&1',\n { timeoutMs: 120000 },\n );\n\n if (installResult.exitCode !== 0) {\n throw new Error(\n `Failed to install s3fs. ` +\n `For S3 mounting, your template needs s3fs and fuse packages.\\n\\n` +\n `Option 1: Use createMountableTemplate() helper:\\n` +\n ` import { E2BSandbox, createMountableTemplate } from '@mastra/e2b';\\n` +\n ` const sandbox = new E2BSandbox({ template: createMountableTemplate() });\\n\\n` +\n `Option 2: Customize the base template:\\n` +\n ` new E2BSandbox({ template: base => base.aptInstall(['your-packages']) })\\n\\n` +\n `Error details: ${installResult.stderr || installResult.stdout}`,\n );\n }\n }\n\n // Get user's uid/gid for proper file ownership\n const idResult = await sandbox.commands.run('id -u && id -g');\n const [uid, gid] = idResult.stdout.trim().split('\\n');\n\n // Determine if we have credentials or using public bucket mode\n const hasCredentials = config.accessKeyId && config.secretAccessKey;\n const credentialsPath = '/tmp/.passwd-s3fs';\n\n // S3-compatible services (R2, MinIO, etc.) require credentials\n // public_bucket=1 only works for truly public AWS S3 buckets\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 if (hasCredentials) {\n // Write credentials file (remove old one first to avoid permission issues)\n const credentialsContent = `${config.accessKeyId}:${config.secretAccessKey}`;\n await sandbox.commands.run(`sudo rm -f ${credentialsPath}`);\n await sandbox.files.write(credentialsPath, credentialsContent);\n await sandbox.commands.run(`chmod 600 ${credentialsPath}`);\n }\n\n // Build mount options\n const mountOptions: string[] = [];\n\n if (hasCredentials) {\n mountOptions.push(`passwd_file=${credentialsPath}`);\n } else {\n // Public bucket mode - read-only access without credentials\n mountOptions.push('public_bucket=1');\n logger.debug(`${LOG_PREFIX} No credentials provided, mounting as public bucket (read-only)`);\n }\n\n mountOptions.push('allow_other'); // Allow non-root users to access the mount\n\n // Set uid/gid so mounted files are owned by user, not root\n if (uid && gid) {\n mountOptions.push(`uid=${uid}`, `gid=${gid}`);\n }\n\n if (config.endpoint) {\n // For S3-compatible storage (MinIO, R2, etc.)\n const endpoint = config.endpoint.replace(/\\/$/, '');\n mountOptions.push(`url=${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 // Mount with sudo (required for /dev/fuse access)\n const mountCmd = `sudo s3fs ${config.bucket} ${mountPath} -o ${mountOptions.join(' -o ')}`;\n logger.debug(`${LOG_PREFIX} Mounting S3:`, hasCredentials ? mountCmd.replace(credentialsPath, '***') : mountCmd);\n\n try {\n const result = await sandbox.commands.run(mountCmd, { timeoutMs: 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 } catch (error: unknown) {\n const errorObj = error as { result?: { exitCode: number; stdout: string; stderr: string } };\n const stderr = errorObj.result?.stderr || '';\n const stdout = errorObj.result?.stdout || '';\n logger.error(`${LOG_PREFIX} s3fs error:`, { stderr, stdout, error: String(error) });\n throw new Error(`Failed to mount S3 bucket: ${stderr || stdout || error}`);\n }\n}\n","import type { FilesystemMountConfig } from '@mastra/core/workspace';\n\nimport { LOG_PREFIX, validateBucketName } from './types';\nimport type { MountContext } from './types';\n\n/**\n * GCS mount config for E2B (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 E2BGCSMountConfig 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: E2BGCSMountConfig, ctx: MountContext): Promise<void> {\n const { sandbox, logger } = ctx;\n\n // Validate inputs before interpolating into shell commands\n validateBucketName(config.bucket);\n\n // Install gcsfuse if not present\n const checkResult = await sandbox.commands.run('which gcsfuse || echo \"not found\"');\n if (checkResult.stdout.includes('not found')) {\n // Detect Ubuntu codename for the gcsfuse repo (default to jammy if unknown)\n const codenameResult = await sandbox.commands.run('lsb_release -cs 2>/dev/null || echo jammy');\n const codename = codenameResult.stdout.trim() || 'jammy';\n\n // Use signed-by keyring instead of deprecated apt-key\n await sandbox.commands.run(\n 'curl -fsSL https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo gpg --dearmor -o /etc/apt/keyrings/gcsfuse.gpg && ' +\n `echo \"deb [signed-by=/etc/apt/keyrings/gcsfuse.gpg] https://packages.cloud.google.com/apt gcsfuse-${codename} main\" | sudo tee /etc/apt/sources.list.d/gcsfuse.list && ` +\n 'sudo apt-get update && sudo apt-get install -y gcsfuse',\n { timeoutMs: 120_000 },\n );\n }\n\n // Get user's uid/gid for proper file ownership\n const idResult = await sandbox.commands.run('id -u && id -g');\n const [uid, gid] = idResult.stdout.trim().split('\\n');\n\n // Build gcsfuse flags\n // Note: gcsfuse uses --uid/--gid flags, not -o uid=X style\n const uidGidFlags = uid && gid ? `--uid=${uid} --gid=${gid}` : '';\n\n const hasCredentials = !!config.serviceAccountKey;\n let mountCmd: string;\n\n if (hasCredentials) {\n // Write service account key with root ownership so sudo gcsfuse can read it\n const keyPath = '/tmp/gcs-key.json';\n await sandbox.commands.run(`sudo rm -f ${keyPath}`);\n await sandbox.files.write(keyPath, config.serviceAccountKey!);\n // Make readable by root (sudo gcsfuse runs as root)\n await sandbox.commands.run(`sudo chown root:root ${keyPath} && sudo chmod 600 ${keyPath}`);\n\n // Mount with credentials using --key-file flag\n // Use sudo for /dev/fuse access (same as s3fs)\n // -o allow_other lets non-root users access the FUSE mount\n mountCmd = `sudo gcsfuse --key-file=${keyPath} -o allow_other ${uidGidFlags} ${config.bucket} ${mountPath}`;\n } else {\n // Public bucket mode - read-only access without credentials\n // Use --anonymous-access flag (not -o option)\n // Use sudo for /dev/fuse access (same as s3fs)\n logger.debug(`${LOG_PREFIX} No credentials provided, mounting GCS as public bucket (read-only)`);\n\n mountCmd = `sudo gcsfuse --anonymous-access -o allow_other ${uidGidFlags} ${config.bucket} ${mountPath}`;\n }\n\n logger.debug(`${LOG_PREFIX} Mounting GCS:`, mountCmd);\n\n try {\n const result = await sandbox.commands.run(mountCmd, { timeoutMs: 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 } catch (error: unknown) {\n const errorObj = error as { result?: { exitCode: number; stdout: string; stderr: string } };\n const stderr = errorObj.result?.stderr || '';\n const stdout = errorObj.result?.stdout || '';\n logger.error(`${LOG_PREFIX} gcsfuse error:`, { stderr, stdout, error: String(error) });\n throw new Error(`Failed to mount GCS bucket: ${stderr || stdout || error}`);\n }\n}\n","/**\n * E2B Process Manager\n *\n * Implements SandboxProcessManager for E2B cloud sandboxes.\n * Wraps the E2B SDK's commands API (background mode, sendStdin, kill, list).\n */\n\nimport { ProcessHandle, SandboxProcessManager } from '@mastra/core/workspace';\nimport type { CommandResult, ProcessInfo, SpawnProcessOptions } from '@mastra/core/workspace';\nimport type { CommandHandle as E2BCommandHandle, Sandbox } from 'e2b';\nimport type { E2BSandbox } from './index';\n\n// =============================================================================\n// E2B Process Handle\n// =============================================================================\n\n/**\n * Wraps an E2B CommandHandle to conform to Mastra's ProcessHandle.\n * Not exported — internal to this module.\n *\n * Listener dispatch is handled by the base class. The manager's spawn()/get()\n * methods wire E2B's constructor-time callbacks to handle.emitStdout/emitStderr.\n */\nclass E2BProcessHandle extends ProcessHandle {\n readonly pid: number;\n\n private readonly _e2bHandle: E2BCommandHandle;\n private readonly _sandbox: Sandbox;\n private readonly _startTime: number;\n\n constructor(e2bHandle: E2BCommandHandle, sandbox: Sandbox, startTime: number, options?: SpawnProcessOptions) {\n super(options);\n this.pid = e2bHandle.pid;\n this._e2bHandle = e2bHandle;\n this._sandbox = sandbox;\n this._startTime = startTime;\n }\n\n /** Delegates to E2B's handle so exitCode reflects server-side state without needing wait(). */\n get exitCode(): number | undefined {\n return this._e2bHandle.exitCode;\n }\n\n async wait(): Promise<CommandResult> {\n try {\n const result = await this._e2bHandle.wait();\n return {\n success: result.exitCode === 0,\n exitCode: result.exitCode,\n stdout: this.stdout,\n stderr: this.stderr,\n executionTimeMs: Date.now() - this._startTime,\n };\n } catch (error) {\n // E2B throws CommandExitError for non-zero exit codes (has .exitCode directly)\n // Some E2B errors also carry stdout/stderr in error.result\n const errorObj = error as {\n exitCode?: number;\n result?: { exitCode: number; stdout: string; stderr: string };\n };\n const exitCode = errorObj.result?.exitCode ?? errorObj.exitCode ?? this.exitCode ?? 1;\n\n // Emit any output attached to the error (E2B sometimes puts it in .result)\n if (errorObj.result?.stdout) this.emitStdout(errorObj.result.stdout);\n if (errorObj.result?.stderr) this.emitStderr(errorObj.result.stderr);\n\n return {\n success: false,\n exitCode,\n stdout: this.stdout,\n stderr: this.stderr || (error instanceof Error ? error.message : String(error)),\n executionTimeMs: Date.now() - this._startTime,\n };\n }\n }\n\n async kill(): Promise<boolean> {\n if (this.exitCode !== undefined) return false;\n return this._e2bHandle.kill();\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.commands.sendStdin(this.pid, data);\n }\n}\n\n// =============================================================================\n// E2B Process Manager\n// =============================================================================\n\n/**\n * E2B implementation of SandboxProcessManager.\n * Uses the E2B SDK's commands.run() with background: true.\n */\nexport class E2BProcessManager extends SandboxProcessManager<E2BSandbox> {\n async spawn(command: string, options: SpawnProcessOptions = {}): Promise<ProcessHandle> {\n return this.sandbox.retryOnDead(async () => {\n const e2b = this.sandbox.e2b;\n\n // Merge default env with per-spawn env\n const mergedEnv = { ...this.env, ...options.env };\n const envs = Object.fromEntries(\n Object.entries(mergedEnv).filter((entry): entry is [string, string] => entry[1] !== undefined),\n );\n\n // Deferred reference — E2B requires callbacks at run() time, but data\n // arrives asynchronously after the promise resolves, so handle is always\n // assigned by the time the first callback fires.\n let handle: E2BProcessHandle;\n\n const e2bHandle = await e2b.commands.run(command, {\n background: true,\n stdin: true,\n cwd: options.cwd,\n envs,\n timeoutMs: options.timeout,\n onStdout: (data: string) => handle.emitStdout(data),\n onStderr: (data: string) => handle.emitStderr(data),\n });\n\n handle = new E2BProcessHandle(e2bHandle, e2b, Date.now(), options);\n this._tracked.set(handle.pid, handle);\n return handle;\n });\n }\n\n /**\n * List processes by querying E2B's commands API.\n * E2B manages all state server-side — no local tracking needed.\n */\n async list(): Promise<ProcessInfo[]> {\n const e2b = this.sandbox.e2b;\n const procs = await e2b.commands.list();\n return procs.map(proc => ({\n pid: proc.pid,\n command: [proc.cmd, ...proc.args].join(' '),\n running: true, // E2B only lists running processes\n }));\n }\n\n /**\n * Get a handle to a process by PID.\n * Checks base class tracking first, then falls back to commands.connect()\n * for processes spawned externally or before reconnection.\n */\n async get(pid: number): Promise<ProcessHandle | undefined> {\n const tracked = this._tracked.get(pid);\n if (tracked) return tracked;\n\n // Fall back to connect() for unknown PIDs (e.g., pre-existing processes)\n const e2b = this.sandbox.e2b;\n let handle: E2BProcessHandle;\n try {\n const e2bHandle = await e2b.commands.connect(pid, {\n onStdout: (data: string) => handle.emitStdout(data),\n onStderr: (data: string) => handle.emitStderr(data),\n });\n handle = new E2BProcessHandle(e2bHandle, e2b, Date.now());\n this._tracked.set(pid, handle);\n return handle;\n } catch {\n return undefined;\n }\n }\n}\n","/**\n * E2B Sandbox Provider\n *\n * A simplified E2B sandbox implementation that supports mounting\n * cloud filesystems (S3, GCS, R2) via FUSE.\n *\n * @see https://e2b.dev/docs\n */\n\nimport type { RequestContext } from '@mastra/core/di';\nimport type {\n SandboxInfo,\n WorkspaceFilesystem,\n MountResult,\n FilesystemMountConfig,\n ProviderStatus,\n MountManager,\n MastraSandboxOptions,\n} from '@mastra/core/workspace';\n\n/**\n * Inlined from `@mastra/core/workspace` to avoid requiring a newer core peer dep.\n */\ntype InstructionsOption = string | ((opts: { defaultInstructions: string; requestContext?: RequestContext }) => string);\nimport { MastraSandbox, SandboxNotReadyError } from '@mastra/core/workspace';\nimport { Sandbox, Template } from 'e2b';\nimport type { TemplateBuilder, TemplateClass } from 'e2b';\nimport { createDefaultMountableTemplate } from '../utils/template';\nimport type { TemplateSpec } from '../utils/template';\nimport { mountS3, mountGCS, LOG_PREFIX } from './mounts';\nimport type { E2BMountConfig, E2BS3MountConfig, E2BGCSMountConfig, MountContext } from './mounts';\nimport { E2BProcessManager } from './process-manager';\n\n/** Allowlist pattern for mount paths — absolute path with safe characters only. */\nconst SAFE_MOUNT_PATH = /^\\/[a-zA-Z0-9_.\\-/]+$/;\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}\n\n/** Allowlist for marker filenames from ls output — e.g. \"mount-abc123\" */\nconst SAFE_MARKER_NAME = /^mount-[a-z0-9]+$/;\n\n// =============================================================================\n// E2B Sandbox Options\n// =============================================================================\n\n/**\n * E2B sandbox provider configuration.\n */\nexport interface E2BSandboxOptions extends Omit<MastraSandboxOptions, 'processes'> {\n /** Unique identifier for this sandbox instance */\n id?: string;\n /**\n * Sandbox template specification.\n *\n * - `string` - Use an existing template by ID\n * - `TemplateBuilder` - Use a custom template (e.g., from `createMountableTemplate()`)\n * - `(base) => base.aptInstall([...])` - Customize the default mountable template\n *\n * If not provided and mounting is used, a default template with s3fs will be built.\n * For best performance, pre-build your template and use the template ID.\n *\n * @see createDefaultMountableTemplate\n */\n template?: TemplateSpec;\n /** Execution timeout in milliseconds\n *\n * @default 300_000 // 5 minutes\n */\n timeout?: number;\n /** Environment variables to set in the sandbox */\n env?: Record<string, string>;\n /** Custom metadata */\n metadata?: Record<string, unknown>;\n\n /** Domain for self-hosted E2B. Falls back to E2B_DOMAIN env var. */\n domain?: string;\n /** API URL for self-hosted E2B. Falls back to E2B_API_URL env var. */\n apiUrl?: string;\n /** API key for authentication. Falls back to E2B_API_KEY env var. */\n apiKey?: string;\n /** Access token for authentication. Falls back to E2B_ACCESS_TOKEN env var. */\n accessToken?: string;\n /**\n * Custom instructions that override the default instructions\n * returned by `getInstructions()`.\n *\n * - `string` — Fully replaces the default instructions.\n * Pass an empty string to suppress instructions entirely.\n * - `(opts) => string` — Receives the default instructions and\n * optional request context so you can extend or customise per-request.\n */\n instructions?: InstructionsOption;\n}\n\n// =============================================================================\n// E2B Sandbox Implementation\n// =============================================================================\n\n/**\n * Simplified E2B sandbox implementation.\n *\n * Features:\n * - Single sandbox instance lifecycle\n * - Supports mounting cloud filesystems (S3, GCS, R2) via FUSE\n * - Automatic sandbox timeout handling with retry\n *\n * @example Basic usage\n * ```typescript\n * import { Workspace } from '@mastra/core/workspace';\n * import { E2BSandbox } from '@mastra/e2b';\n *\n * const sandbox = new E2BSandbox({\n * timeout: 60000,\n * });\n *\n * const workspace = new Workspace({ sandbox });\n * const result = await workspace.executeCode('console.log(\"Hello!\")');\n * ```\n *\n * @example With S3 filesystem mounting\n * ```typescript\n * import { Workspace } from '@mastra/core/workspace';\n * import { E2BSandbox } from '@mastra/e2b';\n * import { S3Filesystem } from '@mastra/s3';\n *\n * const workspace = new Workspace({\n * mounts: {\n * '/bucket': new S3Filesystem({\n * bucket: 'my-bucket',\n * region: 'us-east-1',\n * }),\n * },\n * sandbox: new E2BSandbox({ timeout: 60000 }),\n * });\n *\n * ```\n */\nexport class E2BSandbox extends MastraSandbox {\n readonly id: string;\n readonly name = 'E2BSandbox';\n readonly provider = 'e2b';\n status: ProviderStatus = 'pending';\n\n declare readonly mounts: MountManager; // Non-optional (initialized by BaseSandbox)\n declare readonly processes: E2BProcessManager;\n\n private _sandbox: Sandbox | null = null;\n private _createdAt: Date | null = null;\n private _isRetrying = false;\n private readonly timeout: number;\n private readonly templateSpec?: TemplateSpec;\n private readonly env: Record<string, string>;\n private readonly metadata: Record<string, unknown>;\n private readonly connectionOpts: Record<string, string>;\n private readonly _instructionsOverride?: InstructionsOption;\n\n /** Resolved template ID after building (if needed) */\n private _resolvedTemplateId?: string;\n\n /** Promise for template preparation (started in constructor) */\n private _templatePreparePromise?: Promise<string>;\n\n constructor(options: E2BSandboxOptions = {}) {\n super({\n ...options,\n name: 'E2BSandbox',\n processes: new E2BProcessManager({ env: options.env ?? {} }),\n });\n\n this.id = options.id ?? this.generateId();\n this.timeout = options.timeout ?? 300_000; // 5 minutes;\n this.templateSpec = options.template;\n this.env = options.env ?? {};\n this.metadata = options.metadata ?? {};\n this.connectionOpts = {\n ...(options.domain && { domain: options.domain }),\n ...(options.apiUrl && { apiUrl: options.apiUrl }),\n ...(options.apiKey && { apiKey: options.apiKey }),\n ...(options.accessToken && { accessToken: options.accessToken }),\n };\n\n this._instructionsOverride = options.instructions;\n\n // Start template preparation immediately in background\n // This way template build (if needed) begins before start() is called\n this._templatePreparePromise = this.resolveTemplate().catch(err => {\n this.logger.debug(`${LOG_PREFIX} Template preparation error (will retry on start):`, err);\n return ''; // Return empty string, will be retried in start()\n });\n }\n\n /**\n * Get the underlying E2B Sandbox instance for direct access to E2B APIs.\n *\n * Use this when you need to access E2B features not exposed through the\n * WorkspaceSandbox interface (e.g., files API, ports, etc.).\n *\n * @throws {SandboxNotReadyError} If the sandbox has not been started\n *\n * @example Direct file operations\n * ```typescript\n * const e2b = sandbox.e2b;\n * await e2b.files.write('/tmp/test.txt', 'Hello');\n * const content = await e2b.files.read('/tmp/test.txt');\n * const files = await e2b.files.list('/tmp');\n * ```\n *\n * @example Access ports\n * ```typescript\n * const e2b = sandbox.e2b;\n * const url = e2b.getHost(3000);\n * ```\n */\n get e2b(): Sandbox {\n if (!this._sandbox) {\n throw new SandboxNotReadyError(this.id);\n }\n return this._sandbox;\n }\n\n // ---------------------------------------------------------------------------\n // Lifecycle\n // ---------------------------------------------------------------------------\n\n /**\n * Start the E2B sandbox.\n * Handles template preparation, existing sandbox reconnection, and new sandbox creation.\n *\n * Status management and mount processing are handled by the base class.\n */\n async start(): Promise<void> {\n // Already have a sandbox instance\n if (this._sandbox) {\n return;\n }\n\n // Await template preparation (started in constructor) and existing sandbox search in parallel\n const [existingSandbox, templateId] = await Promise.all([\n this.findExistingSandbox(),\n this._templatePreparePromise || this.resolveTemplate(),\n ]);\n\n if (existingSandbox) {\n this._sandbox = existingSandbox;\n this._createdAt = new Date();\n this.logger.debug(`${LOG_PREFIX} Reconnected to existing sandbox for: ${this.id}`);\n\n // Clean up stale mounts from previous config\n // (processPending is called by base class after start completes)\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 return;\n }\n\n // If template preparation failed earlier, retry now\n let resolvedTemplateId = templateId;\n if (!resolvedTemplateId) {\n this.logger.debug(`${LOG_PREFIX} Template preparation failed earlier, retrying...`);\n resolvedTemplateId = await this.resolveTemplate();\n }\n\n // Create a new sandbox with our logical ID in metadata\n // Using betaCreate with autoPause so sandbox pauses on timeout instead of being destroyed\n this.logger.debug(`${LOG_PREFIX} Creating new sandbox for: ${this.id} with template: ${resolvedTemplateId}`);\n\n try {\n this._sandbox = await Sandbox.betaCreate(resolvedTemplateId, {\n ...this.connectionOpts,\n autoPause: true,\n metadata: {\n ...this.metadata,\n 'mastra-sandbox-id': this.id,\n },\n timeoutMs: this.timeout,\n });\n } catch (createError) {\n // If template not found (404), rebuild it and retry\n const errorStr = String(createError);\n if (errorStr.includes('404') && errorStr.includes('not found') && !this.templateSpec) {\n this.logger.debug(`${LOG_PREFIX} Template not found, rebuilding: ${templateId}`);\n this._resolvedTemplateId = undefined; // Clear cached ID to force rebuild\n const rebuiltTemplateId = await this.buildDefaultTemplate();\n\n this.logger.debug(`${LOG_PREFIX} Retrying sandbox creation with rebuilt template: ${rebuiltTemplateId}`);\n this._sandbox = await Sandbox.betaCreate(rebuiltTemplateId, {\n ...this.connectionOpts,\n autoPause: true,\n metadata: {\n ...this.metadata,\n 'mastra-sandbox-id': this.id,\n },\n timeoutMs: this.timeout,\n });\n } else {\n throw createError;\n }\n }\n\n this.logger.debug(`${LOG_PREFIX} Created sandbox ${this._sandbox.sandboxId} for logical ID: ${this.id}`);\n this._createdAt = new Date();\n\n // Note: processPending is called by base class after start completes\n }\n\n /**\n * Stop the E2B sandbox.\n * Unmounts all filesystems and releases the sandbox reference.\n * Status management is handled by the base class.\n */\n async stop(): Promise<void> {\n // Kill all background processes before stopping\n try {\n const procs = await this.processes.list();\n await Promise.all(procs.map(p => this.processes.kill(p.pid)));\n } catch {\n // Best-effort: sandbox may already be dead\n }\n\n // Unmount all filesystems before stopping\n // Collect keys first since unmount() mutates the map\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 this._sandbox = null;\n }\n\n /**\n * Destroy the E2B sandbox and clean up all resources.\n * Unmounts filesystems, kills the sandbox, and clears mount state.\n * Status management is handled by the base class.\n */\n async destroy(): Promise<void> {\n if (this._sandbox) {\n // Kill all background processes\n try {\n const procs = await this.processes.list();\n await Promise.all(procs.map(p => this.processes.kill(p.pid)));\n } catch {\n // Best-effort: sandbox may already be dead\n }\n\n // Unmount all filesystems\n // Collect keys first since unmount() mutates the map\n for (const mountPath of [...this.mounts.entries.keys()]) {\n try {\n await this.unmount(mountPath);\n } catch {\n // Ignore errors during cleanup\n }\n }\n\n try {\n await this._sandbox.kill();\n } catch {\n // Ignore errors during destroy\n }\n\n this._sandbox = null;\n }\n\n this.mounts.clear();\n }\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: Array.from(this.mounts.entries).map(([path, entry]) => ({\n path,\n filesystem: entry.filesystem?.provider ?? entry.config?.type ?? 'unknown',\n })),\n metadata: {\n ...this.metadata,\n },\n };\n }\n\n /**\n * Get instructions describing this E2B sandbox.\n * Used by agents to understand the execution environment.\n */\n getInstructions(opts?: { requestContext?: RequestContext }): string {\n if (this._instructionsOverride === undefined) return this._getDefaultInstructions();\n if (typeof this._instructionsOverride === 'string') return this._instructionsOverride;\n const defaultInstructions = this._getDefaultInstructions();\n return this._instructionsOverride({ defaultInstructions, requestContext: opts?.requestContext });\n }\n\n private _getDefaultInstructions(): string {\n const mountCount = this.mounts.entries.size;\n const mountInfo = mountCount > 0 ? ` ${mountCount} filesystem(s) mounted via FUSE.` : '';\n return `Cloud sandbox.${mountInfo}`;\n }\n\n // ---------------------------------------------------------------------------\n // Mounting\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\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 E2BMountConfig | 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, unmounting to re-mount with new config...`);\n await this.unmount(mountPath);\n }\n this.logger.debug(`${LOG_PREFIX} Config type: ${config.type}`);\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\n // Check if directory exists and is non-empty (would shadow existing files)\n try {\n const checkResult = await this._sandbox.commands.run(\n `[ -d \"${mountPath}\" ] && [ \"$(ls -A \"${mountPath}\" 2>/dev/null)\" ] && echo \"non-empty\" || echo \"ok\"`,\n );\n if (checkResult.stdout.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 mount directory with sudo (for paths outside home dir like /data)\n // Then chown to current user so mount works without issues\n try {\n this.logger.debug(`${LOG_PREFIX} Creating mount directory for ${mountPath}...`);\n const mkdirCommand = `sudo mkdir -p \"${mountPath}\" && sudo chown $(id -u):$(id -g) \"${mountPath}\"`;\n\n this.logger.debug(`${LOG_PREFIX} Running command: ${mkdirCommand}`);\n const mkdirResult = await this._sandbox.commands.run(mkdirCommand);\n\n this.logger.debug(`${LOG_PREFIX} Created mount directory for mount path \"${mountPath}\":`, mkdirResult);\n } catch (mkdirError) {\n this.logger.debug(`${LOG_PREFIX} mkdir error for \"${mountPath}\":`, mkdirError);\n this.mounts.set(mountPath, { filesystem, state: 'error', config, error: String(mkdirError) });\n return { success: false, mountPath, error: String(mkdirError) };\n }\n\n // Create mount context for mount operations\n const mountCtx: MountContext = {\n sandbox: this._sandbox,\n logger: this.logger,\n };\n\n try {\n switch (config.type) {\n case 's3':\n this.logger.debug(`${LOG_PREFIX} Mounting S3 bucket at ${mountPath}...`);\n await mountS3(mountPath, config as E2BS3MountConfig, 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 bucket at ${mountPath}...`);\n await mountGCS(mountPath, config as E2BGCSMountConfig, mountCtx);\n this.logger.debug(`${LOG_PREFIX} Mounted GCS bucket at ${mountPath}`);\n break;\n default:\n this.mounts.set(mountPath, {\n filesystem,\n state: 'unsupported',\n config,\n error: `Unsupported mount type: ${(config as FilesystemMountConfig).type}`,\n });\n return {\n success: false,\n mountPath,\n error: `Unsupported mount type: ${(config as FilesystemMountConfig).type}`,\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: String(error) });\n\n // Clean up the directory we created since mount failed\n try {\n await this._sandbox!.commands.run(`sudo rmdir \"${mountPath}\" 2>/dev/null || true`);\n this.logger.debug(`${LOG_PREFIX} Cleaned up directory after failed mount: ${mountPath}`);\n } catch {\n // Ignore cleanup errors\n }\n\n return { success: false, mountPath, error: String(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\n this.logger.debug(`${LOG_PREFIX} Unmounting ${mountPath}...`);\n\n try {\n // Use fusermount for FUSE mounts, fall back to umount\n const result = await this._sandbox.commands.run(\n `sudo fusermount -u \"${mountPath}\" 2>/dev/null || sudo umount \"${mountPath}\"`,\n );\n if (result.exitCode !== 0) {\n this.logger.debug(`${LOG_PREFIX} Unmount warning: ${result.stderr || result.stdout}`);\n }\n } catch (error) {\n this.logger.debug(`${LOG_PREFIX} Unmount error:`, error);\n // Try lazy unmount as last resort\n await this._sandbox.commands.run(`sudo umount -l \"${mountPath}\" 2>/dev/null || true`);\n }\n\n this.mounts.delete(mountPath);\n\n // Clean up marker file\n const filename = this.mounts.markerFilename(mountPath);\n const markerPath = `/tmp/.mastra-mounts/${filename}`;\n await this._sandbox.commands.run(`rm -f \"${markerPath}\" 2>/dev/null || true`);\n\n // Remove empty mount directory (only if empty, rmdir fails on non-empty)\n // Use sudo since mount directories outside home (like /data) were created with sudo\n const rmdirResult = await this._sandbox.commands.run(`sudo rmdir \"${mountPath}\" 2>&1`);\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.stderr?.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) {\n throw new SandboxNotReadyError(this.id);\n }\n\n this.logger.debug(`${LOG_PREFIX} Reconciling mounts. Expected paths:`, expectedMountPaths);\n\n // Get current FUSE mounts in the sandbox\n const mountsResult = await this._sandbox.commands.run(\n `grep -E 'fuse\\\\.(s3fs|gcsfuse)' /proc/mounts | awk '{print $2}'`,\n );\n const currentMounts = mountsResult.stdout\n .trim()\n .split('\\n')\n .filter(p => p.length > 0);\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 const markersResult = await this._sandbox.commands.run(`ls /tmp/.mastra-mounts/ 2>/dev/null || echo \"\"`);\n const markerFiles = markersResult.stdout\n .trim()\n .split('\\n')\n .filter(f => f.length > 0 && SAFE_MARKER_NAME.test(f));\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 this._sandbox.commands.run(\n `cat \"/tmp/.mastra-mounts/${markerFile}\" 2>/dev/null || echo \"\"`,\n );\n const parsed = this.mounts.parseMarkerContent(markerResult.stdout.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 await this.unmount(stalePath);\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\n // Remove marker file\n await this._sandbox.commands.run(`rm -f \"/tmp/.mastra-mounts/${markerFile}\" 2>/dev/null || true`);\n\n // Try to remove the directory (will fail if not empty or doesn't exist, which is fine)\n await this._sandbox.commands.run(`sudo rmdir \"${mountPath}\" 2>/dev/null || true`);\n }\n } else {\n // Malformed marker file - just delete it\n this.logger.debug(`${LOG_PREFIX} Removing malformed marker file: ${markerFile}`);\n await this._sandbox.commands.run(`rm -f \"/tmp/.mastra-mounts/${markerFile}\" 2>/dev/null || true`);\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 // Deprecated\n // ---------------------------------------------------------------------------\n\n /** @deprecated Use `e2b` instead. */\n get instance(): Sandbox {\n return this.e2b;\n }\n\n /** @deprecated Use `status === 'running'` instead. */\n async isReady(): Promise<boolean> {\n return this.status === 'running' && this._sandbox !== null;\n }\n\n // ---------------------------------------------------------------------------\n // Internal Helpers\n // ---------------------------------------------------------------------------\n\n private generateId(): string {\n return `e2b-sandbox-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;\n }\n\n /**\n * Find an existing sandbox with matching mastra-sandbox-id metadata.\n * Returns the connected sandbox if found, null otherwise.\n */\n private async findExistingSandbox(): Promise<Sandbox | null> {\n try {\n // Query E2B for existing sandbox with our logical ID in metadata\n const paginator = Sandbox.list({\n ...this.connectionOpts,\n query: {\n metadata: { 'mastra-sandbox-id': this.id },\n state: ['running', 'paused'],\n },\n });\n\n const sandboxes = await paginator.nextItems();\n\n this.logger.debug(`${LOG_PREFIX} sandboxes:`, sandboxes);\n\n // Sandbox.list only returns running/paused sandboxes, so no need to filter\n if (sandboxes.length > 0) {\n const existingSandbox = sandboxes[0]!;\n this.logger.debug(\n `${LOG_PREFIX} Found existing sandbox for ${this.id}: ${existingSandbox.sandboxId} (state: ${existingSandbox.state})`,\n );\n return await Sandbox.connect(existingSandbox.sandboxId, this.connectionOpts);\n }\n } catch (e) {\n this.logger.debug(`${LOG_PREFIX} Error querying for existing sandbox:`, e);\n // Continue to create new sandbox\n }\n\n return null;\n }\n\n /**\n * Resolve the template specification to a template ID.\n *\n * - String: Use as-is (template ID)\n * - TemplateBuilder: Build and return the template ID\n * - Function: Apply to base mountable template, then build\n * - undefined: Use default mountable template (cached)\n */\n private async resolveTemplate(): Promise<string> {\n // If already resolved, return cached ID\n if (this._resolvedTemplateId) {\n return this._resolvedTemplateId;\n }\n\n // No template specified - use default mountable template with caching\n if (!this.templateSpec) {\n const { template, id } = createDefaultMountableTemplate();\n\n // Check if template already exists (cached from previous runs)\n const exists = await Template.exists(id, this.connectionOpts);\n if (exists) {\n this.logger.debug(`${LOG_PREFIX} Using cached mountable template: ${id}`);\n this._resolvedTemplateId = id;\n return id;\n }\n\n // Build the template (first time only)\n this.logger.debug(`${LOG_PREFIX} Building default mountable template: ${id}...`);\n const buildResult = await Template.build(template as TemplateClass, id, this.connectionOpts);\n this._resolvedTemplateId = buildResult.templateId;\n this.logger.debug(`${LOG_PREFIX} Template built and cached: ${buildResult.templateId}`);\n return buildResult.templateId;\n }\n\n // String template ID - use directly\n if (typeof this.templateSpec === 'string') {\n this._resolvedTemplateId = this.templateSpec;\n return this.templateSpec;\n }\n\n // TemplateBuilder or function - need to build\n let template: TemplateBuilder;\n let templateName: string;\n\n if (typeof this.templateSpec === 'function') {\n // Apply customization function to base mountable template\n const { template: baseTemplate } = createDefaultMountableTemplate();\n template = this.templateSpec(baseTemplate);\n // Custom templates get unique names since they're modified\n templateName = `mastra-custom-${this.id.replace(/[^a-zA-Z0-9-]/g, '-')}`;\n } else {\n // Use provided TemplateBuilder directly\n template = this.templateSpec;\n templateName = `mastra-${this.id.replace(/[^a-zA-Z0-9-]/g, '-')}`;\n }\n\n // Build the template\n this.logger.debug(`${LOG_PREFIX} Building custom template: ${templateName}...`);\n const buildResult = await Template.build(template as TemplateClass, templateName, this.connectionOpts);\n this._resolvedTemplateId = buildResult.templateId;\n this.logger.debug(`${LOG_PREFIX} Template built: ${buildResult.templateId}`);\n\n return buildResult.templateId;\n }\n\n /**\n * Build the default mountable template (bypasses exists check).\n */\n private async buildDefaultTemplate(): Promise<string> {\n const { template, id } = createDefaultMountableTemplate();\n this.logger.debug(`${LOG_PREFIX} Building default mountable template: ${id}...`);\n const buildResult = await Template.build(template as TemplateClass, id, this.connectionOpts);\n this._resolvedTemplateId = buildResult.templateId;\n this.logger.debug(`${LOG_PREFIX} Template built: ${buildResult.templateId}`);\n return buildResult.templateId;\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 this._sandbox.commands.run('mkdir -p /tmp/.mastra-mounts');\n await this._sandbox.files.write(markerPath, markerContent);\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 if the config matches.\n */\n private async checkExistingMount(\n mountPath: string,\n newConfig: E2BMountConfig,\n ): Promise<'not_mounted' | 'matching' | 'mismatched'> {\n if (!this._sandbox) throw new SandboxNotReadyError(this.id);\n\n // Check if path is a mount point\n const mountCheck = await this._sandbox.commands.run(\n `mountpoint -q \"${mountPath}\" && echo \"mounted\" || echo \"not mounted\"`,\n );\n\n if (mountCheck.stdout.trim() !== 'mounted') {\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\n try {\n const markerResult = await this._sandbox.commands.run(`cat \"${markerPath}\" 2>/dev/null || echo \"\"`);\n const parsed = this.mounts.parseMarkerContent(markerResult.stdout.trim());\n\n if (!parsed) {\n return 'mismatched';\n }\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 } catch {\n // Marker doesn't exist or can't be read - treat as mismatched\n }\n\n return 'mismatched';\n }\n\n /**\n * Check if an error indicates the sandbox itself is dead/gone.\n * Does NOT include code execution timeouts (those are the user's code taking too long).\n * Does NOT include \"port is not open\" - that needs sandbox kill, not reconnect.\n */\n private isSandboxDeadError(error: unknown): boolean {\n if (!error) return false;\n const errorStr = String(error);\n return (\n errorStr.includes('sandbox was not found') ||\n errorStr.includes('Sandbox is probably not running') ||\n errorStr.includes('Sandbox not found') ||\n errorStr.includes('sandbox has been killed')\n );\n }\n\n /**\n * Handle sandbox timeout by clearing the instance and resetting state.\n *\n * Bypasses the normal stop() lifecycle because the sandbox is already dead —\n * we can't unmount filesystems or run cleanup commands. Instead we reset\n * mount states to 'pending' so they get re-mounted when start() runs again.\n */\n private handleSandboxTimeout(): void {\n this._sandbox = null;\n\n // Reset mounted entries to pending so they get re-mounted on restart\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 this.status = 'stopped';\n }\n\n /**\n * Execute an operation with automatic retry if the sandbox is found to be dead.\n *\n * When the E2B sandbox times out or crashes mid-operation, this method\n * resets sandbox state, restarts it, and retries the operation once.\n *\n * @internal Used by E2BProcessManager to handle dead sandboxes during spawn.\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","/**\n * E2B sandbox provider descriptor for MastraEditor.\n *\n * @example\n * ```typescript\n * import { e2bSandboxProvider } from '@mastra/e2b';\n *\n * const editor = new MastraEditor({\n * sandboxes: [e2bSandboxProvider],\n * });\n * ```\n */\nimport type { SandboxProvider } from '@mastra/core/editor';\nimport { E2BSandbox } from './sandbox';\n\n/**\n * Serializable subset of E2BSandboxOptions for editor storage.\n * Non-serializable options (TemplateBuilder callbacks, runtime objects) are excluded.\n */\ninterface E2BProviderConfig {\n template?: string;\n timeout?: number;\n env?: Record<string, string>;\n metadata?: Record<string, unknown>;\n domain?: string;\n apiUrl?: string;\n apiKey?: string;\n accessToken?: string;\n}\n\nexport const e2bSandboxProvider: SandboxProvider<E2BProviderConfig> = {\n id: 'e2b',\n name: 'E2B Sandbox',\n description: 'Cloud sandbox powered by E2B',\n configSchema: {\n type: 'object',\n properties: {\n template: { type: 'string', description: 'Sandbox template ID' },\n timeout: { type: 'number', description: 'Execution timeout in milliseconds', default: 300000 },\n env: {\n type: 'object',\n description: 'Environment variables',\n additionalProperties: { type: 'string' },\n },\n metadata: {\n type: 'object',\n description: 'Custom metadata',\n additionalProperties: true,\n },\n domain: { type: 'string', description: 'Domain for self-hosted E2B' },\n apiUrl: { type: 'string', description: 'API URL for self-hosted E2B' },\n apiKey: { type: 'string', description: 'E2B API key' },\n accessToken: { type: 'string', description: 'E2B access token' },\n },\n },\n createSandbox: config => new E2BSandbox(config),\n};\n"]}
|
package/dist/index.js
CHANGED
|
@@ -500,7 +500,7 @@ var E2BSandbox = class extends MastraSandbox {
|
|
|
500
500
|
_getDefaultInstructions() {
|
|
501
501
|
const mountCount = this.mounts.entries.size;
|
|
502
502
|
const mountInfo = mountCount > 0 ? ` ${mountCount} filesystem(s) mounted via FUSE.` : "";
|
|
503
|
-
return `Cloud sandbox
|
|
503
|
+
return `Cloud sandbox.${mountInfo}`;
|
|
504
504
|
}
|
|
505
505
|
// ---------------------------------------------------------------------------
|
|
506
506
|
// Mounting
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/template.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","../src/provider.ts"],"names":["template","Template","buildResult"],"mappings":";;;;;AAiEO,IAAM,0BAAA,GAA6B,IAAA;AAgCnC,SAAS,8BAAA,GAA0D;AACxE,EAAA,MAAM,WAAA,GAAc,CAAC,MAAA,EAAQ,MAAM,CAAA;AACnC,EAAA,MAAM,MAAA,GAAS,EAAE,OAAA,EAAS,0BAAA,EAA4B,WAAA,EAAY;AAElE,EAAA,MAAM,IAAA,GAAO,WAAW,QAAQ,CAAA,CAC7B,OAAO,IAAA,CAAK,SAAA,CAAU,QAAQ,MAAA,CAAO,IAAA,CAAK,MAAM,CAAA,CAAE,IAAA,EAAM,CAAC,CAAA,CACzD,OAAO,KAAK,CAAA,CACZ,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA;AAEd,EAAA,MAAM,WAAW,QAAA,EAAS,CAAE,aAAa,MAAM,CAAA,CAAE,WAAW,WAAW,C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AAAA,IACN,UAAA,EAAY;AAAA,MACV,QAAA,EAAU,EAAE,IAAA,EAAM,QAAA,EAAU,aAAa,qBAAA,EAAsB;AAAA,MAC/D,SAAS,EAAE,IAAA,EAAM,UAAU,WAAA,EAAa,mCAAA,EAAqC,SAAS,GAAA,EAAO;AAAA,MAC7F,GAAA,EAAK;AAAA,QACH,IAAA,EAAM,QAAA;AAAA,QACN,WAAA,EAAa,uBAAA;AAAA,QACb,oBAAA,EAAsB,EAAE,IAAA,EAAM,QAAA;AAAS,OACzC;AAAA,MACA,QAAA,EAAU;AAAA,QACR,IAAA,EAAM,QAAA;AAAA,QACN,WAAA,EAAa,iBAAA;AAAA,QACb,oBAAA,EAAsB;AAAA,OACxB;AAAA,MACA,MAAA,EAAQ,EAAE,IAAA,EAAM,QAAA,EAAU,aAAa,4BAAA,EAA6B;AAAA,MACpE,MAAA,EAAQ,EAAE,IAAA,EAAM,QAAA,EAAU,aAAa,6BAAA,EAA8B;AAAA,MACrE,MAAA,EAAQ,EAAE,IAAA,EAAM,QAAA,EAAU,aAAa,aAAA,EAAc;AAAA,MACrD,WAAA,EAAa,EAAE,IAAA,EAAM,QAAA,EAAU,aAAa,kBAAA;AAAmB;AACjE,GACF;AAAA,EACA,aAAA,EAAe,CAAA,MAAA,KAAU,IAAI,UAAA,CAAW,MAAM;AAChD","file":"index.js","sourcesContent":["/**\n * E2B Template Utilities\n *\n * Helper functions for creating and managing E2B sandbox templates.\n */\nimport { createHash } from 'node:crypto';\nimport { Template } from 'e2b';\nimport type { TemplateBuilder } from 'e2b';\n\n// =============================================================================\n// Template Types\n// =============================================================================\n\n/**\n * Template specification for E2B sandbox.\n *\n * Can be:\n * - `string` - Existing template ID (e.g., 'base', 'my-custom-template')\n * - `TemplateBuilder` - A built template object from Template()\n * - `(base: TemplateBuilder) => TemplateBuilder` - Callback to customize the base template\n *\n * @example Using template ID\n * ```typescript\n * new E2BSandbox({ template: 'my-custom-template' })\n * ```\n *\n * @example Using Template builder\n * ```typescript\n * import { Template } from 'e2b';\n *\n * new E2BSandbox({\n * template: Template()\n * .fromUbuntuImage('22.04')\n * .aptInstall(['s3fs', 'curl'])\n * .setEnvs({ NODE_ENV: 'production' })\n * })\n * ```\n *\n * @example Customizing default mountable template\n * ```typescript\n * new E2BSandbox({\n * template: base => base\n * .aptInstall(['nodejs', 'npm'])\n * .runCmd('npm install -g typescript')\n * })\n * ```\n */\nexport type TemplateSpec = string | TemplateBuilder | ((base: TemplateBuilder) => TemplateBuilder);\n\n/**\n * Result from createMountableTemplate containing both the template and its ID.\n */\nexport interface MountableTemplateResult {\n /** The template builder with mount dependencies */\n template: TemplateBuilder;\n /** Deterministic template ID for caching */\n id: string;\n /** List of apt packages installed in the template */\n aptPackages: string[];\n}\n\n/**\n * Version of the default mountable template.\n * Increment this when changing the default template dependencies.\n */\nexport const MOUNTABLE_TEMPLATE_VERSION = 'v1';\n\n/**\n * Create a base template with FUSE mounting dependencies pre-installed.\n *\n * This template includes s3fs and fuse packages required for mounting\n * cloud filesystems (S3, GCS, R2) into the sandbox.\n *\n * The returned `id` is deterministic, allowing E2BSandbox to check if\n * the template already exists before building it.\n *\n * @example Basic usage\n * ```typescript\n * const { template, id } = createMountableTemplate();\n * // First time: builds and caches the template\n * // Subsequent times: reuses existing template\n * const sandbox = new E2BSandbox({ template });\n * ```\n *\n * @example With customization\n * ```typescript\n * const { template } = createMountableTemplate();\n * const customTemplate = template\n * .aptInstall(['nodejs', 'npm'])\n * .runCmd('npm install -g typescript');\n *\n * // Note: customized templates get a unique ID, not the cached one\n * const sandbox = new E2BSandbox({ template: customTemplate });\n * ```\n *\n * @returns Object with template builder and deterministic ID\n */\nexport function createDefaultMountableTemplate(): MountableTemplateResult {\n const aptPackages = ['s3fs', 'fuse'];\n const config = { version: MOUNTABLE_TEMPLATE_VERSION, aptPackages };\n\n const hash = createHash('sha256')\n .update(JSON.stringify(config, Object.keys(config).sort()))\n .digest('hex')\n .slice(0, 16);\n\n const template = Template().fromTemplate('base').aptInstall(aptPackages);\n\n // Note: gcsfuse requires adding Google's apt repo which can be flaky\n // For now, we'll install it at mount time if needed\n\n return {\n template,\n id: `mastra-${hash}`,\n aptPackages,\n };\n}\n","/**\n * Shared types for E2B mount operations.\n */\n\nimport type { Sandbox } from 'e2b';\n\nexport const LOG_PREFIX = '[@mastra/e2b]';\n\nimport type { E2BGCSMountConfig } from './gcs';\nimport type { E2BS3MountConfig } from './s3';\n\n/**\n * Union of mount configs supported by E2B sandbox.\n */\nexport type E2BMountConfig = E2BS3MountConfig | E2BGCSMountConfig;\n\n/**\n * Context for mount operations.\n */\nexport interface MountContext {\n sandbox: Sandbox;\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 * Result of a mount operation.\n */\nexport interface MountOperationResult {\n success: boolean;\n error?: string;\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 */\nexport function validateEndpoint(endpoint: string): void {\n try {\n new URL(endpoint);\n } catch {\n throw new Error(`Invalid endpoint URL: \"${endpoint}\"`);\n }\n}\n","import type { FilesystemMountConfig } from '@mastra/core/workspace';\n\nimport { LOG_PREFIX, validateBucketName, validateEndpoint } from './types';\nimport type { MountContext } from './types';\n\n/**\n * S3 mount config for E2B (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 E2BS3MountConfig 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, 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: E2BS3MountConfig, ctx: MountContext): Promise<void> {\n const { sandbox, logger } = ctx;\n\n // Validate inputs before interpolating into shell commands\n validateBucketName(config.bucket);\n if (config.endpoint) {\n validateEndpoint(config.endpoint);\n }\n\n // Check if s3fs is installed\n const checkResult = await sandbox.commands.run('which s3fs || echo \"not found\"');\n if (checkResult.stdout.includes('not found')) {\n logger.warn(`${LOG_PREFIX} s3fs not found, attempting runtime installation...`);\n logger.info(\n `${LOG_PREFIX} Tip: For faster startup, use createMountableTemplate() to pre-install s3fs in your sandbox template`,\n );\n\n await sandbox.commands.run('sudo apt-get update 2>&1', { timeoutMs: 60000 });\n\n const installResult = await sandbox.commands.run(\n 'sudo apt-get install -y s3fs fuse 2>&1 || sudo apt-get install -y s3fs-fuse fuse 2>&1',\n { timeoutMs: 120000 },\n );\n\n if (installResult.exitCode !== 0) {\n throw new Error(\n `Failed to install s3fs. ` +\n `For S3 mounting, your template needs s3fs and fuse packages.\\n\\n` +\n `Option 1: Use createMountableTemplate() helper:\\n` +\n ` import { E2BSandbox, createMountableTemplate } from '@mastra/e2b';\\n` +\n ` const sandbox = new E2BSandbox({ template: createMountableTemplate() });\\n\\n` +\n `Option 2: Customize the base template:\\n` +\n ` new E2BSandbox({ template: base => base.aptInstall(['your-packages']) })\\n\\n` +\n `Error details: ${installResult.stderr || installResult.stdout}`,\n );\n }\n }\n\n // Get user's uid/gid for proper file ownership\n const idResult = await sandbox.commands.run('id -u && id -g');\n const [uid, gid] = idResult.stdout.trim().split('\\n');\n\n // Determine if we have credentials or using public bucket mode\n const hasCredentials = config.accessKeyId && config.secretAccessKey;\n const credentialsPath = '/tmp/.passwd-s3fs';\n\n // S3-compatible services (R2, MinIO, etc.) require credentials\n // public_bucket=1 only works for truly public AWS S3 buckets\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 if (hasCredentials) {\n // Write credentials file (remove old one first to avoid permission issues)\n const credentialsContent = `${config.accessKeyId}:${config.secretAccessKey}`;\n await sandbox.commands.run(`sudo rm -f ${credentialsPath}`);\n await sandbox.files.write(credentialsPath, credentialsContent);\n await sandbox.commands.run(`chmod 600 ${credentialsPath}`);\n }\n\n // Build mount options\n const mountOptions: string[] = [];\n\n if (hasCredentials) {\n mountOptions.push(`passwd_file=${credentialsPath}`);\n } else {\n // Public bucket mode - read-only access without credentials\n mountOptions.push('public_bucket=1');\n logger.debug(`${LOG_PREFIX} No credentials provided, mounting as public bucket (read-only)`);\n }\n\n mountOptions.push('allow_other'); // Allow non-root users to access the mount\n\n // Set uid/gid so mounted files are owned by user, not root\n if (uid && gid) {\n mountOptions.push(`uid=${uid}`, `gid=${gid}`);\n }\n\n if (config.endpoint) {\n // For S3-compatible storage (MinIO, R2, etc.)\n const endpoint = config.endpoint.replace(/\\/$/, '');\n mountOptions.push(`url=${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 // Mount with sudo (required for /dev/fuse access)\n const mountCmd = `sudo s3fs ${config.bucket} ${mountPath} -o ${mountOptions.join(' -o ')}`;\n logger.debug(`${LOG_PREFIX} Mounting S3:`, hasCredentials ? mountCmd.replace(credentialsPath, '***') : mountCmd);\n\n try {\n const result = await sandbox.commands.run(mountCmd, { timeoutMs: 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 } catch (error: unknown) {\n const errorObj = error as { result?: { exitCode: number; stdout: string; stderr: string } };\n const stderr = errorObj.result?.stderr || '';\n const stdout = errorObj.result?.stdout || '';\n logger.error(`${LOG_PREFIX} s3fs error:`, { stderr, stdout, error: String(error) });\n throw new Error(`Failed to mount S3 bucket: ${stderr || stdout || error}`);\n }\n}\n","import type { FilesystemMountConfig } from '@mastra/core/workspace';\n\nimport { LOG_PREFIX, validateBucketName } from './types';\nimport type { MountContext } from './types';\n\n/**\n * GCS mount config for E2B (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 E2BGCSMountConfig 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: E2BGCSMountConfig, ctx: MountContext): Promise<void> {\n const { sandbox, logger } = ctx;\n\n // Validate inputs before interpolating into shell commands\n validateBucketName(config.bucket);\n\n // Install gcsfuse if not present\n const checkResult = await sandbox.commands.run('which gcsfuse || echo \"not found\"');\n if (checkResult.stdout.includes('not found')) {\n // Detect Ubuntu codename for the gcsfuse repo (default to jammy if unknown)\n const codenameResult = await sandbox.commands.run('lsb_release -cs 2>/dev/null || echo jammy');\n const codename = codenameResult.stdout.trim() || 'jammy';\n\n // Use signed-by keyring instead of deprecated apt-key\n await sandbox.commands.run(\n 'curl -fsSL https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo gpg --dearmor -o /etc/apt/keyrings/gcsfuse.gpg && ' +\n `echo \"deb [signed-by=/etc/apt/keyrings/gcsfuse.gpg] https://packages.cloud.google.com/apt gcsfuse-${codename} main\" | sudo tee /etc/apt/sources.list.d/gcsfuse.list && ` +\n 'sudo apt-get update && sudo apt-get install -y gcsfuse',\n { timeoutMs: 120_000 },\n );\n }\n\n // Get user's uid/gid for proper file ownership\n const idResult = await sandbox.commands.run('id -u && id -g');\n const [uid, gid] = idResult.stdout.trim().split('\\n');\n\n // Build gcsfuse flags\n // Note: gcsfuse uses --uid/--gid flags, not -o uid=X style\n const uidGidFlags = uid && gid ? `--uid=${uid} --gid=${gid}` : '';\n\n const hasCredentials = !!config.serviceAccountKey;\n let mountCmd: string;\n\n if (hasCredentials) {\n // Write service account key with root ownership so sudo gcsfuse can read it\n const keyPath = '/tmp/gcs-key.json';\n await sandbox.commands.run(`sudo rm -f ${keyPath}`);\n await sandbox.files.write(keyPath, config.serviceAccountKey!);\n // Make readable by root (sudo gcsfuse runs as root)\n await sandbox.commands.run(`sudo chown root:root ${keyPath} && sudo chmod 600 ${keyPath}`);\n\n // Mount with credentials using --key-file flag\n // Use sudo for /dev/fuse access (same as s3fs)\n // -o allow_other lets non-root users access the FUSE mount\n mountCmd = `sudo gcsfuse --key-file=${keyPath} -o allow_other ${uidGidFlags} ${config.bucket} ${mountPath}`;\n } else {\n // Public bucket mode - read-only access without credentials\n // Use --anonymous-access flag (not -o option)\n // Use sudo for /dev/fuse access (same as s3fs)\n logger.debug(`${LOG_PREFIX} No credentials provided, mounting GCS as public bucket (read-only)`);\n\n mountCmd = `sudo gcsfuse --anonymous-access -o allow_other ${uidGidFlags} ${config.bucket} ${mountPath}`;\n }\n\n logger.debug(`${LOG_PREFIX} Mounting GCS:`, mountCmd);\n\n try {\n const result = await sandbox.commands.run(mountCmd, { timeoutMs: 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 } catch (error: unknown) {\n const errorObj = error as { result?: { exitCode: number; stdout: string; stderr: string } };\n const stderr = errorObj.result?.stderr || '';\n const stdout = errorObj.result?.stdout || '';\n logger.error(`${LOG_PREFIX} gcsfuse error:`, { stderr, stdout, error: String(error) });\n throw new Error(`Failed to mount GCS bucket: ${stderr || stdout || error}`);\n }\n}\n","/**\n * E2B Process Manager\n *\n * Implements SandboxProcessManager for E2B cloud sandboxes.\n * Wraps the E2B SDK's commands API (background mode, sendStdin, kill, list).\n */\n\nimport { ProcessHandle, SandboxProcessManager } from '@mastra/core/workspace';\nimport type { CommandResult, ProcessInfo, SpawnProcessOptions } from '@mastra/core/workspace';\nimport type { CommandHandle as E2BCommandHandle, Sandbox } from 'e2b';\nimport type { E2BSandbox } from './index';\n\n// =============================================================================\n// E2B Process Handle\n// =============================================================================\n\n/**\n * Wraps an E2B CommandHandle to conform to Mastra's ProcessHandle.\n * Not exported — internal to this module.\n *\n * Listener dispatch is handled by the base class. The manager's spawn()/get()\n * methods wire E2B's constructor-time callbacks to handle.emitStdout/emitStderr.\n */\nclass E2BProcessHandle extends ProcessHandle {\n readonly pid: number;\n\n private readonly _e2bHandle: E2BCommandHandle;\n private readonly _sandbox: Sandbox;\n private readonly _startTime: number;\n\n constructor(e2bHandle: E2BCommandHandle, sandbox: Sandbox, startTime: number, options?: SpawnProcessOptions) {\n super(options);\n this.pid = e2bHandle.pid;\n this._e2bHandle = e2bHandle;\n this._sandbox = sandbox;\n this._startTime = startTime;\n }\n\n /** Delegates to E2B's handle so exitCode reflects server-side state without needing wait(). */\n get exitCode(): number | undefined {\n return this._e2bHandle.exitCode;\n }\n\n async wait(): Promise<CommandResult> {\n try {\n const result = await this._e2bHandle.wait();\n return {\n success: result.exitCode === 0,\n exitCode: result.exitCode,\n stdout: this.stdout,\n stderr: this.stderr,\n executionTimeMs: Date.now() - this._startTime,\n };\n } catch (error) {\n // E2B throws CommandExitError for non-zero exit codes (has .exitCode directly)\n // Some E2B errors also carry stdout/stderr in error.result\n const errorObj = error as {\n exitCode?: number;\n result?: { exitCode: number; stdout: string; stderr: string };\n };\n const exitCode = errorObj.result?.exitCode ?? errorObj.exitCode ?? this.exitCode ?? 1;\n\n // Emit any output attached to the error (E2B sometimes puts it in .result)\n if (errorObj.result?.stdout) this.emitStdout(errorObj.result.stdout);\n if (errorObj.result?.stderr) this.emitStderr(errorObj.result.stderr);\n\n return {\n success: false,\n exitCode,\n stdout: this.stdout,\n stderr: this.stderr || (error instanceof Error ? error.message : String(error)),\n executionTimeMs: Date.now() - this._startTime,\n };\n }\n }\n\n async kill(): Promise<boolean> {\n if (this.exitCode !== undefined) return false;\n return this._e2bHandle.kill();\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.commands.sendStdin(this.pid, data);\n }\n}\n\n// =============================================================================\n// E2B Process Manager\n// =============================================================================\n\n/**\n * E2B implementation of SandboxProcessManager.\n * Uses the E2B SDK's commands.run() with background: true.\n */\nexport class E2BProcessManager extends SandboxProcessManager<E2BSandbox> {\n async spawn(command: string, options: SpawnProcessOptions = {}): Promise<ProcessHandle> {\n return this.sandbox.retryOnDead(async () => {\n const e2b = this.sandbox.e2b;\n\n // Merge default env with per-spawn env\n const mergedEnv = { ...this.env, ...options.env };\n const envs = Object.fromEntries(\n Object.entries(mergedEnv).filter((entry): entry is [string, string] => entry[1] !== undefined),\n );\n\n // Deferred reference — E2B requires callbacks at run() time, but data\n // arrives asynchronously after the promise resolves, so handle is always\n // assigned by the time the first callback fires.\n let handle: E2BProcessHandle;\n\n const e2bHandle = await e2b.commands.run(command, {\n background: true,\n stdin: true,\n cwd: options.cwd,\n envs,\n timeoutMs: options.timeout,\n onStdout: (data: string) => handle.emitStdout(data),\n onStderr: (data: string) => handle.emitStderr(data),\n });\n\n handle = new E2BProcessHandle(e2bHandle, e2b, Date.now(), options);\n this._tracked.set(handle.pid, handle);\n return handle;\n });\n }\n\n /**\n * List processes by querying E2B's commands API.\n * E2B manages all state server-side — no local tracking needed.\n */\n async list(): Promise<ProcessInfo[]> {\n const e2b = this.sandbox.e2b;\n const procs = await e2b.commands.list();\n return procs.map(proc => ({\n pid: proc.pid,\n command: [proc.cmd, ...proc.args].join(' '),\n running: true, // E2B only lists running processes\n }));\n }\n\n /**\n * Get a handle to a process by PID.\n * Checks base class tracking first, then falls back to commands.connect()\n * for processes spawned externally or before reconnection.\n */\n async get(pid: number): Promise<ProcessHandle | undefined> {\n const tracked = this._tracked.get(pid);\n if (tracked) return tracked;\n\n // Fall back to connect() for unknown PIDs (e.g., pre-existing processes)\n const e2b = this.sandbox.e2b;\n let handle: E2BProcessHandle;\n try {\n const e2bHandle = await e2b.commands.connect(pid, {\n onStdout: (data: string) => handle.emitStdout(data),\n onStderr: (data: string) => handle.emitStderr(data),\n });\n handle = new E2BProcessHandle(e2bHandle, e2b, Date.now());\n this._tracked.set(pid, handle);\n return handle;\n } catch {\n return undefined;\n }\n }\n}\n","/**\n * E2B Sandbox Provider\n *\n * A simplified E2B sandbox implementation that supports mounting\n * cloud filesystems (S3, GCS, R2) via FUSE.\n *\n * @see https://e2b.dev/docs\n */\n\nimport type { RequestContext } from '@mastra/core/di';\nimport type {\n SandboxInfo,\n WorkspaceFilesystem,\n MountResult,\n FilesystemMountConfig,\n ProviderStatus,\n MountManager,\n MastraSandboxOptions,\n} from '@mastra/core/workspace';\n\n/**\n * Inlined from `@mastra/core/workspace` to avoid requiring a newer core peer dep.\n */\ntype InstructionsOption = string | ((opts: { defaultInstructions: string; requestContext?: RequestContext }) => string);\nimport { MastraSandbox, SandboxNotReadyError } from '@mastra/core/workspace';\nimport { Sandbox, Template } from 'e2b';\nimport type { TemplateBuilder, TemplateClass } from 'e2b';\nimport { createDefaultMountableTemplate } from '../utils/template';\nimport type { TemplateSpec } from '../utils/template';\nimport { mountS3, mountGCS, LOG_PREFIX } from './mounts';\nimport type { E2BMountConfig, E2BS3MountConfig, E2BGCSMountConfig, MountContext } from './mounts';\nimport { E2BProcessManager } from './process-manager';\n\n/** Allowlist pattern for mount paths — absolute path with safe characters only. */\nconst SAFE_MOUNT_PATH = /^\\/[a-zA-Z0-9_.\\-/]+$/;\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}\n\n/** Allowlist for marker filenames from ls output — e.g. \"mount-abc123\" */\nconst SAFE_MARKER_NAME = /^mount-[a-z0-9]+$/;\n\n// =============================================================================\n// E2B Sandbox Options\n// =============================================================================\n\n/**\n * E2B sandbox provider configuration.\n */\nexport interface E2BSandboxOptions extends MastraSandboxOptions {\n /** Unique identifier for this sandbox instance */\n id?: string;\n /**\n * Sandbox template specification.\n *\n * - `string` - Use an existing template by ID\n * - `TemplateBuilder` - Use a custom template (e.g., from `createMountableTemplate()`)\n * - `(base) => base.aptInstall([...])` - Customize the default mountable template\n *\n * If not provided and mounting is used, a default template with s3fs will be built.\n * For best performance, pre-build your template and use the template ID.\n *\n * @see createDefaultMountableTemplate\n */\n template?: TemplateSpec;\n /** Execution timeout in milliseconds\n *\n * @default 300_000 // 5 minutes\n */\n timeout?: number;\n /** Environment variables to set in the sandbox */\n env?: Record<string, string>;\n /** Custom metadata */\n metadata?: Record<string, unknown>;\n\n /** Domain for self-hosted E2B. Falls back to E2B_DOMAIN env var. */\n domain?: string;\n /** API URL for self-hosted E2B. Falls back to E2B_API_URL env var. */\n apiUrl?: string;\n /** API key for authentication. Falls back to E2B_API_KEY env var. */\n apiKey?: string;\n /** Access token for authentication. Falls back to E2B_ACCESS_TOKEN env var. */\n accessToken?: string;\n /**\n * Custom instructions that override the default instructions\n * returned by `getInstructions()`.\n *\n * - `string` — Fully replaces the default instructions.\n * Pass an empty string to suppress instructions entirely.\n * - `(opts) => string` — Receives the default instructions and\n * optional request context so you can extend or customise per-request.\n */\n instructions?: InstructionsOption;\n}\n\n// =============================================================================\n// E2B Sandbox Implementation\n// =============================================================================\n\n/**\n * Simplified E2B sandbox implementation.\n *\n * Features:\n * - Single sandbox instance lifecycle\n * - Supports mounting cloud filesystems (S3, GCS, R2) via FUSE\n * - Automatic sandbox timeout handling with retry\n *\n * @example Basic usage\n * ```typescript\n * import { Workspace } from '@mastra/core/workspace';\n * import { E2BSandbox } from '@mastra/e2b';\n *\n * const sandbox = new E2BSandbox({\n * timeout: 60000,\n * });\n *\n * const workspace = new Workspace({ sandbox });\n * const result = await workspace.executeCode('console.log(\"Hello!\")');\n * ```\n *\n * @example With S3 filesystem mounting\n * ```typescript\n * import { Workspace } from '@mastra/core/workspace';\n * import { E2BSandbox } from '@mastra/e2b';\n * import { S3Filesystem } from '@mastra/s3';\n *\n * const workspace = new Workspace({\n * mounts: {\n * '/bucket': new S3Filesystem({\n * bucket: 'my-bucket',\n * region: 'us-east-1',\n * }),\n * },\n * sandbox: new E2BSandbox({ timeout: 60000 }),\n * });\n *\n * ```\n */\nexport class E2BSandbox extends MastraSandbox {\n readonly id: string;\n readonly name = 'E2BSandbox';\n readonly provider = 'e2b';\n status: ProviderStatus = 'pending';\n\n declare readonly mounts: MountManager; // Non-optional (initialized by BaseSandbox)\n declare readonly processes: E2BProcessManager;\n\n private _sandbox: Sandbox | null = null;\n private _createdAt: Date | null = null;\n private _isRetrying = false;\n private readonly timeout: number;\n private readonly templateSpec?: TemplateSpec;\n private readonly env: Record<string, string>;\n private readonly metadata: Record<string, unknown>;\n private readonly connectionOpts: Record<string, string>;\n private readonly _instructionsOverride?: InstructionsOption;\n\n /** Resolved template ID after building (if needed) */\n private _resolvedTemplateId?: string;\n\n /** Promise for template preparation (started in constructor) */\n private _templatePreparePromise?: Promise<string>;\n\n constructor(options: E2BSandboxOptions = {}) {\n super({\n ...options,\n name: 'E2BSandbox',\n processes: new E2BProcessManager({ env: options.env ?? {} }),\n });\n\n this.id = options.id ?? this.generateId();\n this.timeout = options.timeout ?? 300_000; // 5 minutes;\n this.templateSpec = options.template;\n this.env = options.env ?? {};\n this.metadata = options.metadata ?? {};\n this.connectionOpts = {\n ...(options.domain && { domain: options.domain }),\n ...(options.apiUrl && { apiUrl: options.apiUrl }),\n ...(options.apiKey && { apiKey: options.apiKey }),\n ...(options.accessToken && { accessToken: options.accessToken }),\n };\n\n this._instructionsOverride = options.instructions;\n\n // Start template preparation immediately in background\n // This way template build (if needed) begins before start() is called\n this._templatePreparePromise = this.resolveTemplate().catch(err => {\n this.logger.debug(`${LOG_PREFIX} Template preparation error (will retry on start):`, err);\n return ''; // Return empty string, will be retried in start()\n });\n }\n\n /**\n * Get the underlying E2B Sandbox instance for direct access to E2B APIs.\n *\n * Use this when you need to access E2B features not exposed through the\n * WorkspaceSandbox interface (e.g., files API, ports, etc.).\n *\n * @throws {SandboxNotReadyError} If the sandbox has not been started\n *\n * @example Direct file operations\n * ```typescript\n * const e2b = sandbox.e2b;\n * await e2b.files.write('/tmp/test.txt', 'Hello');\n * const content = await e2b.files.read('/tmp/test.txt');\n * const files = await e2b.files.list('/tmp');\n * ```\n *\n * @example Access ports\n * ```typescript\n * const e2b = sandbox.e2b;\n * const url = e2b.getHost(3000);\n * ```\n */\n get e2b(): Sandbox {\n if (!this._sandbox) {\n throw new SandboxNotReadyError(this.id);\n }\n return this._sandbox;\n }\n\n // ---------------------------------------------------------------------------\n // Lifecycle\n // ---------------------------------------------------------------------------\n\n /**\n * Start the E2B sandbox.\n * Handles template preparation, existing sandbox reconnection, and new sandbox creation.\n *\n * Status management and mount processing are handled by the base class.\n */\n async start(): Promise<void> {\n // Already have a sandbox instance\n if (this._sandbox) {\n return;\n }\n\n // Await template preparation (started in constructor) and existing sandbox search in parallel\n const [existingSandbox, templateId] = await Promise.all([\n this.findExistingSandbox(),\n this._templatePreparePromise || this.resolveTemplate(),\n ]);\n\n if (existingSandbox) {\n this._sandbox = existingSandbox;\n this._createdAt = new Date();\n this.logger.debug(`${LOG_PREFIX} Reconnected to existing sandbox for: ${this.id}`);\n\n // Clean up stale mounts from previous config\n // (processPending is called by base class after start completes)\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 return;\n }\n\n // If template preparation failed earlier, retry now\n let resolvedTemplateId = templateId;\n if (!resolvedTemplateId) {\n this.logger.debug(`${LOG_PREFIX} Template preparation failed earlier, retrying...`);\n resolvedTemplateId = await this.resolveTemplate();\n }\n\n // Create a new sandbox with our logical ID in metadata\n // Using betaCreate with autoPause so sandbox pauses on timeout instead of being destroyed\n this.logger.debug(`${LOG_PREFIX} Creating new sandbox for: ${this.id} with template: ${resolvedTemplateId}`);\n\n try {\n this._sandbox = await Sandbox.betaCreate(resolvedTemplateId, {\n ...this.connectionOpts,\n autoPause: true,\n metadata: {\n ...this.metadata,\n 'mastra-sandbox-id': this.id,\n },\n timeoutMs: this.timeout,\n });\n } catch (createError) {\n // If template not found (404), rebuild it and retry\n const errorStr = String(createError);\n if (errorStr.includes('404') && errorStr.includes('not found') && !this.templateSpec) {\n this.logger.debug(`${LOG_PREFIX} Template not found, rebuilding: ${templateId}`);\n this._resolvedTemplateId = undefined; // Clear cached ID to force rebuild\n const rebuiltTemplateId = await this.buildDefaultTemplate();\n\n this.logger.debug(`${LOG_PREFIX} Retrying sandbox creation with rebuilt template: ${rebuiltTemplateId}`);\n this._sandbox = await Sandbox.betaCreate(rebuiltTemplateId, {\n ...this.connectionOpts,\n autoPause: true,\n metadata: {\n ...this.metadata,\n 'mastra-sandbox-id': this.id,\n },\n timeoutMs: this.timeout,\n });\n } else {\n throw createError;\n }\n }\n\n this.logger.debug(`${LOG_PREFIX} Created sandbox ${this._sandbox.sandboxId} for logical ID: ${this.id}`);\n this._createdAt = new Date();\n // Note: processPending is called by base class after start completes\n }\n\n /**\n * Stop the E2B sandbox.\n * Unmounts all filesystems and releases the sandbox reference.\n * Status management is handled by the base class.\n */\n async stop(): Promise<void> {\n // Kill all background processes before stopping\n try {\n const procs = await this.processes.list();\n await Promise.all(procs.map(p => this.processes.kill(p.pid)));\n } catch {\n // Best-effort: sandbox may already be dead\n }\n\n // Unmount all filesystems before stopping\n // Collect keys first since unmount() mutates the map\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 this._sandbox = null;\n }\n\n /**\n * Destroy the E2B sandbox and clean up all resources.\n * Unmounts filesystems, kills the sandbox, and clears mount state.\n * Status management is handled by the base class.\n */\n async destroy(): Promise<void> {\n if (this._sandbox) {\n // Kill all background processes\n try {\n const procs = await this.processes.list();\n await Promise.all(procs.map(p => this.processes.kill(p.pid)));\n } catch {\n // Best-effort: sandbox may already be dead\n }\n\n // Unmount all filesystems\n // Collect keys first since unmount() mutates the map\n for (const mountPath of [...this.mounts.entries.keys()]) {\n try {\n await this.unmount(mountPath);\n } catch {\n // Ignore errors during cleanup\n }\n }\n\n try {\n await this._sandbox.kill();\n } catch {\n // Ignore errors during destroy\n }\n\n this._sandbox = null;\n }\n\n this.mounts.clear();\n }\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: Array.from(this.mounts.entries).map(([path, entry]) => ({\n path,\n filesystem: entry.filesystem?.provider ?? entry.config?.type ?? 'unknown',\n })),\n metadata: {\n ...this.metadata,\n },\n };\n }\n\n /**\n * Get instructions describing this E2B sandbox.\n * Used by agents to understand the execution environment.\n */\n getInstructions(opts?: { requestContext?: RequestContext }): string {\n if (this._instructionsOverride === undefined) return this._getDefaultInstructions();\n if (typeof this._instructionsOverride === 'string') return this._instructionsOverride;\n const defaultInstructions = this._getDefaultInstructions();\n return this._instructionsOverride({ defaultInstructions, requestContext: opts?.requestContext });\n }\n\n private _getDefaultInstructions(): string {\n const mountCount = this.mounts.entries.size;\n const mountInfo = mountCount > 0 ? ` ${mountCount} filesystem(s) mounted via FUSE.` : '';\n return `Cloud sandbox with /home/user as working directory.${mountInfo}`;\n }\n\n // ---------------------------------------------------------------------------\n // Mounting\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\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 E2BMountConfig | 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, unmounting to re-mount with new config...`);\n await this.unmount(mountPath);\n }\n this.logger.debug(`${LOG_PREFIX} Config type: ${config.type}`);\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\n // Check if directory exists and is non-empty (would shadow existing files)\n try {\n const checkResult = await this._sandbox.commands.run(\n `[ -d \"${mountPath}\" ] && [ \"$(ls -A \"${mountPath}\" 2>/dev/null)\" ] && echo \"non-empty\" || echo \"ok\"`,\n );\n if (checkResult.stdout.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 mount directory with sudo (for paths outside home dir like /data)\n // Then chown to current user so mount works without issues\n try {\n this.logger.debug(`${LOG_PREFIX} Creating mount directory for ${mountPath}...`);\n const mkdirCommand = `sudo mkdir -p \"${mountPath}\" && sudo chown $(id -u):$(id -g) \"${mountPath}\"`;\n\n this.logger.debug(`${LOG_PREFIX} Running command: ${mkdirCommand}`);\n const mkdirResult = await this._sandbox.commands.run(mkdirCommand);\n\n this.logger.debug(`${LOG_PREFIX} Created mount directory for mount path \"${mountPath}\":`, mkdirResult);\n } catch (mkdirError) {\n this.logger.debug(`${LOG_PREFIX} mkdir error for \"${mountPath}\":`, mkdirError);\n this.mounts.set(mountPath, { filesystem, state: 'error', config, error: String(mkdirError) });\n return { success: false, mountPath, error: String(mkdirError) };\n }\n\n // Create mount context for mount operations\n const mountCtx: MountContext = {\n sandbox: this._sandbox,\n logger: this.logger,\n };\n\n try {\n switch (config.type) {\n case 's3':\n this.logger.debug(`${LOG_PREFIX} Mounting S3 bucket at ${mountPath}...`);\n await mountS3(mountPath, config as E2BS3MountConfig, 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 bucket at ${mountPath}...`);\n await mountGCS(mountPath, config as E2BGCSMountConfig, mountCtx);\n this.logger.debug(`${LOG_PREFIX} Mounted GCS bucket at ${mountPath}`);\n break;\n default:\n this.mounts.set(mountPath, {\n filesystem,\n state: 'unsupported',\n config,\n error: `Unsupported mount type: ${(config as FilesystemMountConfig).type}`,\n });\n return {\n success: false,\n mountPath,\n error: `Unsupported mount type: ${(config as FilesystemMountConfig).type}`,\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: String(error) });\n\n // Clean up the directory we created since mount failed\n try {\n await this._sandbox!.commands.run(`sudo rmdir \"${mountPath}\" 2>/dev/null || true`);\n this.logger.debug(`${LOG_PREFIX} Cleaned up directory after failed mount: ${mountPath}`);\n } catch {\n // Ignore cleanup errors\n }\n\n return { success: false, mountPath, error: String(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\n this.logger.debug(`${LOG_PREFIX} Unmounting ${mountPath}...`);\n\n try {\n // Use fusermount for FUSE mounts, fall back to umount\n const result = await this._sandbox.commands.run(\n `sudo fusermount -u \"${mountPath}\" 2>/dev/null || sudo umount \"${mountPath}\"`,\n );\n if (result.exitCode !== 0) {\n this.logger.debug(`${LOG_PREFIX} Unmount warning: ${result.stderr || result.stdout}`);\n }\n } catch (error) {\n this.logger.debug(`${LOG_PREFIX} Unmount error:`, error);\n // Try lazy unmount as last resort\n await this._sandbox.commands.run(`sudo umount -l \"${mountPath}\" 2>/dev/null || true`);\n }\n\n this.mounts.delete(mountPath);\n\n // Clean up marker file\n const filename = this.mounts.markerFilename(mountPath);\n const markerPath = `/tmp/.mastra-mounts/${filename}`;\n await this._sandbox.commands.run(`rm -f \"${markerPath}\" 2>/dev/null || true`);\n\n // Remove empty mount directory (only if empty, rmdir fails on non-empty)\n // Use sudo since mount directories outside home (like /data) were created with sudo\n const rmdirResult = await this._sandbox.commands.run(`sudo rmdir \"${mountPath}\" 2>&1`);\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.stderr?.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) {\n throw new SandboxNotReadyError(this.id);\n }\n\n this.logger.debug(`${LOG_PREFIX} Reconciling mounts. Expected paths:`, expectedMountPaths);\n\n // Get current FUSE mounts in the sandbox\n const mountsResult = await this._sandbox.commands.run(\n `grep -E 'fuse\\\\.(s3fs|gcsfuse)' /proc/mounts | awk '{print $2}'`,\n );\n const currentMounts = mountsResult.stdout\n .trim()\n .split('\\n')\n .filter(p => p.length > 0);\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 const markersResult = await this._sandbox.commands.run(`ls /tmp/.mastra-mounts/ 2>/dev/null || echo \"\"`);\n const markerFiles = markersResult.stdout\n .trim()\n .split('\\n')\n .filter(f => f.length > 0 && SAFE_MARKER_NAME.test(f));\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 this._sandbox.commands.run(\n `cat \"/tmp/.mastra-mounts/${markerFile}\" 2>/dev/null || echo \"\"`,\n );\n const parsed = this.mounts.parseMarkerContent(markerResult.stdout.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 await this.unmount(stalePath);\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\n // Remove marker file\n await this._sandbox.commands.run(`rm -f \"/tmp/.mastra-mounts/${markerFile}\" 2>/dev/null || true`);\n\n // Try to remove the directory (will fail if not empty or doesn't exist, which is fine)\n await this._sandbox.commands.run(`sudo rmdir \"${mountPath}\" 2>/dev/null || true`);\n }\n } else {\n // Malformed marker file - just delete it\n this.logger.debug(`${LOG_PREFIX} Removing malformed marker file: ${markerFile}`);\n await this._sandbox.commands.run(`rm -f \"/tmp/.mastra-mounts/${markerFile}\" 2>/dev/null || true`);\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 // Deprecated\n // ---------------------------------------------------------------------------\n\n /** @deprecated Use `e2b` instead. */\n get instance(): Sandbox {\n return this.e2b;\n }\n\n /** @deprecated Use `status === 'running'` instead. */\n async isReady(): Promise<boolean> {\n return this.status === 'running' && this._sandbox !== null;\n }\n\n // ---------------------------------------------------------------------------\n // Internal Helpers\n // ---------------------------------------------------------------------------\n\n private generateId(): string {\n return `e2b-sandbox-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;\n }\n\n /**\n * Find an existing sandbox with matching mastra-sandbox-id metadata.\n * Returns the connected sandbox if found, null otherwise.\n */\n private async findExistingSandbox(): Promise<Sandbox | null> {\n try {\n // Query E2B for existing sandbox with our logical ID in metadata\n const paginator = Sandbox.list({\n ...this.connectionOpts,\n query: {\n metadata: { 'mastra-sandbox-id': this.id },\n state: ['running', 'paused'],\n },\n });\n\n const sandboxes = await paginator.nextItems();\n\n this.logger.debug(`${LOG_PREFIX} sandboxes:`, sandboxes);\n\n // Sandbox.list only returns running/paused sandboxes, so no need to filter\n if (sandboxes.length > 0) {\n const existingSandbox = sandboxes[0]!;\n this.logger.debug(\n `${LOG_PREFIX} Found existing sandbox for ${this.id}: ${existingSandbox.sandboxId} (state: ${existingSandbox.state})`,\n );\n return await Sandbox.connect(existingSandbox.sandboxId, this.connectionOpts);\n }\n } catch (e) {\n this.logger.debug(`${LOG_PREFIX} Error querying for existing sandbox:`, e);\n // Continue to create new sandbox\n }\n\n return null;\n }\n\n /**\n * Resolve the template specification to a template ID.\n *\n * - String: Use as-is (template ID)\n * - TemplateBuilder: Build and return the template ID\n * - Function: Apply to base mountable template, then build\n * - undefined: Use default mountable template (cached)\n */\n private async resolveTemplate(): Promise<string> {\n // If already resolved, return cached ID\n if (this._resolvedTemplateId) {\n return this._resolvedTemplateId;\n }\n\n // No template specified - use default mountable template with caching\n if (!this.templateSpec) {\n const { template, id } = createDefaultMountableTemplate();\n\n // Check if template already exists (cached from previous runs)\n const exists = await Template.exists(id, this.connectionOpts);\n if (exists) {\n this.logger.debug(`${LOG_PREFIX} Using cached mountable template: ${id}`);\n this._resolvedTemplateId = id;\n return id;\n }\n\n // Build the template (first time only)\n this.logger.debug(`${LOG_PREFIX} Building default mountable template: ${id}...`);\n const buildResult = await Template.build(template as TemplateClass, id, this.connectionOpts);\n this._resolvedTemplateId = buildResult.templateId;\n this.logger.debug(`${LOG_PREFIX} Template built and cached: ${buildResult.templateId}`);\n return buildResult.templateId;\n }\n\n // String template ID - use directly\n if (typeof this.templateSpec === 'string') {\n this._resolvedTemplateId = this.templateSpec;\n return this.templateSpec;\n }\n\n // TemplateBuilder or function - need to build\n let template: TemplateBuilder;\n let templateName: string;\n\n if (typeof this.templateSpec === 'function') {\n // Apply customization function to base mountable template\n const { template: baseTemplate } = createDefaultMountableTemplate();\n template = this.templateSpec(baseTemplate);\n // Custom templates get unique names since they're modified\n templateName = `mastra-custom-${this.id.replace(/[^a-zA-Z0-9-]/g, '-')}`;\n } else {\n // Use provided TemplateBuilder directly\n template = this.templateSpec;\n templateName = `mastra-${this.id.replace(/[^a-zA-Z0-9-]/g, '-')}`;\n }\n\n // Build the template\n this.logger.debug(`${LOG_PREFIX} Building custom template: ${templateName}...`);\n const buildResult = await Template.build(template as TemplateClass, templateName, this.connectionOpts);\n this._resolvedTemplateId = buildResult.templateId;\n this.logger.debug(`${LOG_PREFIX} Template built: ${buildResult.templateId}`);\n\n return buildResult.templateId;\n }\n\n /**\n * Build the default mountable template (bypasses exists check).\n */\n private async buildDefaultTemplate(): Promise<string> {\n const { template, id } = createDefaultMountableTemplate();\n this.logger.debug(`${LOG_PREFIX} Building default mountable template: ${id}...`);\n const buildResult = await Template.build(template as TemplateClass, id, this.connectionOpts);\n this._resolvedTemplateId = buildResult.templateId;\n this.logger.debug(`${LOG_PREFIX} Template built: ${buildResult.templateId}`);\n return buildResult.templateId;\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 this._sandbox.commands.run('mkdir -p /tmp/.mastra-mounts');\n await this._sandbox.files.write(markerPath, markerContent);\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 if the config matches.\n */\n private async checkExistingMount(\n mountPath: string,\n newConfig: E2BMountConfig,\n ): Promise<'not_mounted' | 'matching' | 'mismatched'> {\n if (!this._sandbox) throw new SandboxNotReadyError(this.id);\n\n // Check if path is a mount point\n const mountCheck = await this._sandbox.commands.run(\n `mountpoint -q \"${mountPath}\" && echo \"mounted\" || echo \"not mounted\"`,\n );\n\n if (mountCheck.stdout.trim() !== 'mounted') {\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\n try {\n const markerResult = await this._sandbox.commands.run(`cat \"${markerPath}\" 2>/dev/null || echo \"\"`);\n const parsed = this.mounts.parseMarkerContent(markerResult.stdout.trim());\n\n if (!parsed) {\n return 'mismatched';\n }\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 } catch {\n // Marker doesn't exist or can't be read - treat as mismatched\n }\n\n return 'mismatched';\n }\n\n /**\n * Check if an error indicates the sandbox itself is dead/gone.\n * Does NOT include code execution timeouts (those are the user's code taking too long).\n * Does NOT include \"port is not open\" - that needs sandbox kill, not reconnect.\n */\n private isSandboxDeadError(error: unknown): boolean {\n if (!error) return false;\n const errorStr = String(error);\n return (\n errorStr.includes('sandbox was not found') ||\n errorStr.includes('Sandbox is probably not running') ||\n errorStr.includes('Sandbox not found') ||\n errorStr.includes('sandbox has been killed')\n );\n }\n\n /**\n * Handle sandbox timeout by clearing the instance and resetting state.\n *\n * Bypasses the normal stop() lifecycle because the sandbox is already dead —\n * we can't unmount filesystems or run cleanup commands. Instead we reset\n * mount states to 'pending' so they get re-mounted when start() runs again.\n */\n private handleSandboxTimeout(): void {\n this._sandbox = null;\n\n // Reset mounted entries to pending so they get re-mounted on restart\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 this.status = 'stopped';\n }\n\n /**\n * Execute an operation with automatic retry if the sandbox is found to be dead.\n *\n * When the E2B sandbox times out or crashes mid-operation, this method\n * resets sandbox state, restarts it, and retries the operation once.\n *\n * @internal Used by E2BProcessManager to handle dead sandboxes during spawn.\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","/**\n * E2B sandbox provider descriptor for MastraEditor.\n *\n * @example\n * ```typescript\n * import { e2bSandboxProvider } from '@mastra/e2b';\n *\n * const editor = new MastraEditor({\n * sandboxes: [e2bSandboxProvider],\n * });\n * ```\n */\nimport type { SandboxProvider } from '@mastra/core/editor';\nimport { E2BSandbox } from './sandbox';\n\n/**\n * Serializable subset of E2BSandboxOptions for editor storage.\n * Non-serializable options (TemplateBuilder callbacks, runtime objects) are excluded.\n */\ninterface E2BProviderConfig {\n template?: string;\n timeout?: number;\n env?: Record<string, string>;\n metadata?: Record<string, unknown>;\n domain?: string;\n apiUrl?: string;\n apiKey?: string;\n accessToken?: string;\n}\n\nexport const e2bSandboxProvider: SandboxProvider<E2BProviderConfig> = {\n id: 'e2b',\n name: 'E2B Sandbox',\n description: 'Cloud sandbox powered by E2B',\n configSchema: {\n type: 'object',\n properties: {\n template: { type: 'string', description: 'Sandbox template ID' },\n timeout: { type: 'number', description: 'Execution timeout in milliseconds', default: 300000 },\n env: {\n type: 'object',\n description: 'Environment variables',\n additionalProperties: { type: 'string' },\n },\n metadata: {\n type: 'object',\n description: 'Custom metadata',\n additionalProperties: true,\n },\n domain: { type: 'string', description: 'Domain for self-hosted E2B' },\n apiUrl: { type: 'string', description: 'API URL for self-hosted E2B' },\n apiKey: { type: 'string', description: 'E2B API key' },\n accessToken: { type: 'string', description: 'E2B access token' },\n },\n },\n createSandbox: config => new E2BSandbox(config),\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/utils/template.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","../src/provider.ts"],"names":["template","Template","buildResult"],"mappings":";;;;;AAiEO,IAAM,0BAAA,GAA6B,IAAA;AAgCnC,SAAS,8BAAA,GAA0D;AACxE,EAAA,MAAM,WAAA,GAAc,CAAC,MAAA,EAAQ,MAAM,CAAA;AACnC,EAAA,MAAM,MAAA,GAAS,EAAE,OAAA,EAAS,0BAAA,EAA4B,WAAA,EAAY;AAElE,EAAA,MAAM,IAAA,GAAO,WAAW,QAAQ,CAAA,CAC7B,OAAO,IAAA,CAAK,SAAA,CAAU,QAAQ,MAAA,CAAO,IAAA,CAAK,MAAM,CAAA,CAAE,IAAA,EAAM,CAAC,CAAA,CACzD,OAAO,KAAK,CAAA,CACZ,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA;AAEd,EAAA,MAAM,WAAW,QAAA,EAAS,CAAE,aAAa,MAAM,CAAA,CAAE,WAAW,WAAW,CAAA;AAKvE,EAAA,OAAO;AAAA,IACL,QAAA;AAAA,IACA,EAAA,EAAI,UAAU,IAAI,CAAA,CAAA;AAAA,IAClB;AAAA,GACF;AACF;;;AC9GO,IAAM,UAAA,GAAa,eAAA;A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,mCAAA,EAAqC,SAAS,GAAA,EAAO;AAAA,MAC7F,GAAA,EAAK;AAAA,QACH,IAAA,EAAM,QAAA;AAAA,QACN,WAAA,EAAa,uBAAA;AAAA,QACb,oBAAA,EAAsB,EAAE,IAAA,EAAM,QAAA;AAAS,OACzC;AAAA,MACA,QAAA,EAAU;AAAA,QACR,IAAA,EAAM,QAAA;AAAA,QACN,WAAA,EAAa,iBAAA;AAAA,QACb,oBAAA,EAAsB;AAAA,OACxB;AAAA,MACA,MAAA,EAAQ,EAAE,IAAA,EAAM,QAAA,EAAU,aAAa,4BAAA,EAA6B;AAAA,MACpE,MAAA,EAAQ,EAAE,IAAA,EAAM,QAAA,EAAU,aAAa,6BAAA,EAA8B;AAAA,MACrE,MAAA,EAAQ,EAAE,IAAA,EAAM,QAAA,EAAU,aAAa,aAAA,EAAc;AAAA,MACrD,WAAA,EAAa,EAAE,IAAA,EAAM,QAAA,EAAU,aAAa,kBAAA;AAAmB;AACjE,GACF;AAAA,EACA,aAAA,EAAe,CAAA,MAAA,KAAU,IAAI,UAAA,CAAW,MAAM;AAChD","file":"index.js","sourcesContent":["/**\n * E2B Template Utilities\n *\n * Helper functions for creating and managing E2B sandbox templates.\n */\nimport { createHash } from 'node:crypto';\nimport { Template } from 'e2b';\nimport type { TemplateBuilder } from 'e2b';\n\n// =============================================================================\n// Template Types\n// =============================================================================\n\n/**\n * Template specification for E2B sandbox.\n *\n * Can be:\n * - `string` - Existing template ID (e.g., 'base', 'my-custom-template')\n * - `TemplateBuilder` - A built template object from Template()\n * - `(base: TemplateBuilder) => TemplateBuilder` - Callback to customize the base template\n *\n * @example Using template ID\n * ```typescript\n * new E2BSandbox({ template: 'my-custom-template' })\n * ```\n *\n * @example Using Template builder\n * ```typescript\n * import { Template } from 'e2b';\n *\n * new E2BSandbox({\n * template: Template()\n * .fromUbuntuImage('22.04')\n * .aptInstall(['s3fs', 'curl'])\n * .setEnvs({ NODE_ENV: 'production' })\n * })\n * ```\n *\n * @example Customizing default mountable template\n * ```typescript\n * new E2BSandbox({\n * template: base => base\n * .aptInstall(['nodejs', 'npm'])\n * .runCmd('npm install -g typescript')\n * })\n * ```\n */\nexport type TemplateSpec = string | TemplateBuilder | ((base: TemplateBuilder) => TemplateBuilder);\n\n/**\n * Result from createMountableTemplate containing both the template and its ID.\n */\nexport interface MountableTemplateResult {\n /** The template builder with mount dependencies */\n template: TemplateBuilder;\n /** Deterministic template ID for caching */\n id: string;\n /** List of apt packages installed in the template */\n aptPackages: string[];\n}\n\n/**\n * Version of the default mountable template.\n * Increment this when changing the default template dependencies.\n */\nexport const MOUNTABLE_TEMPLATE_VERSION = 'v1';\n\n/**\n * Create a base template with FUSE mounting dependencies pre-installed.\n *\n * This template includes s3fs and fuse packages required for mounting\n * cloud filesystems (S3, GCS, R2) into the sandbox.\n *\n * The returned `id` is deterministic, allowing E2BSandbox to check if\n * the template already exists before building it.\n *\n * @example Basic usage\n * ```typescript\n * const { template, id } = createMountableTemplate();\n * // First time: builds and caches the template\n * // Subsequent times: reuses existing template\n * const sandbox = new E2BSandbox({ template });\n * ```\n *\n * @example With customization\n * ```typescript\n * const { template } = createMountableTemplate();\n * const customTemplate = template\n * .aptInstall(['nodejs', 'npm'])\n * .runCmd('npm install -g typescript');\n *\n * // Note: customized templates get a unique ID, not the cached one\n * const sandbox = new E2BSandbox({ template: customTemplate });\n * ```\n *\n * @returns Object with template builder and deterministic ID\n */\nexport function createDefaultMountableTemplate(): MountableTemplateResult {\n const aptPackages = ['s3fs', 'fuse'];\n const config = { version: MOUNTABLE_TEMPLATE_VERSION, aptPackages };\n\n const hash = createHash('sha256')\n .update(JSON.stringify(config, Object.keys(config).sort()))\n .digest('hex')\n .slice(0, 16);\n\n const template = Template().fromTemplate('base').aptInstall(aptPackages);\n\n // Note: gcsfuse requires adding Google's apt repo which can be flaky\n // For now, we'll install it at mount time if needed\n\n return {\n template,\n id: `mastra-${hash}`,\n aptPackages,\n };\n}\n","/**\n * Shared types for E2B mount operations.\n */\n\nimport type { Sandbox } from 'e2b';\n\nexport const LOG_PREFIX = '[@mastra/e2b]';\n\nimport type { E2BGCSMountConfig } from './gcs';\nimport type { E2BS3MountConfig } from './s3';\n\n/**\n * Union of mount configs supported by E2B sandbox.\n */\nexport type E2BMountConfig = E2BS3MountConfig | E2BGCSMountConfig;\n\n/**\n * Context for mount operations.\n */\nexport interface MountContext {\n sandbox: Sandbox;\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 * Result of a mount operation.\n */\nexport interface MountOperationResult {\n success: boolean;\n error?: string;\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 */\nexport function validateEndpoint(endpoint: string): void {\n try {\n new URL(endpoint);\n } catch {\n throw new Error(`Invalid endpoint URL: \"${endpoint}\"`);\n }\n}\n","import type { FilesystemMountConfig } from '@mastra/core/workspace';\n\nimport { LOG_PREFIX, validateBucketName, validateEndpoint } from './types';\nimport type { MountContext } from './types';\n\n/**\n * S3 mount config for E2B (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 E2BS3MountConfig 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, 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: E2BS3MountConfig, ctx: MountContext): Promise<void> {\n const { sandbox, logger } = ctx;\n\n // Validate inputs before interpolating into shell commands\n validateBucketName(config.bucket);\n if (config.endpoint) {\n validateEndpoint(config.endpoint);\n }\n\n // Check if s3fs is installed\n const checkResult = await sandbox.commands.run('which s3fs || echo \"not found\"');\n if (checkResult.stdout.includes('not found')) {\n logger.warn(`${LOG_PREFIX} s3fs not found, attempting runtime installation...`);\n logger.info(\n `${LOG_PREFIX} Tip: For faster startup, use createMountableTemplate() to pre-install s3fs in your sandbox template`,\n );\n\n await sandbox.commands.run('sudo apt-get update 2>&1', { timeoutMs: 60000 });\n\n const installResult = await sandbox.commands.run(\n 'sudo apt-get install -y s3fs fuse 2>&1 || sudo apt-get install -y s3fs-fuse fuse 2>&1',\n { timeoutMs: 120000 },\n );\n\n if (installResult.exitCode !== 0) {\n throw new Error(\n `Failed to install s3fs. ` +\n `For S3 mounting, your template needs s3fs and fuse packages.\\n\\n` +\n `Option 1: Use createMountableTemplate() helper:\\n` +\n ` import { E2BSandbox, createMountableTemplate } from '@mastra/e2b';\\n` +\n ` const sandbox = new E2BSandbox({ template: createMountableTemplate() });\\n\\n` +\n `Option 2: Customize the base template:\\n` +\n ` new E2BSandbox({ template: base => base.aptInstall(['your-packages']) })\\n\\n` +\n `Error details: ${installResult.stderr || installResult.stdout}`,\n );\n }\n }\n\n // Get user's uid/gid for proper file ownership\n const idResult = await sandbox.commands.run('id -u && id -g');\n const [uid, gid] = idResult.stdout.trim().split('\\n');\n\n // Determine if we have credentials or using public bucket mode\n const hasCredentials = config.accessKeyId && config.secretAccessKey;\n const credentialsPath = '/tmp/.passwd-s3fs';\n\n // S3-compatible services (R2, MinIO, etc.) require credentials\n // public_bucket=1 only works for truly public AWS S3 buckets\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 if (hasCredentials) {\n // Write credentials file (remove old one first to avoid permission issues)\n const credentialsContent = `${config.accessKeyId}:${config.secretAccessKey}`;\n await sandbox.commands.run(`sudo rm -f ${credentialsPath}`);\n await sandbox.files.write(credentialsPath, credentialsContent);\n await sandbox.commands.run(`chmod 600 ${credentialsPath}`);\n }\n\n // Build mount options\n const mountOptions: string[] = [];\n\n if (hasCredentials) {\n mountOptions.push(`passwd_file=${credentialsPath}`);\n } else {\n // Public bucket mode - read-only access without credentials\n mountOptions.push('public_bucket=1');\n logger.debug(`${LOG_PREFIX} No credentials provided, mounting as public bucket (read-only)`);\n }\n\n mountOptions.push('allow_other'); // Allow non-root users to access the mount\n\n // Set uid/gid so mounted files are owned by user, not root\n if (uid && gid) {\n mountOptions.push(`uid=${uid}`, `gid=${gid}`);\n }\n\n if (config.endpoint) {\n // For S3-compatible storage (MinIO, R2, etc.)\n const endpoint = config.endpoint.replace(/\\/$/, '');\n mountOptions.push(`url=${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 // Mount with sudo (required for /dev/fuse access)\n const mountCmd = `sudo s3fs ${config.bucket} ${mountPath} -o ${mountOptions.join(' -o ')}`;\n logger.debug(`${LOG_PREFIX} Mounting S3:`, hasCredentials ? mountCmd.replace(credentialsPath, '***') : mountCmd);\n\n try {\n const result = await sandbox.commands.run(mountCmd, { timeoutMs: 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 } catch (error: unknown) {\n const errorObj = error as { result?: { exitCode: number; stdout: string; stderr: string } };\n const stderr = errorObj.result?.stderr || '';\n const stdout = errorObj.result?.stdout || '';\n logger.error(`${LOG_PREFIX} s3fs error:`, { stderr, stdout, error: String(error) });\n throw new Error(`Failed to mount S3 bucket: ${stderr || stdout || error}`);\n }\n}\n","import type { FilesystemMountConfig } from '@mastra/core/workspace';\n\nimport { LOG_PREFIX, validateBucketName } from './types';\nimport type { MountContext } from './types';\n\n/**\n * GCS mount config for E2B (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 E2BGCSMountConfig 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: E2BGCSMountConfig, ctx: MountContext): Promise<void> {\n const { sandbox, logger } = ctx;\n\n // Validate inputs before interpolating into shell commands\n validateBucketName(config.bucket);\n\n // Install gcsfuse if not present\n const checkResult = await sandbox.commands.run('which gcsfuse || echo \"not found\"');\n if (checkResult.stdout.includes('not found')) {\n // Detect Ubuntu codename for the gcsfuse repo (default to jammy if unknown)\n const codenameResult = await sandbox.commands.run('lsb_release -cs 2>/dev/null || echo jammy');\n const codename = codenameResult.stdout.trim() || 'jammy';\n\n // Use signed-by keyring instead of deprecated apt-key\n await sandbox.commands.run(\n 'curl -fsSL https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo gpg --dearmor -o /etc/apt/keyrings/gcsfuse.gpg && ' +\n `echo \"deb [signed-by=/etc/apt/keyrings/gcsfuse.gpg] https://packages.cloud.google.com/apt gcsfuse-${codename} main\" | sudo tee /etc/apt/sources.list.d/gcsfuse.list && ` +\n 'sudo apt-get update && sudo apt-get install -y gcsfuse',\n { timeoutMs: 120_000 },\n );\n }\n\n // Get user's uid/gid for proper file ownership\n const idResult = await sandbox.commands.run('id -u && id -g');\n const [uid, gid] = idResult.stdout.trim().split('\\n');\n\n // Build gcsfuse flags\n // Note: gcsfuse uses --uid/--gid flags, not -o uid=X style\n const uidGidFlags = uid && gid ? `--uid=${uid} --gid=${gid}` : '';\n\n const hasCredentials = !!config.serviceAccountKey;\n let mountCmd: string;\n\n if (hasCredentials) {\n // Write service account key with root ownership so sudo gcsfuse can read it\n const keyPath = '/tmp/gcs-key.json';\n await sandbox.commands.run(`sudo rm -f ${keyPath}`);\n await sandbox.files.write(keyPath, config.serviceAccountKey!);\n // Make readable by root (sudo gcsfuse runs as root)\n await sandbox.commands.run(`sudo chown root:root ${keyPath} && sudo chmod 600 ${keyPath}`);\n\n // Mount with credentials using --key-file flag\n // Use sudo for /dev/fuse access (same as s3fs)\n // -o allow_other lets non-root users access the FUSE mount\n mountCmd = `sudo gcsfuse --key-file=${keyPath} -o allow_other ${uidGidFlags} ${config.bucket} ${mountPath}`;\n } else {\n // Public bucket mode - read-only access without credentials\n // Use --anonymous-access flag (not -o option)\n // Use sudo for /dev/fuse access (same as s3fs)\n logger.debug(`${LOG_PREFIX} No credentials provided, mounting GCS as public bucket (read-only)`);\n\n mountCmd = `sudo gcsfuse --anonymous-access -o allow_other ${uidGidFlags} ${config.bucket} ${mountPath}`;\n }\n\n logger.debug(`${LOG_PREFIX} Mounting GCS:`, mountCmd);\n\n try {\n const result = await sandbox.commands.run(mountCmd, { timeoutMs: 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 } catch (error: unknown) {\n const errorObj = error as { result?: { exitCode: number; stdout: string; stderr: string } };\n const stderr = errorObj.result?.stderr || '';\n const stdout = errorObj.result?.stdout || '';\n logger.error(`${LOG_PREFIX} gcsfuse error:`, { stderr, stdout, error: String(error) });\n throw new Error(`Failed to mount GCS bucket: ${stderr || stdout || error}`);\n }\n}\n","/**\n * E2B Process Manager\n *\n * Implements SandboxProcessManager for E2B cloud sandboxes.\n * Wraps the E2B SDK's commands API (background mode, sendStdin, kill, list).\n */\n\nimport { ProcessHandle, SandboxProcessManager } from '@mastra/core/workspace';\nimport type { CommandResult, ProcessInfo, SpawnProcessOptions } from '@mastra/core/workspace';\nimport type { CommandHandle as E2BCommandHandle, Sandbox } from 'e2b';\nimport type { E2BSandbox } from './index';\n\n// =============================================================================\n// E2B Process Handle\n// =============================================================================\n\n/**\n * Wraps an E2B CommandHandle to conform to Mastra's ProcessHandle.\n * Not exported — internal to this module.\n *\n * Listener dispatch is handled by the base class. The manager's spawn()/get()\n * methods wire E2B's constructor-time callbacks to handle.emitStdout/emitStderr.\n */\nclass E2BProcessHandle extends ProcessHandle {\n readonly pid: number;\n\n private readonly _e2bHandle: E2BCommandHandle;\n private readonly _sandbox: Sandbox;\n private readonly _startTime: number;\n\n constructor(e2bHandle: E2BCommandHandle, sandbox: Sandbox, startTime: number, options?: SpawnProcessOptions) {\n super(options);\n this.pid = e2bHandle.pid;\n this._e2bHandle = e2bHandle;\n this._sandbox = sandbox;\n this._startTime = startTime;\n }\n\n /** Delegates to E2B's handle so exitCode reflects server-side state without needing wait(). */\n get exitCode(): number | undefined {\n return this._e2bHandle.exitCode;\n }\n\n async wait(): Promise<CommandResult> {\n try {\n const result = await this._e2bHandle.wait();\n return {\n success: result.exitCode === 0,\n exitCode: result.exitCode,\n stdout: this.stdout,\n stderr: this.stderr,\n executionTimeMs: Date.now() - this._startTime,\n };\n } catch (error) {\n // E2B throws CommandExitError for non-zero exit codes (has .exitCode directly)\n // Some E2B errors also carry stdout/stderr in error.result\n const errorObj = error as {\n exitCode?: number;\n result?: { exitCode: number; stdout: string; stderr: string };\n };\n const exitCode = errorObj.result?.exitCode ?? errorObj.exitCode ?? this.exitCode ?? 1;\n\n // Emit any output attached to the error (E2B sometimes puts it in .result)\n if (errorObj.result?.stdout) this.emitStdout(errorObj.result.stdout);\n if (errorObj.result?.stderr) this.emitStderr(errorObj.result.stderr);\n\n return {\n success: false,\n exitCode,\n stdout: this.stdout,\n stderr: this.stderr || (error instanceof Error ? error.message : String(error)),\n executionTimeMs: Date.now() - this._startTime,\n };\n }\n }\n\n async kill(): Promise<boolean> {\n if (this.exitCode !== undefined) return false;\n return this._e2bHandle.kill();\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.commands.sendStdin(this.pid, data);\n }\n}\n\n// =============================================================================\n// E2B Process Manager\n// =============================================================================\n\n/**\n * E2B implementation of SandboxProcessManager.\n * Uses the E2B SDK's commands.run() with background: true.\n */\nexport class E2BProcessManager extends SandboxProcessManager<E2BSandbox> {\n async spawn(command: string, options: SpawnProcessOptions = {}): Promise<ProcessHandle> {\n return this.sandbox.retryOnDead(async () => {\n const e2b = this.sandbox.e2b;\n\n // Merge default env with per-spawn env\n const mergedEnv = { ...this.env, ...options.env };\n const envs = Object.fromEntries(\n Object.entries(mergedEnv).filter((entry): entry is [string, string] => entry[1] !== undefined),\n );\n\n // Deferred reference — E2B requires callbacks at run() time, but data\n // arrives asynchronously after the promise resolves, so handle is always\n // assigned by the time the first callback fires.\n let handle: E2BProcessHandle;\n\n const e2bHandle = await e2b.commands.run(command, {\n background: true,\n stdin: true,\n cwd: options.cwd,\n envs,\n timeoutMs: options.timeout,\n onStdout: (data: string) => handle.emitStdout(data),\n onStderr: (data: string) => handle.emitStderr(data),\n });\n\n handle = new E2BProcessHandle(e2bHandle, e2b, Date.now(), options);\n this._tracked.set(handle.pid, handle);\n return handle;\n });\n }\n\n /**\n * List processes by querying E2B's commands API.\n * E2B manages all state server-side — no local tracking needed.\n */\n async list(): Promise<ProcessInfo[]> {\n const e2b = this.sandbox.e2b;\n const procs = await e2b.commands.list();\n return procs.map(proc => ({\n pid: proc.pid,\n command: [proc.cmd, ...proc.args].join(' '),\n running: true, // E2B only lists running processes\n }));\n }\n\n /**\n * Get a handle to a process by PID.\n * Checks base class tracking first, then falls back to commands.connect()\n * for processes spawned externally or before reconnection.\n */\n async get(pid: number): Promise<ProcessHandle | undefined> {\n const tracked = this._tracked.get(pid);\n if (tracked) return tracked;\n\n // Fall back to connect() for unknown PIDs (e.g., pre-existing processes)\n const e2b = this.sandbox.e2b;\n let handle: E2BProcessHandle;\n try {\n const e2bHandle = await e2b.commands.connect(pid, {\n onStdout: (data: string) => handle.emitStdout(data),\n onStderr: (data: string) => handle.emitStderr(data),\n });\n handle = new E2BProcessHandle(e2bHandle, e2b, Date.now());\n this._tracked.set(pid, handle);\n return handle;\n } catch {\n return undefined;\n }\n }\n}\n","/**\n * E2B Sandbox Provider\n *\n * A simplified E2B sandbox implementation that supports mounting\n * cloud filesystems (S3, GCS, R2) via FUSE.\n *\n * @see https://e2b.dev/docs\n */\n\nimport type { RequestContext } from '@mastra/core/di';\nimport type {\n SandboxInfo,\n WorkspaceFilesystem,\n MountResult,\n FilesystemMountConfig,\n ProviderStatus,\n MountManager,\n MastraSandboxOptions,\n} from '@mastra/core/workspace';\n\n/**\n * Inlined from `@mastra/core/workspace` to avoid requiring a newer core peer dep.\n */\ntype InstructionsOption = string | ((opts: { defaultInstructions: string; requestContext?: RequestContext }) => string);\nimport { MastraSandbox, SandboxNotReadyError } from '@mastra/core/workspace';\nimport { Sandbox, Template } from 'e2b';\nimport type { TemplateBuilder, TemplateClass } from 'e2b';\nimport { createDefaultMountableTemplate } from '../utils/template';\nimport type { TemplateSpec } from '../utils/template';\nimport { mountS3, mountGCS, LOG_PREFIX } from './mounts';\nimport type { E2BMountConfig, E2BS3MountConfig, E2BGCSMountConfig, MountContext } from './mounts';\nimport { E2BProcessManager } from './process-manager';\n\n/** Allowlist pattern for mount paths — absolute path with safe characters only. */\nconst SAFE_MOUNT_PATH = /^\\/[a-zA-Z0-9_.\\-/]+$/;\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}\n\n/** Allowlist for marker filenames from ls output — e.g. \"mount-abc123\" */\nconst SAFE_MARKER_NAME = /^mount-[a-z0-9]+$/;\n\n// =============================================================================\n// E2B Sandbox Options\n// =============================================================================\n\n/**\n * E2B sandbox provider configuration.\n */\nexport interface E2BSandboxOptions extends Omit<MastraSandboxOptions, 'processes'> {\n /** Unique identifier for this sandbox instance */\n id?: string;\n /**\n * Sandbox template specification.\n *\n * - `string` - Use an existing template by ID\n * - `TemplateBuilder` - Use a custom template (e.g., from `createMountableTemplate()`)\n * - `(base) => base.aptInstall([...])` - Customize the default mountable template\n *\n * If not provided and mounting is used, a default template with s3fs will be built.\n * For best performance, pre-build your template and use the template ID.\n *\n * @see createDefaultMountableTemplate\n */\n template?: TemplateSpec;\n /** Execution timeout in milliseconds\n *\n * @default 300_000 // 5 minutes\n */\n timeout?: number;\n /** Environment variables to set in the sandbox */\n env?: Record<string, string>;\n /** Custom metadata */\n metadata?: Record<string, unknown>;\n\n /** Domain for self-hosted E2B. Falls back to E2B_DOMAIN env var. */\n domain?: string;\n /** API URL for self-hosted E2B. Falls back to E2B_API_URL env var. */\n apiUrl?: string;\n /** API key for authentication. Falls back to E2B_API_KEY env var. */\n apiKey?: string;\n /** Access token for authentication. Falls back to E2B_ACCESS_TOKEN env var. */\n accessToken?: string;\n /**\n * Custom instructions that override the default instructions\n * returned by `getInstructions()`.\n *\n * - `string` — Fully replaces the default instructions.\n * Pass an empty string to suppress instructions entirely.\n * - `(opts) => string` — Receives the default instructions and\n * optional request context so you can extend or customise per-request.\n */\n instructions?: InstructionsOption;\n}\n\n// =============================================================================\n// E2B Sandbox Implementation\n// =============================================================================\n\n/**\n * Simplified E2B sandbox implementation.\n *\n * Features:\n * - Single sandbox instance lifecycle\n * - Supports mounting cloud filesystems (S3, GCS, R2) via FUSE\n * - Automatic sandbox timeout handling with retry\n *\n * @example Basic usage\n * ```typescript\n * import { Workspace } from '@mastra/core/workspace';\n * import { E2BSandbox } from '@mastra/e2b';\n *\n * const sandbox = new E2BSandbox({\n * timeout: 60000,\n * });\n *\n * const workspace = new Workspace({ sandbox });\n * const result = await workspace.executeCode('console.log(\"Hello!\")');\n * ```\n *\n * @example With S3 filesystem mounting\n * ```typescript\n * import { Workspace } from '@mastra/core/workspace';\n * import { E2BSandbox } from '@mastra/e2b';\n * import { S3Filesystem } from '@mastra/s3';\n *\n * const workspace = new Workspace({\n * mounts: {\n * '/bucket': new S3Filesystem({\n * bucket: 'my-bucket',\n * region: 'us-east-1',\n * }),\n * },\n * sandbox: new E2BSandbox({ timeout: 60000 }),\n * });\n *\n * ```\n */\nexport class E2BSandbox extends MastraSandbox {\n readonly id: string;\n readonly name = 'E2BSandbox';\n readonly provider = 'e2b';\n status: ProviderStatus = 'pending';\n\n declare readonly mounts: MountManager; // Non-optional (initialized by BaseSandbox)\n declare readonly processes: E2BProcessManager;\n\n private _sandbox: Sandbox | null = null;\n private _createdAt: Date | null = null;\n private _isRetrying = false;\n private readonly timeout: number;\n private readonly templateSpec?: TemplateSpec;\n private readonly env: Record<string, string>;\n private readonly metadata: Record<string, unknown>;\n private readonly connectionOpts: Record<string, string>;\n private readonly _instructionsOverride?: InstructionsOption;\n\n /** Resolved template ID after building (if needed) */\n private _resolvedTemplateId?: string;\n\n /** Promise for template preparation (started in constructor) */\n private _templatePreparePromise?: Promise<string>;\n\n constructor(options: E2BSandboxOptions = {}) {\n super({\n ...options,\n name: 'E2BSandbox',\n processes: new E2BProcessManager({ env: options.env ?? {} }),\n });\n\n this.id = options.id ?? this.generateId();\n this.timeout = options.timeout ?? 300_000; // 5 minutes;\n this.templateSpec = options.template;\n this.env = options.env ?? {};\n this.metadata = options.metadata ?? {};\n this.connectionOpts = {\n ...(options.domain && { domain: options.domain }),\n ...(options.apiUrl && { apiUrl: options.apiUrl }),\n ...(options.apiKey && { apiKey: options.apiKey }),\n ...(options.accessToken && { accessToken: options.accessToken }),\n };\n\n this._instructionsOverride = options.instructions;\n\n // Start template preparation immediately in background\n // This way template build (if needed) begins before start() is called\n this._templatePreparePromise = this.resolveTemplate().catch(err => {\n this.logger.debug(`${LOG_PREFIX} Template preparation error (will retry on start):`, err);\n return ''; // Return empty string, will be retried in start()\n });\n }\n\n /**\n * Get the underlying E2B Sandbox instance for direct access to E2B APIs.\n *\n * Use this when you need to access E2B features not exposed through the\n * WorkspaceSandbox interface (e.g., files API, ports, etc.).\n *\n * @throws {SandboxNotReadyError} If the sandbox has not been started\n *\n * @example Direct file operations\n * ```typescript\n * const e2b = sandbox.e2b;\n * await e2b.files.write('/tmp/test.txt', 'Hello');\n * const content = await e2b.files.read('/tmp/test.txt');\n * const files = await e2b.files.list('/tmp');\n * ```\n *\n * @example Access ports\n * ```typescript\n * const e2b = sandbox.e2b;\n * const url = e2b.getHost(3000);\n * ```\n */\n get e2b(): Sandbox {\n if (!this._sandbox) {\n throw new SandboxNotReadyError(this.id);\n }\n return this._sandbox;\n }\n\n // ---------------------------------------------------------------------------\n // Lifecycle\n // ---------------------------------------------------------------------------\n\n /**\n * Start the E2B sandbox.\n * Handles template preparation, existing sandbox reconnection, and new sandbox creation.\n *\n * Status management and mount processing are handled by the base class.\n */\n async start(): Promise<void> {\n // Already have a sandbox instance\n if (this._sandbox) {\n return;\n }\n\n // Await template preparation (started in constructor) and existing sandbox search in parallel\n const [existingSandbox, templateId] = await Promise.all([\n this.findExistingSandbox(),\n this._templatePreparePromise || this.resolveTemplate(),\n ]);\n\n if (existingSandbox) {\n this._sandbox = existingSandbox;\n this._createdAt = new Date();\n this.logger.debug(`${LOG_PREFIX} Reconnected to existing sandbox for: ${this.id}`);\n\n // Clean up stale mounts from previous config\n // (processPending is called by base class after start completes)\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 return;\n }\n\n // If template preparation failed earlier, retry now\n let resolvedTemplateId = templateId;\n if (!resolvedTemplateId) {\n this.logger.debug(`${LOG_PREFIX} Template preparation failed earlier, retrying...`);\n resolvedTemplateId = await this.resolveTemplate();\n }\n\n // Create a new sandbox with our logical ID in metadata\n // Using betaCreate with autoPause so sandbox pauses on timeout instead of being destroyed\n this.logger.debug(`${LOG_PREFIX} Creating new sandbox for: ${this.id} with template: ${resolvedTemplateId}`);\n\n try {\n this._sandbox = await Sandbox.betaCreate(resolvedTemplateId, {\n ...this.connectionOpts,\n autoPause: true,\n metadata: {\n ...this.metadata,\n 'mastra-sandbox-id': this.id,\n },\n timeoutMs: this.timeout,\n });\n } catch (createError) {\n // If template not found (404), rebuild it and retry\n const errorStr = String(createError);\n if (errorStr.includes('404') && errorStr.includes('not found') && !this.templateSpec) {\n this.logger.debug(`${LOG_PREFIX} Template not found, rebuilding: ${templateId}`);\n this._resolvedTemplateId = undefined; // Clear cached ID to force rebuild\n const rebuiltTemplateId = await this.buildDefaultTemplate();\n\n this.logger.debug(`${LOG_PREFIX} Retrying sandbox creation with rebuilt template: ${rebuiltTemplateId}`);\n this._sandbox = await Sandbox.betaCreate(rebuiltTemplateId, {\n ...this.connectionOpts,\n autoPause: true,\n metadata: {\n ...this.metadata,\n 'mastra-sandbox-id': this.id,\n },\n timeoutMs: this.timeout,\n });\n } else {\n throw createError;\n }\n }\n\n this.logger.debug(`${LOG_PREFIX} Created sandbox ${this._sandbox.sandboxId} for logical ID: ${this.id}`);\n this._createdAt = new Date();\n\n // Note: processPending is called by base class after start completes\n }\n\n /**\n * Stop the E2B sandbox.\n * Unmounts all filesystems and releases the sandbox reference.\n * Status management is handled by the base class.\n */\n async stop(): Promise<void> {\n // Kill all background processes before stopping\n try {\n const procs = await this.processes.list();\n await Promise.all(procs.map(p => this.processes.kill(p.pid)));\n } catch {\n // Best-effort: sandbox may already be dead\n }\n\n // Unmount all filesystems before stopping\n // Collect keys first since unmount() mutates the map\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 this._sandbox = null;\n }\n\n /**\n * Destroy the E2B sandbox and clean up all resources.\n * Unmounts filesystems, kills the sandbox, and clears mount state.\n * Status management is handled by the base class.\n */\n async destroy(): Promise<void> {\n if (this._sandbox) {\n // Kill all background processes\n try {\n const procs = await this.processes.list();\n await Promise.all(procs.map(p => this.processes.kill(p.pid)));\n } catch {\n // Best-effort: sandbox may already be dead\n }\n\n // Unmount all filesystems\n // Collect keys first since unmount() mutates the map\n for (const mountPath of [...this.mounts.entries.keys()]) {\n try {\n await this.unmount(mountPath);\n } catch {\n // Ignore errors during cleanup\n }\n }\n\n try {\n await this._sandbox.kill();\n } catch {\n // Ignore errors during destroy\n }\n\n this._sandbox = null;\n }\n\n this.mounts.clear();\n }\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: Array.from(this.mounts.entries).map(([path, entry]) => ({\n path,\n filesystem: entry.filesystem?.provider ?? entry.config?.type ?? 'unknown',\n })),\n metadata: {\n ...this.metadata,\n },\n };\n }\n\n /**\n * Get instructions describing this E2B sandbox.\n * Used by agents to understand the execution environment.\n */\n getInstructions(opts?: { requestContext?: RequestContext }): string {\n if (this._instructionsOverride === undefined) return this._getDefaultInstructions();\n if (typeof this._instructionsOverride === 'string') return this._instructionsOverride;\n const defaultInstructions = this._getDefaultInstructions();\n return this._instructionsOverride({ defaultInstructions, requestContext: opts?.requestContext });\n }\n\n private _getDefaultInstructions(): string {\n const mountCount = this.mounts.entries.size;\n const mountInfo = mountCount > 0 ? ` ${mountCount} filesystem(s) mounted via FUSE.` : '';\n return `Cloud sandbox.${mountInfo}`;\n }\n\n // ---------------------------------------------------------------------------\n // Mounting\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\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 E2BMountConfig | 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, unmounting to re-mount with new config...`);\n await this.unmount(mountPath);\n }\n this.logger.debug(`${LOG_PREFIX} Config type: ${config.type}`);\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\n // Check if directory exists and is non-empty (would shadow existing files)\n try {\n const checkResult = await this._sandbox.commands.run(\n `[ -d \"${mountPath}\" ] && [ \"$(ls -A \"${mountPath}\" 2>/dev/null)\" ] && echo \"non-empty\" || echo \"ok\"`,\n );\n if (checkResult.stdout.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 mount directory with sudo (for paths outside home dir like /data)\n // Then chown to current user so mount works without issues\n try {\n this.logger.debug(`${LOG_PREFIX} Creating mount directory for ${mountPath}...`);\n const mkdirCommand = `sudo mkdir -p \"${mountPath}\" && sudo chown $(id -u):$(id -g) \"${mountPath}\"`;\n\n this.logger.debug(`${LOG_PREFIX} Running command: ${mkdirCommand}`);\n const mkdirResult = await this._sandbox.commands.run(mkdirCommand);\n\n this.logger.debug(`${LOG_PREFIX} Created mount directory for mount path \"${mountPath}\":`, mkdirResult);\n } catch (mkdirError) {\n this.logger.debug(`${LOG_PREFIX} mkdir error for \"${mountPath}\":`, mkdirError);\n this.mounts.set(mountPath, { filesystem, state: 'error', config, error: String(mkdirError) });\n return { success: false, mountPath, error: String(mkdirError) };\n }\n\n // Create mount context for mount operations\n const mountCtx: MountContext = {\n sandbox: this._sandbox,\n logger: this.logger,\n };\n\n try {\n switch (config.type) {\n case 's3':\n this.logger.debug(`${LOG_PREFIX} Mounting S3 bucket at ${mountPath}...`);\n await mountS3(mountPath, config as E2BS3MountConfig, 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 bucket at ${mountPath}...`);\n await mountGCS(mountPath, config as E2BGCSMountConfig, mountCtx);\n this.logger.debug(`${LOG_PREFIX} Mounted GCS bucket at ${mountPath}`);\n break;\n default:\n this.mounts.set(mountPath, {\n filesystem,\n state: 'unsupported',\n config,\n error: `Unsupported mount type: ${(config as FilesystemMountConfig).type}`,\n });\n return {\n success: false,\n mountPath,\n error: `Unsupported mount type: ${(config as FilesystemMountConfig).type}`,\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: String(error) });\n\n // Clean up the directory we created since mount failed\n try {\n await this._sandbox!.commands.run(`sudo rmdir \"${mountPath}\" 2>/dev/null || true`);\n this.logger.debug(`${LOG_PREFIX} Cleaned up directory after failed mount: ${mountPath}`);\n } catch {\n // Ignore cleanup errors\n }\n\n return { success: false, mountPath, error: String(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\n this.logger.debug(`${LOG_PREFIX} Unmounting ${mountPath}...`);\n\n try {\n // Use fusermount for FUSE mounts, fall back to umount\n const result = await this._sandbox.commands.run(\n `sudo fusermount -u \"${mountPath}\" 2>/dev/null || sudo umount \"${mountPath}\"`,\n );\n if (result.exitCode !== 0) {\n this.logger.debug(`${LOG_PREFIX} Unmount warning: ${result.stderr || result.stdout}`);\n }\n } catch (error) {\n this.logger.debug(`${LOG_PREFIX} Unmount error:`, error);\n // Try lazy unmount as last resort\n await this._sandbox.commands.run(`sudo umount -l \"${mountPath}\" 2>/dev/null || true`);\n }\n\n this.mounts.delete(mountPath);\n\n // Clean up marker file\n const filename = this.mounts.markerFilename(mountPath);\n const markerPath = `/tmp/.mastra-mounts/${filename}`;\n await this._sandbox.commands.run(`rm -f \"${markerPath}\" 2>/dev/null || true`);\n\n // Remove empty mount directory (only if empty, rmdir fails on non-empty)\n // Use sudo since mount directories outside home (like /data) were created with sudo\n const rmdirResult = await this._sandbox.commands.run(`sudo rmdir \"${mountPath}\" 2>&1`);\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.stderr?.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) {\n throw new SandboxNotReadyError(this.id);\n }\n\n this.logger.debug(`${LOG_PREFIX} Reconciling mounts. Expected paths:`, expectedMountPaths);\n\n // Get current FUSE mounts in the sandbox\n const mountsResult = await this._sandbox.commands.run(\n `grep -E 'fuse\\\\.(s3fs|gcsfuse)' /proc/mounts | awk '{print $2}'`,\n );\n const currentMounts = mountsResult.stdout\n .trim()\n .split('\\n')\n .filter(p => p.length > 0);\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 const markersResult = await this._sandbox.commands.run(`ls /tmp/.mastra-mounts/ 2>/dev/null || echo \"\"`);\n const markerFiles = markersResult.stdout\n .trim()\n .split('\\n')\n .filter(f => f.length > 0 && SAFE_MARKER_NAME.test(f));\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 this._sandbox.commands.run(\n `cat \"/tmp/.mastra-mounts/${markerFile}\" 2>/dev/null || echo \"\"`,\n );\n const parsed = this.mounts.parseMarkerContent(markerResult.stdout.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 await this.unmount(stalePath);\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\n // Remove marker file\n await this._sandbox.commands.run(`rm -f \"/tmp/.mastra-mounts/${markerFile}\" 2>/dev/null || true`);\n\n // Try to remove the directory (will fail if not empty or doesn't exist, which is fine)\n await this._sandbox.commands.run(`sudo rmdir \"${mountPath}\" 2>/dev/null || true`);\n }\n } else {\n // Malformed marker file - just delete it\n this.logger.debug(`${LOG_PREFIX} Removing malformed marker file: ${markerFile}`);\n await this._sandbox.commands.run(`rm -f \"/tmp/.mastra-mounts/${markerFile}\" 2>/dev/null || true`);\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 // Deprecated\n // ---------------------------------------------------------------------------\n\n /** @deprecated Use `e2b` instead. */\n get instance(): Sandbox {\n return this.e2b;\n }\n\n /** @deprecated Use `status === 'running'` instead. */\n async isReady(): Promise<boolean> {\n return this.status === 'running' && this._sandbox !== null;\n }\n\n // ---------------------------------------------------------------------------\n // Internal Helpers\n // ---------------------------------------------------------------------------\n\n private generateId(): string {\n return `e2b-sandbox-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;\n }\n\n /**\n * Find an existing sandbox with matching mastra-sandbox-id metadata.\n * Returns the connected sandbox if found, null otherwise.\n */\n private async findExistingSandbox(): Promise<Sandbox | null> {\n try {\n // Query E2B for existing sandbox with our logical ID in metadata\n const paginator = Sandbox.list({\n ...this.connectionOpts,\n query: {\n metadata: { 'mastra-sandbox-id': this.id },\n state: ['running', 'paused'],\n },\n });\n\n const sandboxes = await paginator.nextItems();\n\n this.logger.debug(`${LOG_PREFIX} sandboxes:`, sandboxes);\n\n // Sandbox.list only returns running/paused sandboxes, so no need to filter\n if (sandboxes.length > 0) {\n const existingSandbox = sandboxes[0]!;\n this.logger.debug(\n `${LOG_PREFIX} Found existing sandbox for ${this.id}: ${existingSandbox.sandboxId} (state: ${existingSandbox.state})`,\n );\n return await Sandbox.connect(existingSandbox.sandboxId, this.connectionOpts);\n }\n } catch (e) {\n this.logger.debug(`${LOG_PREFIX} Error querying for existing sandbox:`, e);\n // Continue to create new sandbox\n }\n\n return null;\n }\n\n /**\n * Resolve the template specification to a template ID.\n *\n * - String: Use as-is (template ID)\n * - TemplateBuilder: Build and return the template ID\n * - Function: Apply to base mountable template, then build\n * - undefined: Use default mountable template (cached)\n */\n private async resolveTemplate(): Promise<string> {\n // If already resolved, return cached ID\n if (this._resolvedTemplateId) {\n return this._resolvedTemplateId;\n }\n\n // No template specified - use default mountable template with caching\n if (!this.templateSpec) {\n const { template, id } = createDefaultMountableTemplate();\n\n // Check if template already exists (cached from previous runs)\n const exists = await Template.exists(id, this.connectionOpts);\n if (exists) {\n this.logger.debug(`${LOG_PREFIX} Using cached mountable template: ${id}`);\n this._resolvedTemplateId = id;\n return id;\n }\n\n // Build the template (first time only)\n this.logger.debug(`${LOG_PREFIX} Building default mountable template: ${id}...`);\n const buildResult = await Template.build(template as TemplateClass, id, this.connectionOpts);\n this._resolvedTemplateId = buildResult.templateId;\n this.logger.debug(`${LOG_PREFIX} Template built and cached: ${buildResult.templateId}`);\n return buildResult.templateId;\n }\n\n // String template ID - use directly\n if (typeof this.templateSpec === 'string') {\n this._resolvedTemplateId = this.templateSpec;\n return this.templateSpec;\n }\n\n // TemplateBuilder or function - need to build\n let template: TemplateBuilder;\n let templateName: string;\n\n if (typeof this.templateSpec === 'function') {\n // Apply customization function to base mountable template\n const { template: baseTemplate } = createDefaultMountableTemplate();\n template = this.templateSpec(baseTemplate);\n // Custom templates get unique names since they're modified\n templateName = `mastra-custom-${this.id.replace(/[^a-zA-Z0-9-]/g, '-')}`;\n } else {\n // Use provided TemplateBuilder directly\n template = this.templateSpec;\n templateName = `mastra-${this.id.replace(/[^a-zA-Z0-9-]/g, '-')}`;\n }\n\n // Build the template\n this.logger.debug(`${LOG_PREFIX} Building custom template: ${templateName}...`);\n const buildResult = await Template.build(template as TemplateClass, templateName, this.connectionOpts);\n this._resolvedTemplateId = buildResult.templateId;\n this.logger.debug(`${LOG_PREFIX} Template built: ${buildResult.templateId}`);\n\n return buildResult.templateId;\n }\n\n /**\n * Build the default mountable template (bypasses exists check).\n */\n private async buildDefaultTemplate(): Promise<string> {\n const { template, id } = createDefaultMountableTemplate();\n this.logger.debug(`${LOG_PREFIX} Building default mountable template: ${id}...`);\n const buildResult = await Template.build(template as TemplateClass, id, this.connectionOpts);\n this._resolvedTemplateId = buildResult.templateId;\n this.logger.debug(`${LOG_PREFIX} Template built: ${buildResult.templateId}`);\n return buildResult.templateId;\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 this._sandbox.commands.run('mkdir -p /tmp/.mastra-mounts');\n await this._sandbox.files.write(markerPath, markerContent);\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 if the config matches.\n */\n private async checkExistingMount(\n mountPath: string,\n newConfig: E2BMountConfig,\n ): Promise<'not_mounted' | 'matching' | 'mismatched'> {\n if (!this._sandbox) throw new SandboxNotReadyError(this.id);\n\n // Check if path is a mount point\n const mountCheck = await this._sandbox.commands.run(\n `mountpoint -q \"${mountPath}\" && echo \"mounted\" || echo \"not mounted\"`,\n );\n\n if (mountCheck.stdout.trim() !== 'mounted') {\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\n try {\n const markerResult = await this._sandbox.commands.run(`cat \"${markerPath}\" 2>/dev/null || echo \"\"`);\n const parsed = this.mounts.parseMarkerContent(markerResult.stdout.trim());\n\n if (!parsed) {\n return 'mismatched';\n }\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 } catch {\n // Marker doesn't exist or can't be read - treat as mismatched\n }\n\n return 'mismatched';\n }\n\n /**\n * Check if an error indicates the sandbox itself is dead/gone.\n * Does NOT include code execution timeouts (those are the user's code taking too long).\n * Does NOT include \"port is not open\" - that needs sandbox kill, not reconnect.\n */\n private isSandboxDeadError(error: unknown): boolean {\n if (!error) return false;\n const errorStr = String(error);\n return (\n errorStr.includes('sandbox was not found') ||\n errorStr.includes('Sandbox is probably not running') ||\n errorStr.includes('Sandbox not found') ||\n errorStr.includes('sandbox has been killed')\n );\n }\n\n /**\n * Handle sandbox timeout by clearing the instance and resetting state.\n *\n * Bypasses the normal stop() lifecycle because the sandbox is already dead —\n * we can't unmount filesystems or run cleanup commands. Instead we reset\n * mount states to 'pending' so they get re-mounted when start() runs again.\n */\n private handleSandboxTimeout(): void {\n this._sandbox = null;\n\n // Reset mounted entries to pending so they get re-mounted on restart\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 this.status = 'stopped';\n }\n\n /**\n * Execute an operation with automatic retry if the sandbox is found to be dead.\n *\n * When the E2B sandbox times out or crashes mid-operation, this method\n * resets sandbox state, restarts it, and retries the operation once.\n *\n * @internal Used by E2BProcessManager to handle dead sandboxes during spawn.\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","/**\n * E2B sandbox provider descriptor for MastraEditor.\n *\n * @example\n * ```typescript\n * import { e2bSandboxProvider } from '@mastra/e2b';\n *\n * const editor = new MastraEditor({\n * sandboxes: [e2bSandboxProvider],\n * });\n * ```\n */\nimport type { SandboxProvider } from '@mastra/core/editor';\nimport { E2BSandbox } from './sandbox';\n\n/**\n * Serializable subset of E2BSandboxOptions for editor storage.\n * Non-serializable options (TemplateBuilder callbacks, runtime objects) are excluded.\n */\ninterface E2BProviderConfig {\n template?: string;\n timeout?: number;\n env?: Record<string, string>;\n metadata?: Record<string, unknown>;\n domain?: string;\n apiUrl?: string;\n apiKey?: string;\n accessToken?: string;\n}\n\nexport const e2bSandboxProvider: SandboxProvider<E2BProviderConfig> = {\n id: 'e2b',\n name: 'E2B Sandbox',\n description: 'Cloud sandbox powered by E2B',\n configSchema: {\n type: 'object',\n properties: {\n template: { type: 'string', description: 'Sandbox template ID' },\n timeout: { type: 'number', description: 'Execution timeout in milliseconds', default: 300000 },\n env: {\n type: 'object',\n description: 'Environment variables',\n additionalProperties: { type: 'string' },\n },\n metadata: {\n type: 'object',\n description: 'Custom metadata',\n additionalProperties: true,\n },\n domain: { type: 'string', description: 'Domain for self-hosted E2B' },\n apiUrl: { type: 'string', description: 'API URL for self-hosted E2B' },\n apiKey: { type: 'string', description: 'E2B API key' },\n accessToken: { type: 'string', description: 'E2B access token' },\n },\n },\n createSandbox: config => new E2BSandbox(config),\n};\n"]}
|
package/dist/sandbox/index.d.ts
CHANGED
|
@@ -22,7 +22,7 @@ import { E2BProcessManager } from './process-manager.js';
|
|
|
22
22
|
/**
|
|
23
23
|
* E2B sandbox provider configuration.
|
|
24
24
|
*/
|
|
25
|
-
export interface E2BSandboxOptions extends MastraSandboxOptions {
|
|
25
|
+
export interface E2BSandboxOptions extends Omit<MastraSandboxOptions, 'processes'> {
|
|
26
26
|
/** Unique identifier for this sandbox instance */
|
|
27
27
|
id?: string;
|
|
28
28
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/sandbox/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,KAAK,EACV,WAAW,EACX,mBAAmB,EACnB,WAAW,EAEX,cAAc,EACd,YAAY,EACZ,oBAAoB,EACrB,MAAM,wBAAwB,CAAC;AAEhC;;GAEG;AACH,KAAK,kBAAkB,GAAG,MAAM,GAAG,CAAC,CAAC,IAAI,EAAE;IAAE,mBAAmB,EAAE,MAAM,CAAC;IAAC,cAAc,CAAC,EAAE,cAAc,CAAA;CAAE,KAAK,MAAM,CAAC,CAAC;AACxH,OAAO,EAAE,aAAa,EAAwB,MAAM,wBAAwB,CAAC;AAC7E,OAAO,EAAE,OAAO,EAAY,MAAM,KAAK,CAAC;AAGxC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAGtD,OAAO,EAAE,iBAAiB,EAAE,MAAM,m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OAAO,CAAC,IAAI,CAAC;IAgCxB,OAAO,IAAI,OAAO,CAAC,WAAW,CAAC;IAiBrC;;;OAGG;IACH,eAAe,CAAC,IAAI,CAAC,EAAE;QAAE,cAAc,CAAC,EAAE,cAAc,CAAA;KAAE,GAAG,MAAM;IAOnE,OAAO,CAAC,uBAAuB;IAU/B;;;OAGG;IACG,KAAK,CAAC,UAAU,EAAE,mBAAmB,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC;IA8HrF;;OAEG;IACG,OAAO,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IA0C/C;;;;OAIG;IACG,eAAe,CAAC,kBAAkB,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IA4FlE,qCAAqC;IACrC,IAAI,QAAQ,IAAI,OAAO,CAEtB;IAED,sDAAsD;IAChD,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC;IAQjC,OAAO,CAAC,UAAU;IAIlB;;;OAGG;YACW,mBAAmB;IA+BjC;;;;;;;OAOG;YACW,eAAe;IAyD7B;;OAEG;YACW,oBAAoB;IASlC;;;OAGG;YACW,eAAe;IAiB7B;;OAEG;YACW,kBAAkB;IA2ChC;;;;OAIG;IACH,OAAO,CAAC,kBAAkB;IAW1B;;;;;;OAMG;IACH,OAAO,CAAC,oBAAoB;IAa5B;;;;;;;OAOG;IACG,WAAW,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;CAiBvD"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mastra/e2b",
|
|
3
|
-
"version": "0.1.0",
|
|
3
|
+
"version": "0.1.1-alpha.0",
|
|
4
4
|
"description": "E2B cloud sandbox provider for Mastra workspaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -31,12 +31,12 @@
|
|
|
31
31
|
"tsup": "^8.5.1",
|
|
32
32
|
"typescript": "^5.9.3",
|
|
33
33
|
"vitest": "4.0.18",
|
|
34
|
-
"@internal/lint": "0.0.
|
|
35
|
-
"@internal/
|
|
36
|
-
"@
|
|
34
|
+
"@internal/lint": "0.0.63",
|
|
35
|
+
"@internal/types-builder": "0.0.38",
|
|
36
|
+
"@internal/workspace-test-utils": "0.0.7",
|
|
37
|
+
"@mastra/core": "1.9.0-alpha.0",
|
|
37
38
|
"@mastra/gcs": "0.1.1",
|
|
38
|
-
"@
|
|
39
|
-
"@mastra/s3": "0.2.0"
|
|
39
|
+
"@mastra/s3": "0.2.1-alpha.0"
|
|
40
40
|
},
|
|
41
41
|
"peerDependencies": {
|
|
42
42
|
"@mastra/core": ">=1.7.0-0 <2.0.0-0"
|