@mastra/vercel 1.2.0 → 1.3.0-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 CHANGED
@@ -1,5 +1,44 @@
1
1
  # @mastra/vercel
2
2
 
3
+ ## 1.3.0-alpha.0
4
+
5
+ ### Minor Changes
6
+
7
+ - Added `clone()` support to the sandbox providers. `clone()` constructs an unstarted sibling sandbox that inherits the template's configuration (credentials, image, resources) with per-instance overrides for `id` and `env`, so one configured sandbox can act as a template for a fleet of sandbox clones (for example, one per project). ([#19616](https://github.com/mastra-ai/mastra/pull/19616))
8
+
9
+ ```ts
10
+ const template = new E2BSandbox({ apiKey, template: 'base' });
11
+
12
+ const projectSandbox = template.clone({
13
+ id: 'mc-project-42',
14
+ env: { GITHUB_TOKEN: token },
15
+ idleTimeoutMinutes: 30,
16
+ });
17
+ await projectSandbox.start();
18
+ ```
19
+
20
+ `idleTimeoutMinutes` is a best-effort hint that maps to each provider's native lifetime knob (Railway `idleTimeoutMinutes`, E2B/Modal/Vercel timeout in milliseconds, Daytona `autoStopInterval`, Blaxel TTL duration). Docker and Apple Container ignore it since they have no provider-side idle teardown.
21
+
22
+ - Added networking and bulk file upload support to `VercelSandbox`: ([#19577](https://github.com/mastra-ai/mastra/pull/19577))
23
+ - **Public port URLs**: `sandbox.networking.getPortUrl(port)` returns the public URL for a declared port, enabling preview URLs and deploys with the new `@mastra/deployer-sandbox` package.
24
+ - **Bulk file upload**: `sandbox.writeFiles(files)` uploads multiple files in one call using the Vercel Sandbox SDK.
25
+ - **Named sandbox resume**: when `sandboxName` is set, `start()` now reuses an existing sandbox with that name instead of always creating a new one. Stopping a named sandbox snapshots its filesystem, and the next `start()` resumes it.
26
+ - **Real destroy**: `destroy()` now permanently deletes the sandbox and its snapshots (previously it only stopped it). Use `stop()` for a resumable snapshot-stop.
27
+ - **Resume-less lookups**: `networking.getPortUrl()`, `stop()`, and `destroy()` on a named sandbox now attach to the existing sandbox with `resume: false` when the instance hasn't been started in the current process. Resolving a URL or tearing down a stopped sandbox never wakes it (and never starts billing).
28
+
29
+ ```typescript
30
+ import { VercelSandbox } from '@mastra/vercel';
31
+
32
+ const sandbox = new VercelSandbox({ sandboxName: 'my-preview', ports: [4111] });
33
+ await sandbox.start();
34
+ const url = await sandbox.networking.getPortUrl(4111);
35
+ ```
36
+
37
+ ### Patch Changes
38
+
39
+ - Updated dependencies [[`ec857fc`](https://github.com/mastra-ai/mastra/commit/ec857fc79c264b53b38e16478c789b7177f2ad59), [`e1f2fae`](https://github.com/mastra-ai/mastra/commit/e1f2faebaf048c3d4c2e2c01d293767c195d5794), [`63aa799`](https://github.com/mastra-ai/mastra/commit/63aa799c6b44eacc7806cda6846b7c5bbee06b37), [`73db8db`](https://github.com/mastra-ai/mastra/commit/73db8db90d69ab6153c7942749f624db0d96952d), [`73db8db`](https://github.com/mastra-ai/mastra/commit/73db8db90d69ab6153c7942749f624db0d96952d), [`76b7181`](https://github.com/mastra-ai/mastra/commit/76b71810366e6d90b9d3973149d1c7ba3659ffb9), [`0c0e8d7`](https://github.com/mastra-ai/mastra/commit/0c0e8d7becd4d1445c656b78d5d845f606c1ff9d), [`9f7c67a`](https://github.com/mastra-ai/mastra/commit/9f7c67abeeb52c41c51a9b5edee60b62afe7cd8d), [`3b65e68`](https://github.com/mastra-ai/mastra/commit/3b65e68d7f1c771c7a70eea42d83fefdd28cad88), [`e3868e2`](https://github.com/mastra-ai/mastra/commit/e3868e22babfffd0133771669ca724501c2dd58e)]:
40
+ - @mastra/core@1.52.0-alpha.5
41
+
3
42
  ## 1.2.0
4
43
 
5
44
  ### Minor Changes
package/README.md CHANGED
@@ -77,7 +77,7 @@ const info = await sandbox.getInfo();
77
77
  console.log(info.metadata.domains);
78
78
  ```
79
79
 
80
- Vercel supports up to 8 vCPUs and up to 4 exposed ports per sandbox. Memory is allocated at 2048 MB per vCPU.
80
+ Vercel supports up to 32 vCPUs and up to 15 exposed ports per sandbox. Memory is allocated at 2048 MB per vCPU.
81
81
 
82
82
  ### Streaming command output
83
83
 
package/dist/index.cjs CHANGED
@@ -583,12 +583,29 @@ var VercelSandboxProcessManager = class extends workspace.SandboxProcessManager
583
583
 
584
584
  // src/microvm/index.ts
585
585
  var LOG_PREFIX2 = "[VercelSandbox]";
586
- var VercelSandbox = class extends workspace.MastraSandbox {
586
+ var VercelSandbox = class _VercelSandbox extends workspace.MastraSandbox {
587
587
  id;
588
588
  name = "VercelSandbox";
589
589
  provider = "vercel-sandbox";
590
590
  status = "pending";
591
+ /**
592
+ * Networking capability: public HTTPS URLs for exposed ports.
593
+ * A port must be declared in `ports` at construction time for a URL to exist.
594
+ */
595
+ networking = {
596
+ getPortUrl: async (port) => {
597
+ const sandbox = this._sandbox ?? await this.attach();
598
+ if (!sandbox) return null;
599
+ try {
600
+ return sandbox.domain(port);
601
+ } catch {
602
+ return null;
603
+ }
604
+ }
605
+ };
591
606
  _sandbox = null;
607
+ /** True when `_sandbox` came from a resume-less lookup — `start()` must still resume it. */
608
+ _attachedWithoutResume = false;
592
609
  _createdAt = null;
593
610
  _sandboxName;
594
611
  _token;
@@ -601,6 +618,7 @@ var VercelSandbox = class extends workspace.MastraSandbox {
601
618
  _env;
602
619
  _metadata;
603
620
  _instructionsOverride;
621
+ _constructorOptions;
604
622
  constructor(options = {}) {
605
623
  super({
606
624
  ...options,
@@ -619,6 +637,29 @@ var VercelSandbox = class extends workspace.MastraSandbox {
619
637
  this._env = options.env ?? {};
620
638
  this._metadata = options.metadata ?? {};
621
639
  this._instructionsOverride = options.instructions;
640
+ this._constructorOptions = { ...options };
641
+ }
642
+ /**
643
+ * Construct a sibling `VercelSandbox` that inherits this sandbox's
644
+ * configuration (credentials, runtime, resources, ports, metadata,
645
+ * instructions) with per-instance overrides.
646
+ *
647
+ * Performs no I/O — the sandbox clone provisions a fresh MicroVM on its
648
+ * own `start()` (Vercel sandboxes cannot be reconnected to, so
649
+ * `options.sandboxId` is ignored). Use it when one configured sandbox acts
650
+ * as the template for a fleet of independent sandboxes (e.g. one per
651
+ * project).
652
+ *
653
+ * `options.idleTimeoutMinutes` maps to the Vercel sandbox `timeout` (ms).
654
+ */
655
+ clone(options = {}) {
656
+ const { id: _id, sandboxName: _sandboxName, ...base } = this._constructorOptions;
657
+ return new _VercelSandbox({
658
+ ...base,
659
+ ...options.id !== void 0 && { id: options.id },
660
+ ...options.env !== void 0 && { env: options.env },
661
+ ...options.idleTimeoutMinutes !== void 0 && { timeout: options.idleTimeoutMinutes * 6e4 }
662
+ });
622
663
  }
623
664
  /**
624
665
  * The underlying `@vercel/sandbox` instance.
@@ -633,45 +674,90 @@ var VercelSandbox = class extends workspace.MastraSandbox {
633
674
  // ---------------------------------------------------------------------------
634
675
  // Lifecycle
635
676
  // ---------------------------------------------------------------------------
636
- async start() {
637
- if (this._sandbox) {
638
- return;
677
+ /**
678
+ * Attach to an existing named sandbox WITHOUT resuming it (`resume: false`),
679
+ * so lookups (URL resolution, stop, destroy) never wake a stopped sandbox
680
+ * and start billing. Returns null when unnamed or when no sandbox with this
681
+ * name exists.
682
+ */
683
+ async attach() {
684
+ if (this._sandbox) return this._sandbox;
685
+ if (!this._sandboxName) return null;
686
+ try {
687
+ this._sandbox = await sandbox.Sandbox.get({
688
+ name: this._sandboxName,
689
+ resume: false,
690
+ ...this.credentialParams()
691
+ });
692
+ this._attachedWithoutResume = true;
693
+ return this._sandbox;
694
+ } catch {
695
+ return null;
639
696
  }
640
- const hasExplicitCreds = Boolean(this._token || this._teamId || this._projectId);
641
- if (hasExplicitCreds && !(this._token && this._teamId && this._projectId)) {
697
+ }
698
+ /**
699
+ * The token is the credential: when provided, the SDK requires teamId and
700
+ * projectId alongside it. Without a token the SDK authenticates via the
701
+ * `VERCEL_OIDC_TOKEN`; a stray teamId/projectId (for example, an exported
702
+ * `VERCEL_TEAM_ID` in the shell) must not break OIDC auth, so it is ignored.
703
+ */
704
+ credentialParams() {
705
+ if (!this._token) return {};
706
+ if (!(this._teamId && this._projectId)) {
642
707
  throw new Error(
643
- `${LOG_PREFIX2} Incomplete credentials. Provide token, teamId, and projectId together (or the VERCEL_TOKEN, VERCEL_TEAM_ID, and VERCEL_PROJECT_ID env vars), or omit all three to use the VERCEL_OIDC_TOKEN.`
708
+ `${LOG_PREFIX2} Incomplete credentials. Provide token, teamId, and projectId together (or the VERCEL_TOKEN, VERCEL_TEAM_ID, and VERCEL_PROJECT_ID env vars), or omit the token to use the VERCEL_OIDC_TOKEN.`
644
709
  );
645
710
  }
711
+ return { token: this._token, teamId: this._teamId, projectId: this._projectId };
712
+ }
713
+ async start() {
714
+ if (this._sandbox && !this._attachedWithoutResume) {
715
+ return;
716
+ }
646
717
  this.logger.debug(`${LOG_PREFIX2} Creating sandbox...`, { runtime: this._runtime, timeout: this._timeout });
647
- this._sandbox = await sandbox.Sandbox.create({
648
- ...this._sandboxName ? { name: this._sandboxName } : {},
718
+ const params = {
649
719
  runtime: this._runtime,
650
720
  timeout: this._timeout,
651
721
  ...this._vcpus ? { resources: { vcpus: this._vcpus } } : {},
652
722
  ...this._ports?.length ? { ports: this._ports } : {},
653
723
  ...Object.keys(this._env).length ? { env: this._env } : {},
654
- ...hasExplicitCreds ? { token: this._token, teamId: this._teamId, projectId: this._projectId } : {}
655
- });
724
+ ...this.credentialParams()
725
+ };
726
+ this._sandbox = this._sandboxName ? await sandbox.Sandbox.getOrCreate({ ...params, name: this._sandboxName }) : await sandbox.Sandbox.create(params);
727
+ this._attachedWithoutResume = false;
656
728
  this._createdAt = /* @__PURE__ */ new Date();
657
729
  this.logger.debug(`${LOG_PREFIX2} Sandbox ready: ${this._sandbox.name}`);
658
730
  }
731
+ /** Snapshot-stop: the filesystem persists and a named sandbox resumes on the next `start()`. */
659
732
  async stop() {
660
- await this._teardown();
733
+ const sandbox = this._sandbox ?? await this.attach();
734
+ if (!sandbox) {
735
+ return;
736
+ }
737
+ await sandbox.stop();
738
+ this._sandbox = null;
739
+ this._attachedWithoutResume = false;
661
740
  }
741
+ /** Permanently delete the sandbox and its snapshots. */
662
742
  async destroy() {
663
- await this._teardown();
664
- }
665
- async _teardown() {
666
- if (!this._sandbox) {
743
+ const sandbox = this._sandbox ?? await this.attach();
744
+ if (!sandbox) {
667
745
  return;
668
746
  }
669
- try {
670
- await this._sandbox.stop();
671
- } catch (error) {
672
- this.logger.warn(`${LOG_PREFIX2} Error stopping sandbox:`, error);
673
- }
747
+ await sandbox.delete();
674
748
  this._sandbox = null;
749
+ this._attachedWithoutResume = false;
750
+ }
751
+ // ---------------------------------------------------------------------------
752
+ // File Upload
753
+ // ---------------------------------------------------------------------------
754
+ /**
755
+ * Bulk-write files into the sandbox filesystem via the SDK's native upload.
756
+ * Relative paths resolve against /vercel/sandbox.
757
+ */
758
+ async writeFiles(files) {
759
+ await this.ensureRunning();
760
+ await this.sandbox.writeFiles(files.map((f) => ({ path: f.path, content: f.content })));
675
761
  }
676
762
  // ---------------------------------------------------------------------------
677
763
  // Command Execution
@@ -775,7 +861,7 @@ var VercelSandbox = class extends workspace.MastraSandbox {
775
861
  return [
776
862
  "Vercel Sandbox: an ephemeral Firecracker MicroVM running Amazon Linux 2023.",
777
863
  `- Runtime: ${this._runtime}. Working directory defaults to /vercel/sandbox.`,
778
- "- Persistent filesystem within the session; state is lost when the sandbox stops.",
864
+ this._sandboxName ? "- Persistent filesystem: stopping snapshots the filesystem and the named sandbox resumes it on the next start. Processes do not survive a stop." : "- Persistent filesystem within the session; state is lost when the sandbox stops.",
779
865
  "- Runs as the vercel-sandbox user with sudo access (install packages via dnf).",
780
866
  `- The sandbox auto-terminates after ${Math.round(this._timeout / 1e3)} seconds.`,
781
867
  ...this._ports?.length ? [`- Exposed ports: ${this._ports.join(", ")} (reachable via public HTTPS domains).`] : [],
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/executor/index.ts","../src/serverless/index.ts","../src/serverless-provider.ts","../src/microvm/process-manager.ts","../src/microvm/index.ts","../src/microvm-provider.ts"],"names":["MastraSandbox","Sandbo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AA;AAAA,QACb,oBAAA,EAAsB,EAAE,IAAA,EAAM,QAAA;AAAS;AACzC;AACF,GACF;AAAA,EACA,aAAA,EAAe,CAAA,MAAA,KACb,IAAI,aAAA,CAAc;AAAA,IAChB,OAAO,MAAA,CAAO,KAAA;AAAA,IACd,QAAQ,MAAA,CAAO,MAAA;AAAA,IACf,WAAW,MAAA,CAAO,SAAA;AAAA,IAClB,SAAS,MAAA,CAAO,OAAA;AAAA,IAChB,SAAS,MAAA,CAAO,OAAA;AAAA,IAChB,GAAI,MAAA,CAAO,KAAA,GAAQ,EAAE,SAAA,EAAW,EAAE,KAAA,EAAO,MAAA,CAAO,KAAA,EAAM,EAAE,GAAI,EAAC;AAAA,IAC7D,OAAO,MAAA,CAAO,KAAA;AAAA,IACd,KAAK,MAAA,CAAO;AAAA,GACb;AACL","file":"index.cjs","sourcesContent":["/**\n * Executor function source code deployed to Vercel as a serverless function.\n *\n * Returns a string because it's sent as inline file content via\n * the Vercel Deployments API — no separate build step needed.\n *\n * The secret and user env vars are embedded as constants in the source\n * because the Vercel Deployments API does not support setting env vars\n * directly — they must be configured via vercel.json or project settings.\n */\nexport function getExecutorSource(secret: string, env: Record<string, string>): string {\n const envEntries = Object.entries(env)\n .map(([k, v]) => ` ${JSON.stringify(k)}: ${JSON.stringify(v)}`)\n .join(',\\n');\n\n return `\nconst { execFileSync } = require('child_process');\n\nconst SANDBOX_SECRET = ${JSON.stringify(secret)};\nconst SANDBOX_ENV = {\n${envEntries}\n};\n\nmodule.exports = async (req, res) => {\n // Auth check\n const authHeader = req.headers['authorization'] || '';\n if (!SANDBOX_SECRET || authHeader !== 'Bearer ' + SANDBOX_SECRET) {\n return res.status(401).json({ error: 'Unauthorized' });\n }\n\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' });\n }\n\n const { command, args = [], env = {}, cwd, timeout = 55000 } = req.body || {};\n\n if (!command) {\n return res.status(400).json({ error: 'Missing required field: command' });\n }\n\n const execCwd = cwd || '/tmp';\n const execEnv = { ...process.env, ...SANDBOX_ENV, ...env };\n\n // When args is empty the caller sent a full shell command string\n // (e.g. \"echo hello\" or \"ls -la | grep foo\"). Run it through\n // /bin/sh so builtins and pipes work. When args is non-empty the\n // caller split the command properly — use execFileSync to avoid\n // shell injection.\n const useShell = !args || args.length === 0;\n const execCommand = useShell ? '/bin/sh' : command;\n const execArgs = useShell ? ['-c', command] : args;\n\n const startTime = Date.now();\n let timedOut = false;\n\n try {\n const stdout = execFileSync(execCommand, execArgs, {\n cwd: execCwd,\n env: execEnv,\n timeout,\n maxBuffer: 10 * 1024 * 1024,\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n\n return res.status(200).json({\n success: true,\n exitCode: 0,\n stdout: stdout || '',\n stderr: '',\n executionTimeMs: Date.now() - startTime,\n timedOut: false,\n });\n } catch (error) {\n timedOut = error.killed || false;\n\n return res.status(200).json({\n success: false,\n exitCode: error.status != null ? error.status : 1,\n stdout: error.stdout || '',\n stderr: error.stderr || '',\n executionTimeMs: Date.now() - startTime,\n timedOut,\n });\n }\n};\n`;\n}\n","/**\n * Vercel Serverless Sandbox Provider\n *\n * Deploys code as Vercel serverless functions and executes commands\n * via HTTP invocation. Stateless — no persistent filesystem, no\n * interactive shell, no long-running processes.\n *\n * @see https://vercel.com/docs/rest-api\n */\n\nimport type { RequestContext } from '@mastra/core/di';\nimport type {\n SandboxInfo,\n CommandResult,\n ExecuteCommandOptions,\n MastraSandboxOptions,\n ProviderStatus,\n InstructionsOption,\n} from '@mastra/core/workspace';\nimport { MastraSandbox, SandboxNotReadyError } from '@mastra/core/workspace';\nimport { getExecutorSource } from '../executor';\n\nconst LOG_PREFIX = '[VercelServerlessSandbox]';\n\nconst VERCEL_API_BASE = 'https://api.vercel.com';\n\n/**\n * Shell-quote an argument for safe interpolation into a shell command string.\n * Mirrors the implementation in packages/core/src/workspace/sandbox/utils.ts\n * which is not publicly exported.\n */\nfunction shellQuote(arg: string): string {\n if (/^[a-zA-Z0-9._\\-\\/=:@]+$/.test(arg)) return arg;\n return `'${arg.replace(/'/g, \"'\\\\''\")}'`;\n}\n\n// =============================================================================\n// Options\n// =============================================================================\n\nexport interface VercelServerlessSandboxOptions extends Omit<MastraSandboxOptions, 'processes'> {\n /** Vercel API token. Falls back to VERCEL_TOKEN env var. */\n token?: string;\n /** Vercel team ID for team-scoped deployments. */\n teamId?: string;\n /** Existing Vercel project name. Auto-generated if omitted. */\n projectName?: string;\n /** Deployment regions. @default ['iad1'] */\n regions?: string[];\n /** Function max duration in seconds. @default 60 */\n maxDuration?: number;\n /** Function memory in MB. @default 1024 */\n memory?: number;\n /** Environment variables baked into the deployed function. */\n env?: Record<string, string>;\n /** Per-invocation command timeout in ms. @default 55000 */\n commandTimeout?: number;\n /**\n * Custom instructions that override the default instructions\n * returned by `getInstructions()`.\n */\n instructions?: InstructionsOption;\n}\n\n// =============================================================================\n// Implementation\n// =============================================================================\n\nexport class VercelServerlessSandbox extends MastraSandbox {\n readonly id: string;\n readonly name = 'VercelServerlessSandbox';\n readonly provider = 'vercel-serverless';\n status: ProviderStatus = 'pending';\n\n private readonly _token: string;\n private readonly _teamId?: string;\n private readonly _projectName?: string;\n private readonly _regions: string[];\n private readonly _maxDuration: number;\n private readonly _memory: number;\n private readonly _env: Record<string, string>;\n private readonly _commandTimeout: number;\n private readonly _instructionsOverride?: InstructionsOption;\n private readonly _secret: string;\n\n private _deploymentUrl: string | null = null;\n private _deploymentId: string | null = null;\n private _protectionBypass: string | null = null;\n private _createdAt: Date | null = null;\n\n constructor(options: VercelServerlessSandboxOptions = {}) {\n super({ name: 'VercelServerlessSandbox' });\n\n this.id = `vercel-serverless-sandbox-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;\n this._token = options.token || process.env.VERCEL_TOKEN || '';\n this._teamId = options.teamId;\n this._projectName = options.projectName;\n this._regions = options.regions ?? ['iad1'];\n this._maxDuration = options.maxDuration ?? 60;\n this._memory = options.memory ?? 1024;\n this._env = options.env ?? {};\n this._commandTimeout = options.commandTimeout ?? 55_000;\n this._instructionsOverride = options.instructions;\n this._secret = crypto.randomUUID();\n }\n\n // ---------------------------------------------------------------------------\n // Lifecycle\n // ---------------------------------------------------------------------------\n\n async start(): Promise<void> {\n if (this._deploymentUrl) {\n return;\n }\n\n if (!this._token) {\n throw new Error(`${LOG_PREFIX} Missing Vercel API token. Set VERCEL_TOKEN env var or pass token option.`);\n }\n\n // Clean up any stale deployment from a previous stop() → start() cycle.\n // Without this, the old _deploymentId is overwritten and that deployment leaks.\n if (this._deploymentId) {\n this.logger.debug(`${LOG_PREFIX} Cleaning up stale deployment ${this._deploymentId} before restarting...`);\n try {\n const resp = await this._vercelFetch(`/v13/deployments/${this._deploymentId}`, { method: 'DELETE' });\n if (!resp.ok && resp.status !== 404) {\n this.logger.warn(`${LOG_PREFIX} Failed to delete stale deployment: ${resp.status}`);\n }\n } catch (error) {\n this.logger.warn(`${LOG_PREFIX} Error deleting stale deployment:`, error);\n }\n this._deploymentId = null;\n }\n\n this.logger.debug(`${LOG_PREFIX} Deploying executor function...`);\n\n const vercelJson = JSON.stringify({\n functions: {\n 'api/execute.js': {\n memory: this._memory,\n maxDuration: this._maxDuration,\n },\n },\n regions: this._regions,\n });\n\n // Create the deployment\n const deploymentBody: Record<string, unknown> = {\n name: this._projectName ?? `mastra-sandbox-${this.id}`,\n files: [\n {\n file: 'api/execute.js',\n data: getExecutorSource(this._secret, this._env),\n },\n {\n file: 'vercel.json',\n data: vercelJson,\n },\n ],\n projectSettings: {\n framework: null,\n },\n target: 'production',\n };\n\n const createResp = await this._vercelFetch('/v13/deployments', {\n method: 'POST',\n body: JSON.stringify(deploymentBody),\n });\n\n if (!createResp.ok) {\n const errorBody = await createResp.text();\n throw new Error(`${LOG_PREFIX} Failed to create deployment: ${createResp.status} ${errorBody}`);\n }\n\n const deployment = (await createResp.json()) as { id: string; url: string; readyState: string; projectId?: string };\n this._deploymentId = deployment.id;\n\n this.logger.debug(`${LOG_PREFIX} Deployment created: ${deployment.id}, polling for READY...`);\n\n // Poll until ready\n const maxWaitMs = 120_000;\n const pollIntervalMs = 3_000;\n const deadline = Date.now() + maxWaitMs;\n\n while (Date.now() < deadline) {\n const statusResp = await this._vercelFetch(`/v13/deployments/${deployment.id}`);\n if (!statusResp.ok) {\n throw new Error(`${LOG_PREFIX} Failed to check deployment status: ${statusResp.status}`);\n }\n\n const statusBody = (await statusResp.json()) as { readyState: string; url: string };\n\n if (statusBody.readyState === 'READY') {\n this._deploymentUrl = `https://${statusBody.url}`;\n this._createdAt = new Date();\n this.logger.debug(`${LOG_PREFIX} Deployment ready: ${this._deploymentUrl}`);\n\n // Acquire a deployment protection bypass token.\n // Pro/Enterprise teams have Deployment Protection enabled by default,\n // which intercepts HTTP requests with an SSO login page before they\n // reach the serverless function. The bypass token lets us skip that.\n if (deployment.projectId) {\n try {\n this._protectionBypass = await this._acquireProtectionBypass(deployment.projectId);\n } catch {\n // Non-fatal — if the project has no deployment protection, this is unnecessary.\n }\n }\n\n // Warm-up ping\n try {\n await fetch(`${this._deploymentUrl}/api/execute`, {\n method: 'POST',\n headers: this._executorHeaders(),\n body: JSON.stringify({ command: 'echo', args: ['warm'] }),\n });\n } catch {\n // Warm-up failure is non-fatal\n }\n\n return;\n }\n\n if (statusBody.readyState === 'ERROR' || statusBody.readyState === 'CANCELED') {\n throw new Error(`${LOG_PREFIX} Deployment failed with state: ${statusBody.readyState}`);\n }\n\n await new Promise(resolve => setTimeout(resolve, pollIntervalMs));\n }\n\n throw new Error(`${LOG_PREFIX} Deployment timed out after ${maxWaitMs}ms`);\n }\n\n async stop(): Promise<void> {\n // Only clear the URL (disconnects from the deployment) but keep\n // _deploymentId so a subsequent destroy() can still clean up the\n // cloud resource. Clearing both would make destroy() a no-op and\n // leak the deployment.\n this._deploymentUrl = null;\n }\n\n async destroy(): Promise<void> {\n if (this._deploymentId) {\n try {\n const resp = await this._vercelFetch(`/v13/deployments/${this._deploymentId}`, {\n method: 'DELETE',\n });\n if (!resp.ok) {\n // 404 means the deployment is already gone — that's fine.\n // Other status codes indicate infrastructure issues (auth, network)\n // and should be surfaced more visibly.\n if (resp.status === 404) {\n this.logger.debug(`${LOG_PREFIX} Deployment already deleted (404)`);\n } else {\n this.logger.warn(`${LOG_PREFIX} Failed to delete deployment: ${resp.status}`);\n }\n }\n } catch (error) {\n // Network-level failure — warn rather than debug so it's visible\n this.logger.warn(`${LOG_PREFIX} Error deleting deployment:`, error);\n }\n this._deploymentId = null;\n }\n this._deploymentUrl = null;\n this._protectionBypass = null;\n }\n\n // ---------------------------------------------------------------------------\n // Command Execution\n // ---------------------------------------------------------------------------\n\n async executeCommand(command: string, args?: string[], options?: ExecuteCommandOptions): Promise<CommandResult> {\n await this.ensureRunning();\n\n if (!this._deploymentUrl) {\n throw new SandboxNotReadyError(this.id);\n }\n\n const fullCommand = args?.length ? `${command} ${args.map(a => shellQuote(a)).join(' ')}` : command;\n this.logger.debug(`${LOG_PREFIX} Executing: ${fullCommand}`);\n\n const body = {\n command,\n args: args ?? [],\n env: options?.env ?? {},\n cwd: options?.cwd ?? '/tmp',\n timeout: options?.timeout ?? this._commandTimeout,\n };\n\n const maxRetries = 2;\n let lastError: Error | null = null;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n const resp = await fetch(`${this._deploymentUrl}/api/execute`, {\n method: 'POST',\n headers: this._executorHeaders(),\n body: JSON.stringify(body),\n signal: options?.abortSignal,\n });\n\n // Retry on transient errors\n if ((resp.status === 429 || resp.status === 502 || resp.status === 503) && attempt < maxRetries) {\n this.logger.debug(`${LOG_PREFIX} Retryable status ${resp.status}, attempt ${attempt + 1}/${maxRetries}`);\n await new Promise(resolve => setTimeout(resolve, 1000 * (attempt + 1)));\n continue;\n }\n\n // Gateway timeout → timedOut\n if (resp.status === 504) {\n return {\n command: fullCommand,\n args,\n success: false,\n exitCode: 124,\n stdout: '',\n stderr: 'Function execution timed out (504 Gateway Timeout)',\n executionTimeMs: options?.timeout ?? this._commandTimeout,\n timedOut: true,\n };\n }\n\n if (!resp.ok) {\n const errorText = await resp.text();\n throw new Error(`${LOG_PREFIX} Execute failed: ${resp.status} ${errorText}`);\n }\n\n const result = (await resp.json()) as {\n success: boolean;\n exitCode: number;\n stdout: string;\n stderr: string;\n executionTimeMs: number;\n timedOut: boolean;\n };\n\n // Stream callbacks\n if (options?.onStdout && result.stdout) {\n options.onStdout(result.stdout);\n }\n if (options?.onStderr && result.stderr) {\n options.onStderr(result.stderr);\n }\n\n return {\n command: fullCommand,\n args,\n success: result.success,\n exitCode: result.exitCode,\n stdout: result.stdout,\n stderr: result.stderr,\n executionTimeMs: result.executionTimeMs,\n timedOut: result.timedOut,\n };\n } catch (error) {\n if (error instanceof DOMException && error.name === 'AbortError') {\n throw error;\n }\n lastError = error as Error;\n if (attempt < maxRetries) {\n this.logger.debug(`${LOG_PREFIX} Request error, attempt ${attempt + 1}/${maxRetries}:`, error);\n await new Promise(resolve => setTimeout(resolve, 1000 * (attempt + 1)));\n continue;\n }\n }\n }\n\n throw lastError ?? new Error(`${LOG_PREFIX} executeCommand failed after retries`);\n }\n\n // ---------------------------------------------------------------------------\n // Info & Instructions\n // ---------------------------------------------------------------------------\n\n // Matches the resolveInstructions pattern in packages/core/src/workspace/utils.ts\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 return [\n 'Vercel serverless sandbox.',\n 'Limitations:',\n '- Stateless: no persistent filesystem between invocations.',\n '- No interactive shell or streaming stdin.',\n '- No long-running or background processes.',\n `- Maximum execution time: ${this._maxDuration} seconds.`,\n '- Only /tmp is writable (ephemeral, cleared between invocations).',\n '- Shell commands (pipes, builtins) are supported via /bin/sh -c.',\n ].join('\\n');\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 metadata: {\n deploymentId: this._deploymentId,\n deploymentUrl: this._deploymentUrl,\n regions: this._regions,\n maxDuration: this._maxDuration,\n memory: this._memory,\n },\n };\n }\n\n // ---------------------------------------------------------------------------\n // Private Helpers\n // ---------------------------------------------------------------------------\n\n /**\n * Fetch an existing protection bypass token for the project, or create one\n * if none exists. Returns the token string, or null if acquisition fails.\n */\n private async _acquireProtectionBypass(projectId: string): Promise<string | null> {\n // 1. Check if the project already has a bypass token.\n const projResp = await this._vercelFetch(`/v9/projects/${projectId}`);\n if (projResp.ok) {\n const project = (await projResp.json()) as {\n protectionBypass?: Record<string, unknown>;\n };\n const existing = project.protectionBypass ? Object.keys(project.protectionBypass)[0] : undefined;\n if (existing) {\n this.logger.debug(`${LOG_PREFIX} Using existing protection bypass token`);\n return existing;\n }\n }\n\n // 2. No token exists — create one via the dedicated endpoint.\n this.logger.debug(`${LOG_PREFIX} Creating protection bypass token...`);\n const createResp = await this._vercelFetch(`/v1/projects/${projectId}/protection-bypass`, {\n method: 'PATCH',\n body: JSON.stringify({}),\n });\n if (createResp.ok) {\n const result = (await createResp.json()) as {\n protectionBypass?: Record<string, unknown>;\n };\n const created = result.protectionBypass ? Object.keys(result.protectionBypass)[0] : undefined;\n if (created) {\n this.logger.debug(`${LOG_PREFIX} Protection bypass token created`);\n return created;\n }\n }\n\n this.logger.debug(`${LOG_PREFIX} Could not acquire protection bypass token (project may not require it)`);\n return null;\n }\n\n private _executorHeaders(): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this._secret}`,\n };\n if (this._protectionBypass) {\n headers['x-vercel-protection-bypass'] = this._protectionBypass;\n }\n return headers;\n }\n\n private async _vercelFetch(path: string, options: RequestInit = {}): Promise<Response> {\n const url = new URL(path, VERCEL_API_BASE);\n if (this._teamId) {\n url.searchParams.set('teamId', this._teamId);\n }\n\n return fetch(url.toString(), {\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this._token}`,\n ...((options.headers as Record<string, string>) ?? {}),\n },\n });\n }\n}\n","/**\n * Vercel serverless sandbox provider descriptor for MastraEditor.\n *\n * @example\n * ```typescript\n * import { vercelServerlessSandboxProvider } from '@mastra/vercel';\n *\n * const editor = new MastraEditor({\n * sandboxes: [vercelServerlessSandboxProvider],\n * });\n * ```\n */\nimport type { SandboxProvider } from '@mastra/core/editor';\nimport { VercelServerlessSandbox } from './serverless';\n\n/**\n * Serializable subset of VercelServerlessSandboxOptions for editor storage.\n */\ninterface VercelProviderConfig {\n token?: string;\n teamId?: string;\n projectName?: string;\n regions?: string[];\n maxDuration?: number;\n memory?: number;\n env?: Record<string, string>;\n commandTimeout?: number;\n}\n\nexport const vercelServerlessSandboxProvider: SandboxProvider<VercelProviderConfig> = {\n id: 'vercel-serverless',\n name: 'Vercel Sandbox (Serverless)',\n description: 'Serverless sandbox powered by Vercel Functions',\n configSchema: {\n type: 'object',\n properties: {\n token: { type: 'string', description: 'Vercel API token' },\n teamId: { type: 'string', description: 'Vercel team ID' },\n projectName: { type: 'string', description: 'Existing Vercel project name' },\n regions: {\n type: 'array',\n description: 'Deployment regions',\n items: { type: 'string' },\n default: ['iad1'],\n },\n maxDuration: { type: 'number', description: 'Function max duration in seconds', default: 60 },\n memory: { type: 'number', description: 'Function memory in MB', default: 1024 },\n env: {\n type: 'object',\n description: 'Environment variables',\n additionalProperties: { type: 'string' },\n },\n commandTimeout: { type: 'number', description: 'Per-invocation timeout in ms', default: 55000 },\n },\n },\n createSandbox: config => new VercelServerlessSandbox(config),\n};\n","/**\n * Vercel Sandbox (MicroVM) Process Manager\n *\n * Implements SandboxProcessManager for the `@vercel/sandbox` SDK. Each spawn()\n * starts a detached command via `sandbox.runCommand({ detached: true })` and\n * streams its output through the command's async `logs()` iterator.\n *\n * The Vercel Sandbox SDK does not expose a stdin channel for running commands,\n * so `sendStdin()` throws a clear \"not supported\" error.\n */\n\nimport { ProcessHandle, SandboxProcessManager } from '@mastra/core/workspace';\nimport type { CommandResult, ProcessInfo, SpawnProcessOptions } from '@mastra/core/workspace';\nimport type { Command } from '@vercel/sandbox';\nimport type { VercelSandbox } from './index';\n\n// =============================================================================\n// Process Handle\n// =============================================================================\n\n/**\n * Wraps a detached Vercel Sandbox {@link Command} to conform to Mastra's\n * ProcessHandle. Not exported — internal to this module.\n */\nclass VercelSandboxProcessHandle extends ProcessHandle {\n readonly pid: string;\n\n private readonly _command: Command;\n private readonly _startTime: number;\n private readonly _timeout?: number;\n\n private _exitCode: number | undefined;\n private _waitPromise: Promise<CommandResult> | null = null;\n private _streamingPromise: Promise<void> | null = null;\n private _killed = false;\n\n constructor(command: Command, startTime: number, options?: SpawnProcessOptions) {\n super(options);\n this.pid = command.cmdId;\n this._command = command;\n this._startTime = startTime;\n this._timeout = options?.timeout;\n }\n\n get exitCode(): number | undefined {\n return this._exitCode;\n }\n\n /** @internal Set by the process manager after streaming starts. */\n set streamingPromise(p: Promise<void>) {\n this._streamingPromise = p;\n }\n\n async wait(): Promise<CommandResult> {\n if (!this._waitPromise) {\n this._waitPromise = this._doWait();\n }\n return this._waitPromise;\n }\n\n private async _doWait(): Promise<CommandResult> {\n const finishedPromise = this._command\n .wait()\n .then(finished => {\n if (this._exitCode === undefined) this._exitCode = finished.exitCode;\n })\n .catch(() => {\n if (this._exitCode === undefined) this._exitCode = 1;\n });\n\n if (this._timeout) {\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n const timeoutPromise = new Promise<'timeout'>(resolve => {\n timeoutId = setTimeout(() => resolve('timeout'), this._timeout);\n });\n\n const outcome = await Promise.race([finishedPromise.then(() => 'done' as const), timeoutPromise]);\n clearTimeout(timeoutId);\n\n if (outcome === 'timeout') {\n await this.kill();\n this._exitCode = 124;\n await this._streamingPromise?.catch(() => {});\n return {\n success: false,\n exitCode: 124,\n stdout: this.stdout,\n stderr: this.stderr || `Command timed out after ${this._timeout}ms`,\n executionTimeMs: Date.now() - this._startTime,\n killed: true,\n timedOut: true,\n };\n }\n } else {\n await finishedPromise;\n }\n\n // Drain any remaining streamed output before reporting the result.\n await this._streamingPromise?.catch(() => {});\n\n if (this._killed) {\n return {\n success: false,\n exitCode: this._exitCode ?? 137,\n stdout: this.stdout,\n stderr: this.stderr,\n executionTimeMs: Date.now() - this._startTime,\n killed: true,\n timedOut: false,\n };\n }\n\n return {\n success: this._exitCode === 0,\n exitCode: this._exitCode ?? 1,\n stdout: this.stdout,\n stderr: this.stderr,\n executionTimeMs: Date.now() - this._startTime,\n };\n }\n\n async kill(): Promise<boolean> {\n if (this._exitCode !== undefined && !this._killed) return false;\n this._killed = true;\n if (this._exitCode === undefined) this._exitCode = 137; // SIGKILL\n try {\n await this._command.kill();\n } catch {\n // Command may already be gone.\n }\n return true;\n }\n\n async sendStdin(_data: string): Promise<void> {\n throw new Error('VercelSandbox does not support sending stdin to running processes.');\n }\n}\n\n// =============================================================================\n// Process Manager\n// =============================================================================\n\nexport interface VercelSandboxProcessManagerOptions {\n env?: Record<string, string | undefined>;\n}\n\n/**\n * Vercel Sandbox implementation of SandboxProcessManager. Uses one detached\n * `runCommand` per spawned process.\n */\nexport class VercelSandboxProcessManager extends SandboxProcessManager<VercelSandbox> {\n async spawn(command: string, options: SpawnProcessOptions = {}): Promise<ProcessHandle> {\n const mergedEnv = { ...this.env, ...options.env };\n const env = Object.fromEntries(\n Object.entries(mergedEnv).filter((entry): entry is [string, string] => entry[1] !== undefined),\n );\n\n // The workspace passes a full command string; run it through a shell so\n // pipes, redirects, and builtins behave as expected.\n const cmd = await this.sandbox.sandbox.runCommand({\n cmd: 'sh',\n args: ['-c', command],\n ...(options.cwd ? { cwd: options.cwd } : {}),\n ...(Object.keys(env).length ? { env } : {}),\n detached: true,\n });\n\n const handle = new VercelSandboxProcessHandle(cmd, Date.now(), options);\n\n const streamingPromise = (async () => {\n for await (const log of cmd.logs()) {\n if (log.stream === 'stdout') handle.emitStdout(log.data);\n else handle.emitStderr(log.data);\n }\n })().catch(() => {\n // Stream ends when the command exits or is killed — swallow the error.\n });\n\n handle.streamingPromise = streamingPromise;\n\n this._tracked.set(handle.pid, handle);\n return handle;\n }\n\n async list(): Promise<ProcessInfo[]> {\n const result: ProcessInfo[] = [];\n for (const [pid, handle] of this._tracked) {\n result.push({\n pid,\n command: handle.command,\n running: handle.exitCode === undefined,\n exitCode: handle.exitCode,\n });\n }\n return result;\n }\n}\n","/**\n * Vercel Sandbox (MicroVM) Provider\n *\n * Wraps the official `@vercel/sandbox` SDK, which provisions ephemeral\n * Firecracker MicroVMs (Amazon Linux 2023) with a persistent in-session\n * filesystem, command execution, background processes, and exposed ports.\n *\n * This is distinct from the `VercelServerlessSandbox` provider in this package, which\n * runs commands as Vercel serverless Functions and is stateless.\n *\n * @see https://vercel.com/docs/vercel-sandbox\n */\n\nimport type { RequestContext } from '@mastra/core/di';\nimport type {\n CommandResult,\n ExecuteCommandOptions,\n InstructionsOption,\n MastraSandboxOptions,\n ProviderStatus,\n SandboxInfo,\n} from '@mastra/core/workspace';\nimport { MastraSandbox, SandboxNotReadyError } from '@mastra/core/workspace';\nimport { Sandbox } from '@vercel/sandbox';\nimport { VercelSandboxProcessManager } from './process-manager';\n\nconst LOG_PREFIX = '[VercelSandbox]';\n\n/** Vercel Sandbox runtimes (default `node24`). */\nexport type VercelSandboxRuntime = 'node24' | 'node22' | 'node26' | 'python3.13';\n\n// =============================================================================\n// Options\n// =============================================================================\n\n/**\n * Vercel Sandbox (MicroVM) provider configuration.\n *\n * Authentication: the SDK uses the `VERCEL_OIDC_TOKEN` environment variable\n * automatically when available. To authenticate from an environment without\n * OIDC, supply `token`, `teamId`, and `projectId` together (falling back to\n * the `VERCEL_TOKEN`, `VERCEL_TEAM_ID`, and `VERCEL_PROJECT_ID` env vars).\n */\nexport interface VercelSandboxOptions extends Omit<MastraSandboxOptions, 'processes'> {\n /** Unique identifier for this sandbox instance. */\n id?: string;\n /** Optional sandbox name passed to the Vercel API. Auto-generated if omitted. */\n sandboxName?: string;\n /** Vercel API token. Falls back to the `VERCEL_TOKEN` env var. */\n token?: string;\n /** Vercel team ID. Falls back to the `VERCEL_TEAM_ID` env var. */\n teamId?: string;\n /** Vercel project ID. Falls back to the `VERCEL_PROJECT_ID` env var. */\n projectId?: string;\n /** Sandbox runtime. @default 'node24' */\n runtime?: VercelSandboxRuntime;\n /**\n * Timeout in milliseconds before the sandbox auto-terminates.\n * @default 300_000 // 5 minutes\n */\n timeout?: number;\n /** Resources to allocate. `vcpus` controls CPU count (2048 MB memory per vCPU). */\n resources?: { vcpus?: number };\n /** Ports to expose from the sandbox (up to 4). Access via `getInfo().metadata.domains`. */\n ports?: number[];\n /** Default environment variables inherited by all commands. */\n env?: Record<string, string>;\n /** Custom metadata surfaced via `getInfo()`. */\n metadata?: Record<string, unknown>;\n /**\n * Custom instructions that override the default instructions\n * returned by `getInstructions()`.\n *\n * - `string` — Fully replaces the default instructions. Pass an empty\n * string to suppress instructions entirely.\n * - `(opts) => string` — Receives the default instructions and optional\n * request context so you can extend or customise per-request.\n */\n instructions?: InstructionsOption;\n}\n\n// =============================================================================\n// Implementation\n// =============================================================================\n\n/**\n * Vercel Sandbox (MicroVM) provider for Mastra workspaces.\n *\n * @example Basic usage\n * ```typescript\n * import { Workspace } from '@mastra/core/workspace';\n * import { VercelSandbox } from '@mastra/vercel';\n *\n * const workspace = new Workspace({\n * sandbox: new VercelSandbox({ runtime: 'node24', timeout: 600_000 }),\n * });\n *\n * const result = await workspace.sandbox.executeCommand('node', ['--version']);\n * ```\n */\nexport class VercelSandbox extends MastraSandbox {\n readonly id: string;\n readonly name = 'VercelSandbox';\n readonly provider = 'vercel-sandbox';\n status: ProviderStatus = 'pending';\n\n declare readonly processes: VercelSandboxProcessManager;\n\n private _sandbox: Sandbox | null = null;\n private _createdAt: Date | null = null;\n\n private readonly _sandboxName?: string;\n private readonly _token?: string;\n private readonly _teamId?: string;\n private readonly _projectId?: string;\n private readonly _runtime: VercelSandboxRuntime;\n private readonly _timeout: number;\n private readonly _vcpus?: number;\n private readonly _ports?: number[];\n private readonly _env: Record<string, string>;\n private readonly _metadata: Record<string, unknown>;\n private readonly _instructionsOverride?: InstructionsOption;\n\n constructor(options: VercelSandboxOptions = {}) {\n super({\n ...options,\n name: 'VercelSandbox',\n processes: new VercelSandboxProcessManager({ env: options.env ?? {} }),\n });\n\n this.id = options.id ?? `vercel-sandbox-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;\n this._sandboxName = options.sandboxName;\n this._token = options.token ?? process.env.VERCEL_TOKEN;\n this._teamId = options.teamId ?? process.env.VERCEL_TEAM_ID;\n this._projectId = options.projectId ?? process.env.VERCEL_PROJECT_ID;\n this._runtime = options.runtime ?? 'node24';\n this._timeout = options.timeout ?? 300_000;\n this._vcpus = options.resources?.vcpus;\n this._ports = options.ports;\n this._env = options.env ?? {};\n this._metadata = options.metadata ?? {};\n this._instructionsOverride = options.instructions;\n }\n\n /**\n * The underlying `@vercel/sandbox` instance.\n * Throws if the sandbox has not been started yet.\n */\n get sandbox(): Sandbox {\n if (!this._sandbox) {\n throw new SandboxNotReadyError(this.id);\n }\n return this._sandbox;\n }\n\n // ---------------------------------------------------------------------------\n // Lifecycle\n // ---------------------------------------------------------------------------\n\n async start(): Promise<void> {\n if (this._sandbox) {\n return;\n }\n\n // Credentials are all-or-nothing: when any explicit credential is provided,\n // the SDK requires the full triple. Otherwise it falls back to the OIDC token.\n const hasExplicitCreds = Boolean(this._token || this._teamId || this._projectId);\n if (hasExplicitCreds && !(this._token && this._teamId && this._projectId)) {\n throw new Error(\n `${LOG_PREFIX} Incomplete credentials. Provide token, teamId, and projectId together ` +\n `(or the VERCEL_TOKEN, VERCEL_TEAM_ID, and VERCEL_PROJECT_ID env vars), ` +\n `or omit all three to use the VERCEL_OIDC_TOKEN.`,\n );\n }\n\n this.logger.debug(`${LOG_PREFIX} Creating sandbox...`, { runtime: this._runtime, timeout: this._timeout });\n\n this._sandbox = await Sandbox.create({\n ...(this._sandboxName ? { name: this._sandboxName } : {}),\n runtime: this._runtime,\n timeout: this._timeout,\n ...(this._vcpus ? { resources: { vcpus: this._vcpus } } : {}),\n ...(this._ports?.length ? { ports: this._ports } : {}),\n ...(Object.keys(this._env).length ? { env: this._env } : {}),\n ...(hasExplicitCreds ? { token: this._token!, teamId: this._teamId!, projectId: this._projectId! } : {}),\n });\n\n this._createdAt = new Date();\n this.logger.debug(`${LOG_PREFIX} Sandbox ready: ${this._sandbox.name}`);\n }\n\n async stop(): Promise<void> {\n await this._teardown();\n }\n\n async destroy(): Promise<void> {\n await this._teardown();\n }\n\n private async _teardown(): Promise<void> {\n if (!this._sandbox) {\n return;\n }\n try {\n await this._sandbox.stop();\n } catch (error) {\n this.logger.warn(`${LOG_PREFIX} Error stopping sandbox:`, error);\n }\n this._sandbox = null;\n }\n\n // ---------------------------------------------------------------------------\n // Command Execution\n // ---------------------------------------------------------------------------\n\n async executeCommand(command: string, args?: string[], options?: ExecuteCommandOptions): Promise<CommandResult> {\n await this.ensureRunning();\n\n const startTime = Date.now();\n const fullCommand = args?.length ? `${command} ${args.join(' ')}` : command;\n this.logger.debug(`${LOG_PREFIX} Executing: ${fullCommand}`, { cwd: options?.cwd });\n\n const mergedEnv = { ...this._env, ...options?.env };\n const env = Object.fromEntries(\n Object.entries(mergedEnv).filter((entry): entry is [string, string] => entry[1] !== undefined),\n );\n\n // Race the command against the optional timeout so we can return a partial\n // result with a 124 exit code (matching other providers) instead of hanging.\n // On timeout we abort the in-flight command so it stops running in the VM.\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n const abortController = new AbortController();\n const forwardAbort = () => abortController.abort();\n if (options?.abortSignal) {\n if (options.abortSignal.aborted) abortController.abort();\n else options.abortSignal.addEventListener('abort', forwardAbort, { once: true });\n }\n const signal = abortController.signal;\n const timeoutPromise = options?.timeout\n ? new Promise<'timeout'>(resolve => {\n timeoutId = setTimeout(() => resolve('timeout'), options.timeout);\n })\n : null;\n\n try {\n const commandPromise = this.sandbox.runCommand({\n cmd: command,\n args: args ?? [],\n ...(options?.cwd ? { cwd: options.cwd } : {}),\n ...(Object.keys(env).length ? { env } : {}),\n signal,\n });\n\n const finished = timeoutPromise ? await Promise.race([commandPromise, timeoutPromise]) : await commandPromise;\n\n if (finished === 'timeout') {\n abortController.abort();\n return {\n command: fullCommand,\n args,\n success: false,\n exitCode: 124,\n stdout: '',\n stderr: `Command timed out after ${options!.timeout}ms`,\n executionTimeMs: Date.now() - startTime,\n timedOut: true,\n };\n }\n\n const [stdout, stderr] = await Promise.all([finished.stdout(), finished.stderr()]);\n\n if (options?.onStdout && stdout) options.onStdout(stdout);\n if (options?.onStderr && stderr) options.onStderr(stderr);\n\n return {\n command: fullCommand,\n args,\n success: finished.exitCode === 0,\n exitCode: finished.exitCode,\n stdout,\n stderr,\n executionTimeMs: Date.now() - startTime,\n };\n } finally {\n if (timeoutId) clearTimeout(timeoutId);\n options?.abortSignal?.removeEventListener('abort', forwardAbort);\n }\n }\n\n // ---------------------------------------------------------------------------\n // Info & Instructions\n // ---------------------------------------------------------------------------\n\n getInfo(): SandboxInfo {\n const domains: Record<number, string> = {};\n if (this._sandbox && this._ports?.length) {\n for (const port of this._ports) {\n try {\n domains[port] = this._sandbox.domain(port);\n } catch {\n // Port may not have an associated route yet — skip.\n }\n }\n }\n\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 metadata: {\n ...this._metadata,\n sandboxName: this._sandbox?.name,\n runtime: this._runtime,\n timeout: this._timeout,\n ...(this._vcpus ? { vcpus: this._vcpus } : {}),\n ...(this._ports?.length ? { ports: this._ports, domains } : {}),\n },\n };\n }\n\n // Matches the resolveInstructions pattern in @mastra/core/workspace.\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 return [\n 'Vercel Sandbox: an ephemeral Firecracker MicroVM running Amazon Linux 2023.',\n `- Runtime: ${this._runtime}. Working directory defaults to /vercel/sandbox.`,\n '- Persistent filesystem within the session; state is lost when the sandbox stops.',\n '- Runs as the vercel-sandbox user with sudo access (install packages via dnf).',\n `- The sandbox auto-terminates after ${Math.round(this._timeout / 1000)} seconds.`,\n ...(this._ports?.length\n ? [`- Exposed ports: ${this._ports.join(', ')} (reachable via public HTTPS domains).`]\n : []),\n '- Background/long-running processes are supported via the process tools.',\n '- Filesystem mounting (FUSE) is not supported.',\n ].join('\\n');\n }\n}\n","/**\n * Vercel Sandbox (MicroVM) provider descriptor for MastraEditor.\n *\n * @example\n * ```typescript\n * import { vercelSandboxProvider } from '@mastra/vercel';\n *\n * const editor = new MastraEditor({\n * sandboxes: [vercelSandboxProvider],\n * });\n * ```\n */\nimport type { SandboxProvider } from '@mastra/core/editor';\nimport { VercelSandbox } from './microvm';\n\n/**\n * Serializable subset of VercelSandboxOptions for editor storage.\n */\ninterface VercelSandboxProviderConfig {\n token?: string;\n teamId?: string;\n projectId?: string;\n runtime?: 'node24' | 'node22' | 'node26' | 'python3.13';\n timeout?: number;\n vcpus?: number;\n ports?: number[];\n env?: Record<string, string>;\n}\n\nexport const vercelSandboxProvider: SandboxProvider<VercelSandboxProviderConfig> = {\n id: 'vercel-sandbox',\n name: 'Vercel Sandbox (MicroVM)',\n description: 'Ephemeral Firecracker MicroVM sandbox powered by Vercel Sandbox',\n configSchema: {\n type: 'object',\n properties: {\n token: { type: 'string', description: 'Vercel API token (falls back to VERCEL_TOKEN; omit to use OIDC)' },\n teamId: { type: 'string', description: 'Vercel team ID (falls back to VERCEL_TEAM_ID)' },\n projectId: { type: 'string', description: 'Vercel project ID (falls back to VERCEL_PROJECT_ID)' },\n runtime: {\n type: 'string',\n description: 'Sandbox runtime',\n enum: ['node24', 'node22', 'node26', 'python3.13'],\n default: 'node24',\n },\n timeout: { type: 'number', description: 'Auto-terminate timeout in milliseconds', default: 300000 },\n vcpus: { type: 'number', description: 'Number of vCPUs (2048 MB memory per vCPU)' },\n ports: {\n type: 'array',\n description: 'Ports to expose (up to 4)',\n items: { type: 'number' },\n },\n env: {\n type: 'object',\n description: 'Environment variables',\n additionalProperties: { type: 'string' },\n },\n },\n },\n createSandbox: config =>\n new VercelSandbox({\n token: config.token,\n teamId: config.teamId,\n projectId: config.projectId,\n runtime: config.runtime,\n timeout: config.timeout,\n ...(config.vcpus ? { resources: { vcpus: config.vcpus } } : {}),\n ports: config.ports,\n env: config.env,\n }),\n};\n"]}
1
+ {"version":3,"sources":["../src/executor/index.ts","../src/serverless/index.ts","../src/serverless-provider.ts","../src/microvm/process-manager.ts","../src/microvm/index.ts","../src/microvm-provider.ts"],"names":["MastraSandbox","SandboxNotReadyError","ProcessHandle","SandboxProcessManager","LOG_PREFIX","Sandbox"],"mappings":";;;;;;;;AAUO,SAAS,iBAAA,CAAkB,QAAgB,GAAA,EAAqC;AACrF,EAAA,MAAM,UAAA,GAAa,MAAA,CAAO,OAAA,CAAQ,GAAG,CAAA,CAClC,IAAI,CAAC,CAAC,CAAA,EAAG,CAAC,CAAA,KAAM,CAAA,EAAA,EAAK,KAAK,SAAA,CAAU,CAAC,CAAC,CAAA,EAAA,EAAK,IAAA,CAAK,SAAA,CAAU,CAAC,CAAC,CAAA,CAAE,CAAA,CAC9D,IAAA,CAAK,KAAK,CAAA;AAEb,EAAA,OAAO;AAAA;;AAAA,uBAAA,EAGgB,IAAA,CAAK,SAAA,CAAU,MAAM,CAAC,CAAA;AAAA;AAAA,EAE7C,UAAU;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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,EAAS;AAAA,OACX;AAAA,MACA,SAAS,EAAE,IAAA,EAAM,UAAU,WAAA,EAAa,wCAAA,EAA0C,SAAS,GAAA,EAAO;AAAA,MAClG,KAAA,EAAO,EAAE,IAAA,EAAM,QAAA,EAAU,aAAa,2CAAA,EAA4C;AAAA,MAClF,KAAA,EAAO;AAAA,QACL,IAAA,EAAM,OAAA;AAAA,QACN,WAAA,EAAa,2BAAA;AAAA,QACb,KAAA,EAAO,EAAE,IAAA,EAAM,QAAA;AAAS,OAC1B;AAAA,MACA,GAAA,EAAK;AAAA,QACH,IAAA,EAAM,QAAA;AAAA,QACN,WAAA,EAAa,uBAAA;AAAA,QACb,oBAAA,EAAsB,EAAE,IAAA,EAAM,QAAA;AAAS;AACzC;AACF,GACF;AAAA,EACA,aAAA,EAAe,CAAA,MAAA,KACb,IAAI,aAAA,CAAc;AAAA,IAChB,OAAO,MAAA,CAAO,KAAA;AAAA,IACd,QAAQ,MAAA,CAAO,MAAA;AAAA,IACf,WAAW,MAAA,CAAO,SAAA;AAAA,IAClB,SAAS,MAAA,CAAO,OAAA;AAAA,IAChB,SAAS,MAAA,CAAO,OAAA;AAAA,IAChB,GAAI,MAAA,CAAO,KAAA,GAAQ,EAAE,SAAA,EAAW,EAAE,KAAA,EAAO,MAAA,CAAO,KAAA,EAAM,EAAE,GAAI,EAAC;AAAA,IAC7D,OAAO,MAAA,CAAO,KAAA;AAAA,IACd,KAAK,MAAA,CAAO;AAAA,GACb;AACL","file":"index.cjs","sourcesContent":["/**\n * Executor function source code deployed to Vercel as a serverless function.\n *\n * Returns a string because it's sent as inline file content via\n * the Vercel Deployments API — no separate build step needed.\n *\n * The secret and user env vars are embedded as constants in the source\n * because the Vercel Deployments API does not support setting env vars\n * directly — they must be configured via vercel.json or project settings.\n */\nexport function getExecutorSource(secret: string, env: Record<string, string>): string {\n const envEntries = Object.entries(env)\n .map(([k, v]) => ` ${JSON.stringify(k)}: ${JSON.stringify(v)}`)\n .join(',\\n');\n\n return `\nconst { execFileSync } = require('child_process');\n\nconst SANDBOX_SECRET = ${JSON.stringify(secret)};\nconst SANDBOX_ENV = {\n${envEntries}\n};\n\nmodule.exports = async (req, res) => {\n // Auth check\n const authHeader = req.headers['authorization'] || '';\n if (!SANDBOX_SECRET || authHeader !== 'Bearer ' + SANDBOX_SECRET) {\n return res.status(401).json({ error: 'Unauthorized' });\n }\n\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' });\n }\n\n const { command, args = [], env = {}, cwd, timeout = 55000 } = req.body || {};\n\n if (!command) {\n return res.status(400).json({ error: 'Missing required field: command' });\n }\n\n const execCwd = cwd || '/tmp';\n const execEnv = { ...process.env, ...SANDBOX_ENV, ...env };\n\n // When args is empty the caller sent a full shell command string\n // (e.g. \"echo hello\" or \"ls -la | grep foo\"). Run it through\n // /bin/sh so builtins and pipes work. When args is non-empty the\n // caller split the command properly — use execFileSync to avoid\n // shell injection.\n const useShell = !args || args.length === 0;\n const execCommand = useShell ? '/bin/sh' : command;\n const execArgs = useShell ? ['-c', command] : args;\n\n const startTime = Date.now();\n let timedOut = false;\n\n try {\n const stdout = execFileSync(execCommand, execArgs, {\n cwd: execCwd,\n env: execEnv,\n timeout,\n maxBuffer: 10 * 1024 * 1024,\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n\n return res.status(200).json({\n success: true,\n exitCode: 0,\n stdout: stdout || '',\n stderr: '',\n executionTimeMs: Date.now() - startTime,\n timedOut: false,\n });\n } catch (error) {\n timedOut = error.killed || false;\n\n return res.status(200).json({\n success: false,\n exitCode: error.status != null ? error.status : 1,\n stdout: error.stdout || '',\n stderr: error.stderr || '',\n executionTimeMs: Date.now() - startTime,\n timedOut,\n });\n }\n};\n`;\n}\n","/**\n * Vercel Serverless Sandbox Provider\n *\n * Deploys code as Vercel serverless functions and executes commands\n * via HTTP invocation. Stateless — no persistent filesystem, no\n * interactive shell, no long-running processes.\n *\n * @see https://vercel.com/docs/rest-api\n */\n\nimport type { RequestContext } from '@mastra/core/di';\nimport type {\n SandboxInfo,\n CommandResult,\n ExecuteCommandOptions,\n MastraSandboxOptions,\n ProviderStatus,\n InstructionsOption,\n} from '@mastra/core/workspace';\nimport { MastraSandbox, SandboxNotReadyError } from '@mastra/core/workspace';\nimport { getExecutorSource } from '../executor';\n\nconst LOG_PREFIX = '[VercelServerlessSandbox]';\n\nconst VERCEL_API_BASE = 'https://api.vercel.com';\n\n/**\n * Shell-quote an argument for safe interpolation into a shell command string.\n * Mirrors the implementation in packages/core/src/workspace/sandbox/utils.ts\n * which is not publicly exported.\n */\nfunction shellQuote(arg: string): string {\n if (/^[a-zA-Z0-9._\\-\\/=:@]+$/.test(arg)) return arg;\n return `'${arg.replace(/'/g, \"'\\\\''\")}'`;\n}\n\n// =============================================================================\n// Options\n// =============================================================================\n\nexport interface VercelServerlessSandboxOptions extends Omit<MastraSandboxOptions, 'processes'> {\n /** Vercel API token. Falls back to VERCEL_TOKEN env var. */\n token?: string;\n /** Vercel team ID for team-scoped deployments. */\n teamId?: string;\n /** Existing Vercel project name. Auto-generated if omitted. */\n projectName?: string;\n /** Deployment regions. @default ['iad1'] */\n regions?: string[];\n /** Function max duration in seconds. @default 60 */\n maxDuration?: number;\n /** Function memory in MB. @default 1024 */\n memory?: number;\n /** Environment variables baked into the deployed function. */\n env?: Record<string, string>;\n /** Per-invocation command timeout in ms. @default 55000 */\n commandTimeout?: number;\n /**\n * Custom instructions that override the default instructions\n * returned by `getInstructions()`.\n */\n instructions?: InstructionsOption;\n}\n\n// =============================================================================\n// Implementation\n// =============================================================================\n\nexport class VercelServerlessSandbox extends MastraSandbox {\n readonly id: string;\n readonly name = 'VercelServerlessSandbox';\n readonly provider = 'vercel-serverless';\n status: ProviderStatus = 'pending';\n\n private readonly _token: string;\n private readonly _teamId?: string;\n private readonly _projectName?: string;\n private readonly _regions: string[];\n private readonly _maxDuration: number;\n private readonly _memory: number;\n private readonly _env: Record<string, string>;\n private readonly _commandTimeout: number;\n private readonly _instructionsOverride?: InstructionsOption;\n private readonly _secret: string;\n\n private _deploymentUrl: string | null = null;\n private _deploymentId: string | null = null;\n private _protectionBypass: string | null = null;\n private _createdAt: Date | null = null;\n\n constructor(options: VercelServerlessSandboxOptions = {}) {\n super({ name: 'VercelServerlessSandbox' });\n\n this.id = `vercel-serverless-sandbox-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;\n this._token = options.token || process.env.VERCEL_TOKEN || '';\n this._teamId = options.teamId;\n this._projectName = options.projectName;\n this._regions = options.regions ?? ['iad1'];\n this._maxDuration = options.maxDuration ?? 60;\n this._memory = options.memory ?? 1024;\n this._env = options.env ?? {};\n this._commandTimeout = options.commandTimeout ?? 55_000;\n this._instructionsOverride = options.instructions;\n this._secret = crypto.randomUUID();\n }\n\n // ---------------------------------------------------------------------------\n // Lifecycle\n // ---------------------------------------------------------------------------\n\n async start(): Promise<void> {\n if (this._deploymentUrl) {\n return;\n }\n\n if (!this._token) {\n throw new Error(`${LOG_PREFIX} Missing Vercel API token. Set VERCEL_TOKEN env var or pass token option.`);\n }\n\n // Clean up any stale deployment from a previous stop() → start() cycle.\n // Without this, the old _deploymentId is overwritten and that deployment leaks.\n if (this._deploymentId) {\n this.logger.debug(`${LOG_PREFIX} Cleaning up stale deployment ${this._deploymentId} before restarting...`);\n try {\n const resp = await this._vercelFetch(`/v13/deployments/${this._deploymentId}`, { method: 'DELETE' });\n if (!resp.ok && resp.status !== 404) {\n this.logger.warn(`${LOG_PREFIX} Failed to delete stale deployment: ${resp.status}`);\n }\n } catch (error) {\n this.logger.warn(`${LOG_PREFIX} Error deleting stale deployment:`, error);\n }\n this._deploymentId = null;\n }\n\n this.logger.debug(`${LOG_PREFIX} Deploying executor function...`);\n\n const vercelJson = JSON.stringify({\n functions: {\n 'api/execute.js': {\n memory: this._memory,\n maxDuration: this._maxDuration,\n },\n },\n regions: this._regions,\n });\n\n // Create the deployment\n const deploymentBody: Record<string, unknown> = {\n name: this._projectName ?? `mastra-sandbox-${this.id}`,\n files: [\n {\n file: 'api/execute.js',\n data: getExecutorSource(this._secret, this._env),\n },\n {\n file: 'vercel.json',\n data: vercelJson,\n },\n ],\n projectSettings: {\n framework: null,\n },\n target: 'production',\n };\n\n const createResp = await this._vercelFetch('/v13/deployments', {\n method: 'POST',\n body: JSON.stringify(deploymentBody),\n });\n\n if (!createResp.ok) {\n const errorBody = await createResp.text();\n throw new Error(`${LOG_PREFIX} Failed to create deployment: ${createResp.status} ${errorBody}`);\n }\n\n const deployment = (await createResp.json()) as { id: string; url: string; readyState: string; projectId?: string };\n this._deploymentId = deployment.id;\n\n this.logger.debug(`${LOG_PREFIX} Deployment created: ${deployment.id}, polling for READY...`);\n\n // Poll until ready\n const maxWaitMs = 120_000;\n const pollIntervalMs = 3_000;\n const deadline = Date.now() + maxWaitMs;\n\n while (Date.now() < deadline) {\n const statusResp = await this._vercelFetch(`/v13/deployments/${deployment.id}`);\n if (!statusResp.ok) {\n throw new Error(`${LOG_PREFIX} Failed to check deployment status: ${statusResp.status}`);\n }\n\n const statusBody = (await statusResp.json()) as { readyState: string; url: string };\n\n if (statusBody.readyState === 'READY') {\n this._deploymentUrl = `https://${statusBody.url}`;\n this._createdAt = new Date();\n this.logger.debug(`${LOG_PREFIX} Deployment ready: ${this._deploymentUrl}`);\n\n // Acquire a deployment protection bypass token.\n // Pro/Enterprise teams have Deployment Protection enabled by default,\n // which intercepts HTTP requests with an SSO login page before they\n // reach the serverless function. The bypass token lets us skip that.\n if (deployment.projectId) {\n try {\n this._protectionBypass = await this._acquireProtectionBypass(deployment.projectId);\n } catch {\n // Non-fatal — if the project has no deployment protection, this is unnecessary.\n }\n }\n\n // Warm-up ping\n try {\n await fetch(`${this._deploymentUrl}/api/execute`, {\n method: 'POST',\n headers: this._executorHeaders(),\n body: JSON.stringify({ command: 'echo', args: ['warm'] }),\n });\n } catch {\n // Warm-up failure is non-fatal\n }\n\n return;\n }\n\n if (statusBody.readyState === 'ERROR' || statusBody.readyState === 'CANCELED') {\n throw new Error(`${LOG_PREFIX} Deployment failed with state: ${statusBody.readyState}`);\n }\n\n await new Promise(resolve => setTimeout(resolve, pollIntervalMs));\n }\n\n throw new Error(`${LOG_PREFIX} Deployment timed out after ${maxWaitMs}ms`);\n }\n\n async stop(): Promise<void> {\n // Only clear the URL (disconnects from the deployment) but keep\n // _deploymentId so a subsequent destroy() can still clean up the\n // cloud resource. Clearing both would make destroy() a no-op and\n // leak the deployment.\n this._deploymentUrl = null;\n }\n\n async destroy(): Promise<void> {\n if (this._deploymentId) {\n try {\n const resp = await this._vercelFetch(`/v13/deployments/${this._deploymentId}`, {\n method: 'DELETE',\n });\n if (!resp.ok) {\n // 404 means the deployment is already gone — that's fine.\n // Other status codes indicate infrastructure issues (auth, network)\n // and should be surfaced more visibly.\n if (resp.status === 404) {\n this.logger.debug(`${LOG_PREFIX} Deployment already deleted (404)`);\n } else {\n this.logger.warn(`${LOG_PREFIX} Failed to delete deployment: ${resp.status}`);\n }\n }\n } catch (error) {\n // Network-level failure — warn rather than debug so it's visible\n this.logger.warn(`${LOG_PREFIX} Error deleting deployment:`, error);\n }\n this._deploymentId = null;\n }\n this._deploymentUrl = null;\n this._protectionBypass = null;\n }\n\n // ---------------------------------------------------------------------------\n // Command Execution\n // ---------------------------------------------------------------------------\n\n async executeCommand(command: string, args?: string[], options?: ExecuteCommandOptions): Promise<CommandResult> {\n await this.ensureRunning();\n\n if (!this._deploymentUrl) {\n throw new SandboxNotReadyError(this.id);\n }\n\n const fullCommand = args?.length ? `${command} ${args.map(a => shellQuote(a)).join(' ')}` : command;\n this.logger.debug(`${LOG_PREFIX} Executing: ${fullCommand}`);\n\n const body = {\n command,\n args: args ?? [],\n env: options?.env ?? {},\n cwd: options?.cwd ?? '/tmp',\n timeout: options?.timeout ?? this._commandTimeout,\n };\n\n const maxRetries = 2;\n let lastError: Error | null = null;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n const resp = await fetch(`${this._deploymentUrl}/api/execute`, {\n method: 'POST',\n headers: this._executorHeaders(),\n body: JSON.stringify(body),\n signal: options?.abortSignal,\n });\n\n // Retry on transient errors\n if ((resp.status === 429 || resp.status === 502 || resp.status === 503) && attempt < maxRetries) {\n this.logger.debug(`${LOG_PREFIX} Retryable status ${resp.status}, attempt ${attempt + 1}/${maxRetries}`);\n await new Promise(resolve => setTimeout(resolve, 1000 * (attempt + 1)));\n continue;\n }\n\n // Gateway timeout → timedOut\n if (resp.status === 504) {\n return {\n command: fullCommand,\n args,\n success: false,\n exitCode: 124,\n stdout: '',\n stderr: 'Function execution timed out (504 Gateway Timeout)',\n executionTimeMs: options?.timeout ?? this._commandTimeout,\n timedOut: true,\n };\n }\n\n if (!resp.ok) {\n const errorText = await resp.text();\n throw new Error(`${LOG_PREFIX} Execute failed: ${resp.status} ${errorText}`);\n }\n\n const result = (await resp.json()) as {\n success: boolean;\n exitCode: number;\n stdout: string;\n stderr: string;\n executionTimeMs: number;\n timedOut: boolean;\n };\n\n // Stream callbacks\n if (options?.onStdout && result.stdout) {\n options.onStdout(result.stdout);\n }\n if (options?.onStderr && result.stderr) {\n options.onStderr(result.stderr);\n }\n\n return {\n command: fullCommand,\n args,\n success: result.success,\n exitCode: result.exitCode,\n stdout: result.stdout,\n stderr: result.stderr,\n executionTimeMs: result.executionTimeMs,\n timedOut: result.timedOut,\n };\n } catch (error) {\n if (error instanceof DOMException && error.name === 'AbortError') {\n throw error;\n }\n lastError = error as Error;\n if (attempt < maxRetries) {\n this.logger.debug(`${LOG_PREFIX} Request error, attempt ${attempt + 1}/${maxRetries}:`, error);\n await new Promise(resolve => setTimeout(resolve, 1000 * (attempt + 1)));\n continue;\n }\n }\n }\n\n throw lastError ?? new Error(`${LOG_PREFIX} executeCommand failed after retries`);\n }\n\n // ---------------------------------------------------------------------------\n // Info & Instructions\n // ---------------------------------------------------------------------------\n\n // Matches the resolveInstructions pattern in packages/core/src/workspace/utils.ts\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 return [\n 'Vercel serverless sandbox.',\n 'Limitations:',\n '- Stateless: no persistent filesystem between invocations.',\n '- No interactive shell or streaming stdin.',\n '- No long-running or background processes.',\n `- Maximum execution time: ${this._maxDuration} seconds.`,\n '- Only /tmp is writable (ephemeral, cleared between invocations).',\n '- Shell commands (pipes, builtins) are supported via /bin/sh -c.',\n ].join('\\n');\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 metadata: {\n deploymentId: this._deploymentId,\n deploymentUrl: this._deploymentUrl,\n regions: this._regions,\n maxDuration: this._maxDuration,\n memory: this._memory,\n },\n };\n }\n\n // ---------------------------------------------------------------------------\n // Private Helpers\n // ---------------------------------------------------------------------------\n\n /**\n * Fetch an existing protection bypass token for the project, or create one\n * if none exists. Returns the token string, or null if acquisition fails.\n */\n private async _acquireProtectionBypass(projectId: string): Promise<string | null> {\n // 1. Check if the project already has a bypass token.\n const projResp = await this._vercelFetch(`/v9/projects/${projectId}`);\n if (projResp.ok) {\n const project = (await projResp.json()) as {\n protectionBypass?: Record<string, unknown>;\n };\n const existing = project.protectionBypass ? Object.keys(project.protectionBypass)[0] : undefined;\n if (existing) {\n this.logger.debug(`${LOG_PREFIX} Using existing protection bypass token`);\n return existing;\n }\n }\n\n // 2. No token exists — create one via the dedicated endpoint.\n this.logger.debug(`${LOG_PREFIX} Creating protection bypass token...`);\n const createResp = await this._vercelFetch(`/v1/projects/${projectId}/protection-bypass`, {\n method: 'PATCH',\n body: JSON.stringify({}),\n });\n if (createResp.ok) {\n const result = (await createResp.json()) as {\n protectionBypass?: Record<string, unknown>;\n };\n const created = result.protectionBypass ? Object.keys(result.protectionBypass)[0] : undefined;\n if (created) {\n this.logger.debug(`${LOG_PREFIX} Protection bypass token created`);\n return created;\n }\n }\n\n this.logger.debug(`${LOG_PREFIX} Could not acquire protection bypass token (project may not require it)`);\n return null;\n }\n\n private _executorHeaders(): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this._secret}`,\n };\n if (this._protectionBypass) {\n headers['x-vercel-protection-bypass'] = this._protectionBypass;\n }\n return headers;\n }\n\n private async _vercelFetch(path: string, options: RequestInit = {}): Promise<Response> {\n const url = new URL(path, VERCEL_API_BASE);\n if (this._teamId) {\n url.searchParams.set('teamId', this._teamId);\n }\n\n return fetch(url.toString(), {\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this._token}`,\n ...((options.headers as Record<string, string>) ?? {}),\n },\n });\n }\n}\n","/**\n * Vercel serverless sandbox provider descriptor for MastraEditor.\n *\n * @example\n * ```typescript\n * import { vercelServerlessSandboxProvider } from '@mastra/vercel';\n *\n * const editor = new MastraEditor({\n * sandboxes: [vercelServerlessSandboxProvider],\n * });\n * ```\n */\nimport type { SandboxProvider } from '@mastra/core/editor';\nimport { VercelServerlessSandbox } from './serverless';\n\n/**\n * Serializable subset of VercelServerlessSandboxOptions for editor storage.\n */\ninterface VercelProviderConfig {\n token?: string;\n teamId?: string;\n projectName?: string;\n regions?: string[];\n maxDuration?: number;\n memory?: number;\n env?: Record<string, string>;\n commandTimeout?: number;\n}\n\nexport const vercelServerlessSandboxProvider: SandboxProvider<VercelProviderConfig> = {\n id: 'vercel-serverless',\n name: 'Vercel Sandbox (Serverless)',\n description: 'Serverless sandbox powered by Vercel Functions',\n configSchema: {\n type: 'object',\n properties: {\n token: { type: 'string', description: 'Vercel API token' },\n teamId: { type: 'string', description: 'Vercel team ID' },\n projectName: { type: 'string', description: 'Existing Vercel project name' },\n regions: {\n type: 'array',\n description: 'Deployment regions',\n items: { type: 'string' },\n default: ['iad1'],\n },\n maxDuration: { type: 'number', description: 'Function max duration in seconds', default: 60 },\n memory: { type: 'number', description: 'Function memory in MB', default: 1024 },\n env: {\n type: 'object',\n description: 'Environment variables',\n additionalProperties: { type: 'string' },\n },\n commandTimeout: { type: 'number', description: 'Per-invocation timeout in ms', default: 55000 },\n },\n },\n createSandbox: config => new VercelServerlessSandbox(config),\n};\n","/**\n * Vercel Sandbox (MicroVM) Process Manager\n *\n * Implements SandboxProcessManager for the `@vercel/sandbox` SDK. Each spawn()\n * starts a detached command via `sandbox.runCommand({ detached: true })` and\n * streams its output through the command's async `logs()` iterator.\n *\n * The Vercel Sandbox SDK does not expose a stdin channel for running commands,\n * so `sendStdin()` throws a clear \"not supported\" error.\n */\n\nimport { ProcessHandle, SandboxProcessManager } from '@mastra/core/workspace';\nimport type { CommandResult, ProcessInfo, SpawnProcessOptions } from '@mastra/core/workspace';\nimport type { Command } from '@vercel/sandbox';\nimport type { VercelSandbox } from './index';\n\n// =============================================================================\n// Process Handle\n// =============================================================================\n\n/**\n * Wraps a detached Vercel Sandbox {@link Command} to conform to Mastra's\n * ProcessHandle. Not exported — internal to this module.\n */\nclass VercelSandboxProcessHandle extends ProcessHandle {\n readonly pid: string;\n\n private readonly _command: Command;\n private readonly _startTime: number;\n private readonly _timeout?: number;\n\n private _exitCode: number | undefined;\n private _waitPromise: Promise<CommandResult> | null = null;\n private _streamingPromise: Promise<void> | null = null;\n private _killed = false;\n\n constructor(command: Command, startTime: number, options?: SpawnProcessOptions) {\n super(options);\n this.pid = command.cmdId;\n this._command = command;\n this._startTime = startTime;\n this._timeout = options?.timeout;\n }\n\n get exitCode(): number | undefined {\n return this._exitCode;\n }\n\n /** @internal Set by the process manager after streaming starts. */\n set streamingPromise(p: Promise<void>) {\n this._streamingPromise = p;\n }\n\n async wait(): Promise<CommandResult> {\n if (!this._waitPromise) {\n this._waitPromise = this._doWait();\n }\n return this._waitPromise;\n }\n\n private async _doWait(): Promise<CommandResult> {\n const finishedPromise = this._command\n .wait()\n .then(finished => {\n if (this._exitCode === undefined) this._exitCode = finished.exitCode;\n })\n .catch(() => {\n if (this._exitCode === undefined) this._exitCode = 1;\n });\n\n if (this._timeout) {\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n const timeoutPromise = new Promise<'timeout'>(resolve => {\n timeoutId = setTimeout(() => resolve('timeout'), this._timeout);\n });\n\n const outcome = await Promise.race([finishedPromise.then(() => 'done' as const), timeoutPromise]);\n clearTimeout(timeoutId);\n\n if (outcome === 'timeout') {\n await this.kill();\n this._exitCode = 124;\n await this._streamingPromise?.catch(() => {});\n return {\n success: false,\n exitCode: 124,\n stdout: this.stdout,\n stderr: this.stderr || `Command timed out after ${this._timeout}ms`,\n executionTimeMs: Date.now() - this._startTime,\n killed: true,\n timedOut: true,\n };\n }\n } else {\n await finishedPromise;\n }\n\n // Drain any remaining streamed output before reporting the result.\n await this._streamingPromise?.catch(() => {});\n\n if (this._killed) {\n return {\n success: false,\n exitCode: this._exitCode ?? 137,\n stdout: this.stdout,\n stderr: this.stderr,\n executionTimeMs: Date.now() - this._startTime,\n killed: true,\n timedOut: false,\n };\n }\n\n return {\n success: this._exitCode === 0,\n exitCode: this._exitCode ?? 1,\n stdout: this.stdout,\n stderr: this.stderr,\n executionTimeMs: Date.now() - this._startTime,\n };\n }\n\n async kill(): Promise<boolean> {\n if (this._exitCode !== undefined && !this._killed) return false;\n this._killed = true;\n if (this._exitCode === undefined) this._exitCode = 137; // SIGKILL\n try {\n await this._command.kill();\n } catch {\n // Command may already be gone.\n }\n return true;\n }\n\n async sendStdin(_data: string): Promise<void> {\n throw new Error('VercelSandbox does not support sending stdin to running processes.');\n }\n}\n\n// =============================================================================\n// Process Manager\n// =============================================================================\n\nexport interface VercelSandboxProcessManagerOptions {\n env?: Record<string, string | undefined>;\n}\n\n/**\n * Vercel Sandbox implementation of SandboxProcessManager. Uses one detached\n * `runCommand` per spawned process.\n */\nexport class VercelSandboxProcessManager extends SandboxProcessManager<VercelSandbox> {\n async spawn(command: string, options: SpawnProcessOptions = {}): Promise<ProcessHandle> {\n const mergedEnv = { ...this.env, ...options.env };\n const env = Object.fromEntries(\n Object.entries(mergedEnv).filter((entry): entry is [string, string] => entry[1] !== undefined),\n );\n\n // The workspace passes a full command string; run it through a shell so\n // pipes, redirects, and builtins behave as expected.\n const cmd = await this.sandbox.sandbox.runCommand({\n cmd: 'sh',\n args: ['-c', command],\n ...(options.cwd ? { cwd: options.cwd } : {}),\n ...(Object.keys(env).length ? { env } : {}),\n detached: true,\n });\n\n const handle = new VercelSandboxProcessHandle(cmd, Date.now(), options);\n\n const streamingPromise = (async () => {\n for await (const log of cmd.logs()) {\n if (log.stream === 'stdout') handle.emitStdout(log.data);\n else handle.emitStderr(log.data);\n }\n })().catch(() => {\n // Stream ends when the command exits or is killed — swallow the error.\n });\n\n handle.streamingPromise = streamingPromise;\n\n this._tracked.set(handle.pid, handle);\n return handle;\n }\n\n async list(): Promise<ProcessInfo[]> {\n const result: ProcessInfo[] = [];\n for (const [pid, handle] of this._tracked) {\n result.push({\n pid,\n command: handle.command,\n running: handle.exitCode === undefined,\n exitCode: handle.exitCode,\n });\n }\n return result;\n }\n}\n","/**\n * Vercel Sandbox (MicroVM) Provider\n *\n * Wraps the official `@vercel/sandbox` SDK, which provisions ephemeral\n * Firecracker MicroVMs (Amazon Linux 2023) with a persistent in-session\n * filesystem, command execution, background processes, and exposed ports.\n *\n * This is distinct from the `VercelServerlessSandbox` provider in this package, which\n * runs commands as Vercel serverless Functions and is stateless.\n *\n * @see https://vercel.com/docs/vercel-sandbox\n */\n\nimport type { RequestContext } from '@mastra/core/di';\nimport type {\n CommandResult,\n ExecuteCommandOptions,\n InstructionsOption,\n MastraSandboxOptions,\n ProviderStatus,\n SandboxFileInput,\n SandboxCloneOptions,\n SandboxInfo,\n SandboxNetworking,\n} from '@mastra/core/workspace';\nimport { MastraSandbox, SandboxNotReadyError } from '@mastra/core/workspace';\nimport { Sandbox } from '@vercel/sandbox';\nimport { VercelSandboxProcessManager } from './process-manager';\n\nconst LOG_PREFIX = '[VercelSandbox]';\n\n/** Vercel Sandbox runtimes (default `node24`). */\nexport type VercelSandboxRuntime = 'node24' | 'node22' | 'node26' | 'python3.13';\n\n// =============================================================================\n// Options\n// =============================================================================\n\n/**\n * Vercel Sandbox (MicroVM) provider configuration.\n *\n * Authentication: the SDK uses the `VERCEL_OIDC_TOKEN` environment variable\n * automatically when available. To authenticate from an environment without\n * OIDC, supply `token`, `teamId`, and `projectId` together (falling back to\n * the `VERCEL_TOKEN`, `VERCEL_TEAM_ID`, and `VERCEL_PROJECT_ID` env vars).\n */\nexport interface VercelSandboxOptions extends Omit<MastraSandboxOptions, 'processes'> {\n /** Unique identifier for this sandbox instance. */\n id?: string;\n /** Optional sandbox name passed to the Vercel API. Auto-generated if omitted. */\n sandboxName?: string;\n /** Vercel API token. Falls back to the `VERCEL_TOKEN` env var. */\n token?: string;\n /** Vercel team ID. Falls back to the `VERCEL_TEAM_ID` env var. */\n teamId?: string;\n /** Vercel project ID. Falls back to the `VERCEL_PROJECT_ID` env var. */\n projectId?: string;\n /** Sandbox runtime. @default 'node24' */\n runtime?: VercelSandboxRuntime;\n /**\n * Timeout in milliseconds before the sandbox auto-terminates.\n * @default 300_000 // 5 minutes\n */\n timeout?: number;\n /** Resources to allocate. `vcpus` controls CPU count (2048 MB memory per vCPU). */\n resources?: { vcpus?: number };\n /** Ports to expose from the sandbox (up to 4). Access via `getInfo().metadata.domains`. */\n ports?: number[];\n /** Default environment variables inherited by all commands. */\n env?: Record<string, string>;\n /** Custom metadata surfaced via `getInfo()`. */\n metadata?: Record<string, unknown>;\n /**\n * Custom instructions that override the default instructions\n * returned by `getInstructions()`.\n *\n * - `string` — Fully replaces the default instructions. Pass an empty\n * string to suppress instructions entirely.\n * - `(opts) => string` — Receives the default instructions and optional\n * request context so you can extend or customise per-request.\n */\n instructions?: InstructionsOption;\n}\n\n// =============================================================================\n// Implementation\n// =============================================================================\n\n/**\n * Vercel Sandbox (MicroVM) provider for Mastra workspaces.\n *\n * @example Basic usage\n * ```typescript\n * import { Workspace } from '@mastra/core/workspace';\n * import { VercelSandbox } from '@mastra/vercel';\n *\n * const workspace = new Workspace({\n * sandbox: new VercelSandbox({ runtime: 'node24', timeout: 600_000 }),\n * });\n *\n * const result = await workspace.sandbox.executeCommand('node', ['--version']);\n * ```\n */\nexport class VercelSandbox extends MastraSandbox {\n readonly id: string;\n readonly name = 'VercelSandbox';\n readonly provider = 'vercel-sandbox';\n status: ProviderStatus = 'pending';\n\n declare readonly processes: VercelSandboxProcessManager;\n\n /**\n * Networking capability: public HTTPS URLs for exposed ports.\n * A port must be declared in `ports` at construction time for a URL to exist.\n */\n readonly networking: SandboxNetworking = {\n getPortUrl: async (port: number): Promise<string | null> => {\n const sandbox = this._sandbox ?? (await this.attach());\n if (!sandbox) return null;\n try {\n return sandbox.domain(port);\n } catch {\n // Port has no associated route (not declared in `ports`).\n return null;\n }\n },\n };\n\n private _sandbox: Sandbox | null = null;\n /** True when `_sandbox` came from a resume-less lookup — `start()` must still resume it. */\n private _attachedWithoutResume = false;\n private _createdAt: Date | null = null;\n\n private readonly _sandboxName?: string;\n private readonly _token?: string;\n private readonly _teamId?: string;\n private readonly _projectId?: string;\n private readonly _runtime: VercelSandboxRuntime;\n private readonly _timeout: number;\n private readonly _vcpus?: number;\n private readonly _ports?: number[];\n private readonly _env: Record<string, string>;\n private readonly _metadata: Record<string, unknown>;\n private readonly _instructionsOverride?: InstructionsOption;\n private readonly _constructorOptions: VercelSandboxOptions;\n\n constructor(options: VercelSandboxOptions = {}) {\n super({\n ...options,\n name: 'VercelSandbox',\n processes: new VercelSandboxProcessManager({ env: options.env ?? {} }),\n });\n\n this.id = options.id ?? `vercel-sandbox-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;\n this._sandboxName = options.sandboxName;\n this._token = options.token ?? process.env.VERCEL_TOKEN;\n this._teamId = options.teamId ?? process.env.VERCEL_TEAM_ID;\n this._projectId = options.projectId ?? process.env.VERCEL_PROJECT_ID;\n this._runtime = options.runtime ?? 'node24';\n this._timeout = options.timeout ?? 300_000;\n this._vcpus = options.resources?.vcpus;\n this._ports = options.ports;\n this._env = options.env ?? {};\n this._metadata = options.metadata ?? {};\n this._instructionsOverride = options.instructions;\n this._constructorOptions = { ...options };\n }\n\n /**\n * Construct a sibling `VercelSandbox` that inherits this sandbox's\n * configuration (credentials, runtime, resources, ports, metadata,\n * instructions) with per-instance overrides.\n *\n * Performs no I/O — the sandbox clone provisions a fresh MicroVM on its\n * own `start()` (Vercel sandboxes cannot be reconnected to, so\n * `options.sandboxId` is ignored). Use it when one configured sandbox acts\n * as the template for a fleet of independent sandboxes (e.g. one per\n * project).\n *\n * `options.idleTimeoutMinutes` maps to the Vercel sandbox `timeout` (ms).\n */\n clone(options: SandboxCloneOptions = {}): VercelSandbox {\n const { id: _id, sandboxName: _sandboxName, ...base } = this._constructorOptions;\n return new VercelSandbox({\n ...base,\n ...(options.id !== undefined && { id: options.id }),\n ...(options.env !== undefined && { env: options.env }),\n ...(options.idleTimeoutMinutes !== undefined && { timeout: options.idleTimeoutMinutes * 60_000 }),\n });\n }\n\n /**\n * The underlying `@vercel/sandbox` instance.\n * Throws if the sandbox has not been started yet.\n */\n get sandbox(): 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 * Attach to an existing named sandbox WITHOUT resuming it (`resume: false`),\n * so lookups (URL resolution, stop, destroy) never wake a stopped sandbox\n * and start billing. Returns null when unnamed or when no sandbox with this\n * name exists.\n */\n private async attach(): Promise<Sandbox | null> {\n if (this._sandbox) return this._sandbox;\n if (!this._sandboxName) return null;\n\n try {\n this._sandbox = await Sandbox.get({\n name: this._sandboxName,\n resume: false,\n ...this.credentialParams(),\n });\n this._attachedWithoutResume = true;\n return this._sandbox;\n } catch {\n return null;\n }\n }\n\n /**\n * The token is the credential: when provided, the SDK requires teamId and\n * projectId alongside it. Without a token the SDK authenticates via the\n * `VERCEL_OIDC_TOKEN`; a stray teamId/projectId (for example, an exported\n * `VERCEL_TEAM_ID` in the shell) must not break OIDC auth, so it is ignored.\n */\n private credentialParams(): { token: string; teamId: string; projectId: string } | Record<string, never> {\n if (!this._token) return {};\n if (!(this._teamId && this._projectId)) {\n throw new Error(\n `${LOG_PREFIX} Incomplete credentials. Provide token, teamId, and projectId together ` +\n `(or the VERCEL_TOKEN, VERCEL_TEAM_ID, and VERCEL_PROJECT_ID env vars), ` +\n `or omit the token to use the VERCEL_OIDC_TOKEN.`,\n );\n }\n return { token: this._token, teamId: this._teamId, projectId: this._projectId };\n }\n\n async start(): Promise<void> {\n // A sandbox attached via a resume-less lookup still needs an actual\n // resume, so only a started/resumed sandbox short-circuits here.\n if (this._sandbox && !this._attachedWithoutResume) {\n return;\n }\n\n this.logger.debug(`${LOG_PREFIX} Creating sandbox...`, { runtime: this._runtime, timeout: this._timeout });\n\n const params = {\n runtime: this._runtime,\n timeout: this._timeout,\n ...(this._vcpus ? { resources: { vcpus: this._vcpus } } : {}),\n ...(this._ports?.length ? { ports: this._ports } : {}),\n ...(Object.keys(this._env).length ? { env: this._env } : {}),\n ...this.credentialParams(),\n };\n\n // Named sandboxes are an identity: get-or-create resumes the existing\n // sandbox (snapshot restore) if one with this name exists, otherwise\n // creates a fresh one with the name. Unnamed sandboxes always create.\n this._sandbox = this._sandboxName\n ? await Sandbox.getOrCreate({ ...params, name: this._sandboxName })\n : await Sandbox.create(params);\n this._attachedWithoutResume = false;\n\n this._createdAt = new Date();\n this.logger.debug(`${LOG_PREFIX} Sandbox ready: ${this._sandbox.name}`);\n }\n\n /** Snapshot-stop: the filesystem persists and a named sandbox resumes on the next `start()`. */\n async stop(): Promise<void> {\n const sandbox = this._sandbox ?? (await this.attach());\n if (!sandbox) {\n return;\n }\n // Stop failures propagate — a sandbox that failed to stop is still\n // running (and billing), so callers must not assume it snapshotted.\n await sandbox.stop();\n this._sandbox = null;\n this._attachedWithoutResume = false;\n }\n\n /** Permanently delete the sandbox and its snapshots. */\n async destroy(): Promise<void> {\n // Attach by name when needed so destroy works from a fresh process\n // (e.g. a `getDeployment()` handle) without resuming the sandbox first.\n const sandbox = this._sandbox ?? (await this.attach());\n if (!sandbox) {\n return;\n }\n // Delete failures propagate — a sandbox that failed to delete still\n // exists, so callers must not assume cleanup completed.\n await sandbox.delete();\n this._sandbox = null;\n this._attachedWithoutResume = false;\n }\n\n // ---------------------------------------------------------------------------\n // File Upload\n // ---------------------------------------------------------------------------\n\n /**\n * Bulk-write files into the sandbox filesystem via the SDK's native upload.\n * Relative paths resolve against /vercel/sandbox.\n */\n async writeFiles(files: SandboxFileInput[]): Promise<void> {\n await this.ensureRunning();\n await this.sandbox.writeFiles(files.map(f => ({ path: f.path, content: f.content })));\n }\n\n // ---------------------------------------------------------------------------\n // Command Execution\n // ---------------------------------------------------------------------------\n\n async executeCommand(command: string, args?: string[], options?: ExecuteCommandOptions): Promise<CommandResult> {\n await this.ensureRunning();\n\n const startTime = Date.now();\n const fullCommand = args?.length ? `${command} ${args.join(' ')}` : command;\n this.logger.debug(`${LOG_PREFIX} Executing: ${fullCommand}`, { cwd: options?.cwd });\n\n const mergedEnv = { ...this._env, ...options?.env };\n const env = Object.fromEntries(\n Object.entries(mergedEnv).filter((entry): entry is [string, string] => entry[1] !== undefined),\n );\n\n // Race the command against the optional timeout so we can return a partial\n // result with a 124 exit code (matching other providers) instead of hanging.\n // On timeout we abort the in-flight command so it stops running in the VM.\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n const abortController = new AbortController();\n const forwardAbort = () => abortController.abort();\n if (options?.abortSignal) {\n if (options.abortSignal.aborted) abortController.abort();\n else options.abortSignal.addEventListener('abort', forwardAbort, { once: true });\n }\n const signal = abortController.signal;\n const timeoutPromise = options?.timeout\n ? new Promise<'timeout'>(resolve => {\n timeoutId = setTimeout(() => resolve('timeout'), options.timeout);\n })\n : null;\n\n try {\n const commandPromise = this.sandbox.runCommand({\n cmd: command,\n args: args ?? [],\n ...(options?.cwd ? { cwd: options.cwd } : {}),\n ...(Object.keys(env).length ? { env } : {}),\n signal,\n });\n\n const finished = timeoutPromise ? await Promise.race([commandPromise, timeoutPromise]) : await commandPromise;\n\n if (finished === 'timeout') {\n abortController.abort();\n return {\n command: fullCommand,\n args,\n success: false,\n exitCode: 124,\n stdout: '',\n stderr: `Command timed out after ${options!.timeout}ms`,\n executionTimeMs: Date.now() - startTime,\n timedOut: true,\n };\n }\n\n const [stdout, stderr] = await Promise.all([finished.stdout(), finished.stderr()]);\n\n if (options?.onStdout && stdout) options.onStdout(stdout);\n if (options?.onStderr && stderr) options.onStderr(stderr);\n\n return {\n command: fullCommand,\n args,\n success: finished.exitCode === 0,\n exitCode: finished.exitCode,\n stdout,\n stderr,\n executionTimeMs: Date.now() - startTime,\n };\n } finally {\n if (timeoutId) clearTimeout(timeoutId);\n options?.abortSignal?.removeEventListener('abort', forwardAbort);\n }\n }\n\n // ---------------------------------------------------------------------------\n // Info & Instructions\n // ---------------------------------------------------------------------------\n\n getInfo(): SandboxInfo {\n const domains: Record<number, string> = {};\n if (this._sandbox && this._ports?.length) {\n for (const port of this._ports) {\n try {\n domains[port] = this._sandbox.domain(port);\n } catch {\n // Port may not have an associated route yet — skip.\n }\n }\n }\n\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 metadata: {\n ...this._metadata,\n sandboxName: this._sandbox?.name,\n runtime: this._runtime,\n timeout: this._timeout,\n ...(this._vcpus ? { vcpus: this._vcpus } : {}),\n ...(this._ports?.length ? { ports: this._ports, domains } : {}),\n },\n };\n }\n\n // Matches the resolveInstructions pattern in @mastra/core/workspace.\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 return [\n 'Vercel Sandbox: an ephemeral Firecracker MicroVM running Amazon Linux 2023.',\n `- Runtime: ${this._runtime}. Working directory defaults to /vercel/sandbox.`,\n this._sandboxName\n ? '- Persistent filesystem: stopping snapshots the filesystem and the named sandbox resumes it on the next start. Processes do not survive a stop.'\n : '- Persistent filesystem within the session; state is lost when the sandbox stops.',\n '- Runs as the vercel-sandbox user with sudo access (install packages via dnf).',\n `- The sandbox auto-terminates after ${Math.round(this._timeout / 1000)} seconds.`,\n ...(this._ports?.length\n ? [`- Exposed ports: ${this._ports.join(', ')} (reachable via public HTTPS domains).`]\n : []),\n '- Background/long-running processes are supported via the process tools.',\n '- Filesystem mounting (FUSE) is not supported.',\n ].join('\\n');\n }\n}\n","/**\n * Vercel Sandbox (MicroVM) provider descriptor for MastraEditor.\n *\n * @example\n * ```typescript\n * import { vercelSandboxProvider } from '@mastra/vercel';\n *\n * const editor = new MastraEditor({\n * sandboxes: [vercelSandboxProvider],\n * });\n * ```\n */\nimport type { SandboxProvider } from '@mastra/core/editor';\nimport { VercelSandbox } from './microvm';\n\n/**\n * Serializable subset of VercelSandboxOptions for editor storage.\n */\ninterface VercelSandboxProviderConfig {\n token?: string;\n teamId?: string;\n projectId?: string;\n runtime?: 'node24' | 'node22' | 'node26' | 'python3.13';\n timeout?: number;\n vcpus?: number;\n ports?: number[];\n env?: Record<string, string>;\n}\n\nexport const vercelSandboxProvider: SandboxProvider<VercelSandboxProviderConfig> = {\n id: 'vercel-sandbox',\n name: 'Vercel Sandbox (MicroVM)',\n description: 'Ephemeral Firecracker MicroVM sandbox powered by Vercel Sandbox',\n configSchema: {\n type: 'object',\n properties: {\n token: { type: 'string', description: 'Vercel API token (falls back to VERCEL_TOKEN; omit to use OIDC)' },\n teamId: { type: 'string', description: 'Vercel team ID (falls back to VERCEL_TEAM_ID)' },\n projectId: { type: 'string', description: 'Vercel project ID (falls back to VERCEL_PROJECT_ID)' },\n runtime: {\n type: 'string',\n description: 'Sandbox runtime',\n enum: ['node24', 'node22', 'node26', 'python3.13'],\n default: 'node24',\n },\n timeout: { type: 'number', description: 'Auto-terminate timeout in milliseconds', default: 300000 },\n vcpus: { type: 'number', description: 'Number of vCPUs (2048 MB memory per vCPU)' },\n ports: {\n type: 'array',\n description: 'Ports to expose (up to 4)',\n items: { type: 'number' },\n },\n env: {\n type: 'object',\n description: 'Environment variables',\n additionalProperties: { type: 'string' },\n },\n },\n },\n createSandbox: config =>\n new VercelSandbox({\n token: config.token,\n teamId: config.teamId,\n projectId: config.projectId,\n runtime: config.runtime,\n timeout: config.timeout,\n ...(config.vcpus ? { resources: { vcpus: config.vcpus } } : {}),\n ports: config.ports,\n env: config.env,\n }),\n};\n"]}