@mastra/vercel 1.3.0-alpha.0 → 1.4.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/dist/index.cjs CHANGED
@@ -1,14 +1,20 @@
1
- 'use strict';
2
-
3
- var workspace = require('@mastra/core/workspace');
4
- var sandbox = require('@vercel/sandbox');
5
-
6
- // src/serverless/index.ts
7
-
8
- // src/executor/index.ts
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _mastra_core_workspace = require("@mastra/core/workspace");
3
+ let _vercel_sandbox = require("@vercel/sandbox");
4
+ //#region src/executor/index.ts
5
+ /**
6
+ * Executor function source code deployed to Vercel as a serverless function.
7
+ *
8
+ * Returns a string because it's sent as inline file content via
9
+ * the Vercel Deployments API — no separate build step needed.
10
+ *
11
+ * The secret and user env vars are embedded as constants in the source
12
+ * because the Vercel Deployments API does not support setting env vars
13
+ * directly — they must be configured via vercel.json or project settings.
14
+ */
9
15
  function getExecutorSource(secret, env) {
10
- const envEntries = Object.entries(env).map(([k, v]) => ` ${JSON.stringify(k)}: ${JSON.stringify(v)}`).join(",\n");
11
- return `
16
+ const envEntries = Object.entries(env).map(([k, v]) => ` ${JSON.stringify(k)}: ${JSON.stringify(v)}`).join(",\n");
17
+ return `
12
18
  const { execFileSync } = require('child_process');
13
19
 
14
20
  const SANDBOX_SECRET = ${JSON.stringify(secret)};
@@ -39,7 +45,7 @@ module.exports = async (req, res) => {
39
45
  // When args is empty the caller sent a full shell command string
40
46
  // (e.g. "echo hello" or "ls -la | grep foo"). Run it through
41
47
  // /bin/sh so builtins and pipes work. When args is non-empty the
42
- // caller split the command properly \u2014 use execFileSync to avoid
48
+ // caller split the command properly — use execFileSync to avoid
43
49
  // shell injection.
44
50
  const useShell = !args || args.length === 0;
45
51
  const execCommand = useShell ? '/bin/sh' : command;
@@ -81,843 +87,849 @@ module.exports = async (req, res) => {
81
87
  };
82
88
  `;
83
89
  }
84
-
85
- // src/serverless/index.ts
86
- var LOG_PREFIX = "[VercelServerlessSandbox]";
87
- var VERCEL_API_BASE = "https://api.vercel.com";
90
+ //#endregion
91
+ //#region src/serverless/index.ts
92
+ const LOG_PREFIX$1 = "[VercelServerlessSandbox]";
93
+ const VERCEL_API_BASE = "https://api.vercel.com";
94
+ /**
95
+ * Shell-quote an argument for safe interpolation into a shell command string.
96
+ * Mirrors the implementation in packages/core/src/workspace/sandbox/utils.ts
97
+ * which is not publicly exported.
98
+ */
88
99
  function shellQuote(arg) {
89
- if (/^[a-zA-Z0-9._\-\/=:@]+$/.test(arg)) return arg;
90
- return `'${arg.replace(/'/g, "'\\''")}'`;
100
+ if (/^[a-zA-Z0-9._\-\/=:@]+$/.test(arg)) return arg;
101
+ return `'${arg.replace(/'/g, "'\\''")}'`;
91
102
  }
92
- var VercelServerlessSandbox = class extends workspace.MastraSandbox {
93
- id;
94
- name = "VercelServerlessSandbox";
95
- provider = "vercel-serverless";
96
- status = "pending";
97
- _token;
98
- _teamId;
99
- _projectName;
100
- _regions;
101
- _maxDuration;
102
- _memory;
103
- _env;
104
- _commandTimeout;
105
- _instructionsOverride;
106
- _secret;
107
- _deploymentUrl = null;
108
- _deploymentId = null;
109
- _protectionBypass = null;
110
- _createdAt = null;
111
- constructor(options = {}) {
112
- super({ name: "VercelServerlessSandbox" });
113
- this.id = `vercel-serverless-sandbox-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
114
- this._token = options.token || process.env.VERCEL_TOKEN || "";
115
- this._teamId = options.teamId;
116
- this._projectName = options.projectName;
117
- this._regions = options.regions ?? ["iad1"];
118
- this._maxDuration = options.maxDuration ?? 60;
119
- this._memory = options.memory ?? 1024;
120
- this._env = options.env ?? {};
121
- this._commandTimeout = options.commandTimeout ?? 55e3;
122
- this._instructionsOverride = options.instructions;
123
- this._secret = crypto.randomUUID();
124
- }
125
- // ---------------------------------------------------------------------------
126
- // Lifecycle
127
- // ---------------------------------------------------------------------------
128
- async start() {
129
- if (this._deploymentUrl) {
130
- return;
131
- }
132
- if (!this._token) {
133
- throw new Error(`${LOG_PREFIX} Missing Vercel API token. Set VERCEL_TOKEN env var or pass token option.`);
134
- }
135
- if (this._deploymentId) {
136
- this.logger.debug(`${LOG_PREFIX} Cleaning up stale deployment ${this._deploymentId} before restarting...`);
137
- try {
138
- const resp = await this._vercelFetch(`/v13/deployments/${this._deploymentId}`, { method: "DELETE" });
139
- if (!resp.ok && resp.status !== 404) {
140
- this.logger.warn(`${LOG_PREFIX} Failed to delete stale deployment: ${resp.status}`);
141
- }
142
- } catch (error) {
143
- this.logger.warn(`${LOG_PREFIX} Error deleting stale deployment:`, error);
144
- }
145
- this._deploymentId = null;
146
- }
147
- this.logger.debug(`${LOG_PREFIX} Deploying executor function...`);
148
- const vercelJson = JSON.stringify({
149
- functions: {
150
- "api/execute.js": {
151
- memory: this._memory,
152
- maxDuration: this._maxDuration
153
- }
154
- },
155
- regions: this._regions
156
- });
157
- const deploymentBody = {
158
- name: this._projectName ?? `mastra-sandbox-${this.id}`,
159
- files: [
160
- {
161
- file: "api/execute.js",
162
- data: getExecutorSource(this._secret, this._env)
163
- },
164
- {
165
- file: "vercel.json",
166
- data: vercelJson
167
- }
168
- ],
169
- projectSettings: {
170
- framework: null
171
- },
172
- target: "production"
173
- };
174
- const createResp = await this._vercelFetch("/v13/deployments", {
175
- method: "POST",
176
- body: JSON.stringify(deploymentBody)
177
- });
178
- if (!createResp.ok) {
179
- const errorBody = await createResp.text();
180
- throw new Error(`${LOG_PREFIX} Failed to create deployment: ${createResp.status} ${errorBody}`);
181
- }
182
- const deployment = await createResp.json();
183
- this._deploymentId = deployment.id;
184
- this.logger.debug(`${LOG_PREFIX} Deployment created: ${deployment.id}, polling for READY...`);
185
- const maxWaitMs = 12e4;
186
- const pollIntervalMs = 3e3;
187
- const deadline = Date.now() + maxWaitMs;
188
- while (Date.now() < deadline) {
189
- const statusResp = await this._vercelFetch(`/v13/deployments/${deployment.id}`);
190
- if (!statusResp.ok) {
191
- throw new Error(`${LOG_PREFIX} Failed to check deployment status: ${statusResp.status}`);
192
- }
193
- const statusBody = await statusResp.json();
194
- if (statusBody.readyState === "READY") {
195
- this._deploymentUrl = `https://${statusBody.url}`;
196
- this._createdAt = /* @__PURE__ */ new Date();
197
- this.logger.debug(`${LOG_PREFIX} Deployment ready: ${this._deploymentUrl}`);
198
- if (deployment.projectId) {
199
- try {
200
- this._protectionBypass = await this._acquireProtectionBypass(deployment.projectId);
201
- } catch {
202
- }
203
- }
204
- try {
205
- await fetch(`${this._deploymentUrl}/api/execute`, {
206
- method: "POST",
207
- headers: this._executorHeaders(),
208
- body: JSON.stringify({ command: "echo", args: ["warm"] })
209
- });
210
- } catch {
211
- }
212
- return;
213
- }
214
- if (statusBody.readyState === "ERROR" || statusBody.readyState === "CANCELED") {
215
- throw new Error(`${LOG_PREFIX} Deployment failed with state: ${statusBody.readyState}`);
216
- }
217
- await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
218
- }
219
- throw new Error(`${LOG_PREFIX} Deployment timed out after ${maxWaitMs}ms`);
220
- }
221
- async stop() {
222
- this._deploymentUrl = null;
223
- }
224
- async destroy() {
225
- if (this._deploymentId) {
226
- try {
227
- const resp = await this._vercelFetch(`/v13/deployments/${this._deploymentId}`, {
228
- method: "DELETE"
229
- });
230
- if (!resp.ok) {
231
- if (resp.status === 404) {
232
- this.logger.debug(`${LOG_PREFIX} Deployment already deleted (404)`);
233
- } else {
234
- this.logger.warn(`${LOG_PREFIX} Failed to delete deployment: ${resp.status}`);
235
- }
236
- }
237
- } catch (error) {
238
- this.logger.warn(`${LOG_PREFIX} Error deleting deployment:`, error);
239
- }
240
- this._deploymentId = null;
241
- }
242
- this._deploymentUrl = null;
243
- this._protectionBypass = null;
244
- }
245
- // ---------------------------------------------------------------------------
246
- // Command Execution
247
- // ---------------------------------------------------------------------------
248
- async executeCommand(command, args, options) {
249
- await this.ensureRunning();
250
- if (!this._deploymentUrl) {
251
- throw new workspace.SandboxNotReadyError(this.id);
252
- }
253
- const fullCommand = args?.length ? `${command} ${args.map((a) => shellQuote(a)).join(" ")}` : command;
254
- this.logger.debug(`${LOG_PREFIX} Executing: ${fullCommand}`);
255
- const body = {
256
- command,
257
- args: args ?? [],
258
- env: options?.env ?? {},
259
- cwd: options?.cwd ?? "/tmp",
260
- timeout: options?.timeout ?? this._commandTimeout
261
- };
262
- const maxRetries = 2;
263
- let lastError = null;
264
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
265
- try {
266
- const resp = await fetch(`${this._deploymentUrl}/api/execute`, {
267
- method: "POST",
268
- headers: this._executorHeaders(),
269
- body: JSON.stringify(body),
270
- signal: options?.abortSignal
271
- });
272
- if ((resp.status === 429 || resp.status === 502 || resp.status === 503) && attempt < maxRetries) {
273
- this.logger.debug(`${LOG_PREFIX} Retryable status ${resp.status}, attempt ${attempt + 1}/${maxRetries}`);
274
- await new Promise((resolve) => setTimeout(resolve, 1e3 * (attempt + 1)));
275
- continue;
276
- }
277
- if (resp.status === 504) {
278
- return {
279
- command: fullCommand,
280
- args,
281
- success: false,
282
- exitCode: 124,
283
- stdout: "",
284
- stderr: "Function execution timed out (504 Gateway Timeout)",
285
- executionTimeMs: options?.timeout ?? this._commandTimeout,
286
- timedOut: true
287
- };
288
- }
289
- if (!resp.ok) {
290
- const errorText = await resp.text();
291
- throw new Error(`${LOG_PREFIX} Execute failed: ${resp.status} ${errorText}`);
292
- }
293
- const result = await resp.json();
294
- if (options?.onStdout && result.stdout) {
295
- options.onStdout(result.stdout);
296
- }
297
- if (options?.onStderr && result.stderr) {
298
- options.onStderr(result.stderr);
299
- }
300
- return {
301
- command: fullCommand,
302
- args,
303
- success: result.success,
304
- exitCode: result.exitCode,
305
- stdout: result.stdout,
306
- stderr: result.stderr,
307
- executionTimeMs: result.executionTimeMs,
308
- timedOut: result.timedOut
309
- };
310
- } catch (error) {
311
- if (error instanceof DOMException && error.name === "AbortError") {
312
- throw error;
313
- }
314
- lastError = error;
315
- if (attempt < maxRetries) {
316
- this.logger.debug(`${LOG_PREFIX} Request error, attempt ${attempt + 1}/${maxRetries}:`, error);
317
- await new Promise((resolve) => setTimeout(resolve, 1e3 * (attempt + 1)));
318
- continue;
319
- }
320
- }
321
- }
322
- throw lastError ?? new Error(`${LOG_PREFIX} executeCommand failed after retries`);
323
- }
324
- // ---------------------------------------------------------------------------
325
- // Info & Instructions
326
- // ---------------------------------------------------------------------------
327
- // Matches the resolveInstructions pattern in packages/core/src/workspace/utils.ts
328
- getInstructions(opts) {
329
- if (this._instructionsOverride === void 0) return this._getDefaultInstructions();
330
- if (typeof this._instructionsOverride === "string") return this._instructionsOverride;
331
- const defaultInstructions = this._getDefaultInstructions();
332
- return this._instructionsOverride({ defaultInstructions, requestContext: opts?.requestContext });
333
- }
334
- _getDefaultInstructions() {
335
- return [
336
- "Vercel serverless sandbox.",
337
- "Limitations:",
338
- "- Stateless: no persistent filesystem between invocations.",
339
- "- No interactive shell or streaming stdin.",
340
- "- No long-running or background processes.",
341
- `- Maximum execution time: ${this._maxDuration} seconds.`,
342
- "- Only /tmp is writable (ephemeral, cleared between invocations).",
343
- "- Shell commands (pipes, builtins) are supported via /bin/sh -c."
344
- ].join("\n");
345
- }
346
- async getInfo() {
347
- return {
348
- id: this.id,
349
- name: this.name,
350
- provider: this.provider,
351
- status: this.status,
352
- createdAt: this._createdAt ?? /* @__PURE__ */ new Date(),
353
- metadata: {
354
- deploymentId: this._deploymentId,
355
- deploymentUrl: this._deploymentUrl,
356
- regions: this._regions,
357
- maxDuration: this._maxDuration,
358
- memory: this._memory
359
- }
360
- };
361
- }
362
- // ---------------------------------------------------------------------------
363
- // Private Helpers
364
- // ---------------------------------------------------------------------------
365
- /**
366
- * Fetch an existing protection bypass token for the project, or create one
367
- * if none exists. Returns the token string, or null if acquisition fails.
368
- */
369
- async _acquireProtectionBypass(projectId) {
370
- const projResp = await this._vercelFetch(`/v9/projects/${projectId}`);
371
- if (projResp.ok) {
372
- const project = await projResp.json();
373
- const existing = project.protectionBypass ? Object.keys(project.protectionBypass)[0] : void 0;
374
- if (existing) {
375
- this.logger.debug(`${LOG_PREFIX} Using existing protection bypass token`);
376
- return existing;
377
- }
378
- }
379
- this.logger.debug(`${LOG_PREFIX} Creating protection bypass token...`);
380
- const createResp = await this._vercelFetch(`/v1/projects/${projectId}/protection-bypass`, {
381
- method: "PATCH",
382
- body: JSON.stringify({})
383
- });
384
- if (createResp.ok) {
385
- const result = await createResp.json();
386
- const created = result.protectionBypass ? Object.keys(result.protectionBypass)[0] : void 0;
387
- if (created) {
388
- this.logger.debug(`${LOG_PREFIX} Protection bypass token created`);
389
- return created;
390
- }
391
- }
392
- this.logger.debug(`${LOG_PREFIX} Could not acquire protection bypass token (project may not require it)`);
393
- return null;
394
- }
395
- _executorHeaders() {
396
- const headers = {
397
- "Content-Type": "application/json",
398
- Authorization: `Bearer ${this._secret}`
399
- };
400
- if (this._protectionBypass) {
401
- headers["x-vercel-protection-bypass"] = this._protectionBypass;
402
- }
403
- return headers;
404
- }
405
- async _vercelFetch(path, options = {}) {
406
- const url = new URL(path, VERCEL_API_BASE);
407
- if (this._teamId) {
408
- url.searchParams.set("teamId", this._teamId);
409
- }
410
- return fetch(url.toString(), {
411
- ...options,
412
- headers: {
413
- "Content-Type": "application/json",
414
- Authorization: `Bearer ${this._token}`,
415
- ...options.headers ?? {}
416
- }
417
- });
418
- }
103
+ var VercelServerlessSandbox = class extends _mastra_core_workspace.MastraSandbox {
104
+ id;
105
+ name = "VercelServerlessSandbox";
106
+ provider = "vercel-serverless";
107
+ status = "pending";
108
+ _token;
109
+ _teamId;
110
+ _projectName;
111
+ _regions;
112
+ _maxDuration;
113
+ _memory;
114
+ _env;
115
+ _commandTimeout;
116
+ _instructionsOverride;
117
+ _secret;
118
+ _deploymentUrl = null;
119
+ _deploymentId = null;
120
+ _protectionBypass = null;
121
+ _createdAt = null;
122
+ constructor(options = {}) {
123
+ super({ name: "VercelServerlessSandbox" });
124
+ this.id = `vercel-serverless-sandbox-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
125
+ this._token = options.token || process.env.VERCEL_TOKEN || "";
126
+ this._teamId = options.teamId;
127
+ this._projectName = options.projectName;
128
+ this._regions = options.regions ?? ["iad1"];
129
+ this._maxDuration = options.maxDuration ?? 60;
130
+ this._memory = options.memory ?? 1024;
131
+ this._env = options.env ?? {};
132
+ this._commandTimeout = options.commandTimeout ?? 55e3;
133
+ this._instructionsOverride = options.instructions;
134
+ this._secret = crypto.randomUUID();
135
+ }
136
+ async start() {
137
+ if (this._deploymentUrl) return;
138
+ if (!this._token) throw new Error(`${LOG_PREFIX$1} Missing Vercel API token. Set VERCEL_TOKEN env var or pass token option.`);
139
+ if (this._deploymentId) {
140
+ this.logger.debug(`${LOG_PREFIX$1} Cleaning up stale deployment ${this._deploymentId} before restarting...`);
141
+ try {
142
+ const resp = await this._vercelFetch(`/v13/deployments/${this._deploymentId}`, { method: "DELETE" });
143
+ if (!resp.ok && resp.status !== 404) this.logger.warn(`${LOG_PREFIX$1} Failed to delete stale deployment: ${resp.status}`);
144
+ } catch (error) {
145
+ this.logger.warn(`${LOG_PREFIX$1} Error deleting stale deployment:`, error);
146
+ }
147
+ this._deploymentId = null;
148
+ }
149
+ this.logger.debug(`${LOG_PREFIX$1} Deploying executor function...`);
150
+ const vercelJson = JSON.stringify({
151
+ functions: { "api/execute.js": {
152
+ memory: this._memory,
153
+ maxDuration: this._maxDuration
154
+ } },
155
+ regions: this._regions
156
+ });
157
+ const deploymentBody = {
158
+ name: this._projectName ?? `mastra-sandbox-${this.id}`,
159
+ files: [{
160
+ file: "api/execute.js",
161
+ data: getExecutorSource(this._secret, this._env)
162
+ }, {
163
+ file: "vercel.json",
164
+ data: vercelJson
165
+ }],
166
+ projectSettings: { framework: null },
167
+ target: "production"
168
+ };
169
+ const createResp = await this._vercelFetch("/v13/deployments", {
170
+ method: "POST",
171
+ body: JSON.stringify(deploymentBody)
172
+ });
173
+ if (!createResp.ok) {
174
+ const errorBody = await createResp.text();
175
+ throw new Error(`${LOG_PREFIX$1} Failed to create deployment: ${createResp.status} ${errorBody}`);
176
+ }
177
+ const deployment = await createResp.json();
178
+ this._deploymentId = deployment.id;
179
+ this.logger.debug(`${LOG_PREFIX$1} Deployment created: ${deployment.id}, polling for READY...`);
180
+ const maxWaitMs = 12e4;
181
+ const pollIntervalMs = 3e3;
182
+ const deadline = Date.now() + maxWaitMs;
183
+ while (Date.now() < deadline) {
184
+ const statusResp = await this._vercelFetch(`/v13/deployments/${deployment.id}`);
185
+ if (!statusResp.ok) throw new Error(`${LOG_PREFIX$1} Failed to check deployment status: ${statusResp.status}`);
186
+ const statusBody = await statusResp.json();
187
+ if (statusBody.readyState === "READY") {
188
+ this._deploymentUrl = `https://${statusBody.url}`;
189
+ this._createdAt = /* @__PURE__ */ new Date();
190
+ this.logger.debug(`${LOG_PREFIX$1} Deployment ready: ${this._deploymentUrl}`);
191
+ if (deployment.projectId) try {
192
+ this._protectionBypass = await this._acquireProtectionBypass(deployment.projectId);
193
+ } catch {}
194
+ try {
195
+ await fetch(`${this._deploymentUrl}/api/execute`, {
196
+ method: "POST",
197
+ headers: this._executorHeaders(),
198
+ body: JSON.stringify({
199
+ command: "echo",
200
+ args: ["warm"]
201
+ })
202
+ });
203
+ } catch {}
204
+ return;
205
+ }
206
+ if (statusBody.readyState === "ERROR" || statusBody.readyState === "CANCELED") throw new Error(`${LOG_PREFIX$1} Deployment failed with state: ${statusBody.readyState}`);
207
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
208
+ }
209
+ throw new Error(`${LOG_PREFIX$1} Deployment timed out after ${maxWaitMs}ms`);
210
+ }
211
+ async stop() {
212
+ this._deploymentUrl = null;
213
+ }
214
+ async destroy() {
215
+ if (this._deploymentId) {
216
+ try {
217
+ const resp = await this._vercelFetch(`/v13/deployments/${this._deploymentId}`, { method: "DELETE" });
218
+ if (!resp.ok) if (resp.status === 404) this.logger.debug(`${LOG_PREFIX$1} Deployment already deleted (404)`);
219
+ else this.logger.warn(`${LOG_PREFIX$1} Failed to delete deployment: ${resp.status}`);
220
+ } catch (error) {
221
+ this.logger.warn(`${LOG_PREFIX$1} Error deleting deployment:`, error);
222
+ }
223
+ this._deploymentId = null;
224
+ }
225
+ this._deploymentUrl = null;
226
+ this._protectionBypass = null;
227
+ }
228
+ async executeCommand(command, args, options) {
229
+ await this.ensureRunning();
230
+ if (!this._deploymentUrl) throw new _mastra_core_workspace.SandboxNotReadyError(this.id);
231
+ const fullCommand = args?.length ? `${command} ${args.map((a) => shellQuote(a)).join(" ")}` : command;
232
+ this.logger.debug(`${LOG_PREFIX$1} Executing: ${fullCommand}`);
233
+ const body = {
234
+ command,
235
+ args: args ?? [],
236
+ env: options?.env ?? {},
237
+ cwd: options?.cwd ?? "/tmp",
238
+ timeout: options?.timeout ?? this._commandTimeout
239
+ };
240
+ const maxRetries = 2;
241
+ let lastError = null;
242
+ for (let attempt = 0; attempt <= maxRetries; attempt++) try {
243
+ const resp = await fetch(`${this._deploymentUrl}/api/execute`, {
244
+ method: "POST",
245
+ headers: this._executorHeaders(),
246
+ body: JSON.stringify(body),
247
+ signal: options?.abortSignal
248
+ });
249
+ if ((resp.status === 429 || resp.status === 502 || resp.status === 503) && attempt < maxRetries) {
250
+ this.logger.debug(`${LOG_PREFIX$1} Retryable status ${resp.status}, attempt ${attempt + 1}/${maxRetries}`);
251
+ await new Promise((resolve) => setTimeout(resolve, 1e3 * (attempt + 1)));
252
+ continue;
253
+ }
254
+ if (resp.status === 504) return {
255
+ command: fullCommand,
256
+ args,
257
+ success: false,
258
+ exitCode: 124,
259
+ stdout: "",
260
+ stderr: "Function execution timed out (504 Gateway Timeout)",
261
+ executionTimeMs: options?.timeout ?? this._commandTimeout,
262
+ timedOut: true
263
+ };
264
+ if (!resp.ok) {
265
+ const errorText = await resp.text();
266
+ throw new Error(`${LOG_PREFIX$1} Execute failed: ${resp.status} ${errorText}`);
267
+ }
268
+ const result = await resp.json();
269
+ if (options?.onStdout && result.stdout) options.onStdout(result.stdout);
270
+ if (options?.onStderr && result.stderr) options.onStderr(result.stderr);
271
+ return {
272
+ command: fullCommand,
273
+ args,
274
+ success: result.success,
275
+ exitCode: result.exitCode,
276
+ stdout: result.stdout,
277
+ stderr: result.stderr,
278
+ executionTimeMs: result.executionTimeMs,
279
+ timedOut: result.timedOut
280
+ };
281
+ } catch (error) {
282
+ if (error instanceof DOMException && error.name === "AbortError") throw error;
283
+ lastError = error;
284
+ if (attempt < maxRetries) {
285
+ this.logger.debug(`${LOG_PREFIX$1} Request error, attempt ${attempt + 1}/${maxRetries}:`, error);
286
+ await new Promise((resolve) => setTimeout(resolve, 1e3 * (attempt + 1)));
287
+ continue;
288
+ }
289
+ }
290
+ throw lastError ?? /* @__PURE__ */ new Error(`${LOG_PREFIX$1} executeCommand failed after retries`);
291
+ }
292
+ getInstructions(opts) {
293
+ if (this._instructionsOverride === void 0) return this._getDefaultInstructions();
294
+ if (typeof this._instructionsOverride === "string") return this._instructionsOverride;
295
+ const defaultInstructions = this._getDefaultInstructions();
296
+ return this._instructionsOverride({
297
+ defaultInstructions,
298
+ requestContext: opts?.requestContext
299
+ });
300
+ }
301
+ _getDefaultInstructions() {
302
+ return [
303
+ "Vercel serverless sandbox.",
304
+ "Limitations:",
305
+ "- Stateless: no persistent filesystem between invocations.",
306
+ "- No interactive shell or streaming stdin.",
307
+ "- No long-running or background processes.",
308
+ `- Maximum execution time: ${this._maxDuration} seconds.`,
309
+ "- Only /tmp is writable (ephemeral, cleared between invocations).",
310
+ "- Shell commands (pipes, builtins) are supported via /bin/sh -c."
311
+ ].join("\n");
312
+ }
313
+ async getInfo() {
314
+ return {
315
+ id: this.id,
316
+ name: this.name,
317
+ provider: this.provider,
318
+ status: this.status,
319
+ createdAt: this._createdAt ?? /* @__PURE__ */ new Date(),
320
+ metadata: {
321
+ deploymentId: this._deploymentId,
322
+ deploymentUrl: this._deploymentUrl,
323
+ regions: this._regions,
324
+ maxDuration: this._maxDuration,
325
+ memory: this._memory
326
+ }
327
+ };
328
+ }
329
+ /**
330
+ * Fetch an existing protection bypass token for the project, or create one
331
+ * if none exists. Returns the token string, or null if acquisition fails.
332
+ */
333
+ async _acquireProtectionBypass(projectId) {
334
+ const projResp = await this._vercelFetch(`/v9/projects/${projectId}`);
335
+ if (projResp.ok) {
336
+ const project = await projResp.json();
337
+ const existing = project.protectionBypass ? Object.keys(project.protectionBypass)[0] : void 0;
338
+ if (existing) {
339
+ this.logger.debug(`${LOG_PREFIX$1} Using existing protection bypass token`);
340
+ return existing;
341
+ }
342
+ }
343
+ this.logger.debug(`${LOG_PREFIX$1} Creating protection bypass token...`);
344
+ const createResp = await this._vercelFetch(`/v1/projects/${projectId}/protection-bypass`, {
345
+ method: "PATCH",
346
+ body: JSON.stringify({})
347
+ });
348
+ if (createResp.ok) {
349
+ const result = await createResp.json();
350
+ const created = result.protectionBypass ? Object.keys(result.protectionBypass)[0] : void 0;
351
+ if (created) {
352
+ this.logger.debug(`${LOG_PREFIX$1} Protection bypass token created`);
353
+ return created;
354
+ }
355
+ }
356
+ this.logger.debug(`${LOG_PREFIX$1} Could not acquire protection bypass token (project may not require it)`);
357
+ return null;
358
+ }
359
+ _executorHeaders() {
360
+ const headers = {
361
+ "Content-Type": "application/json",
362
+ Authorization: `Bearer ${this._secret}`
363
+ };
364
+ if (this._protectionBypass) headers["x-vercel-protection-bypass"] = this._protectionBypass;
365
+ return headers;
366
+ }
367
+ async _vercelFetch(path, options = {}) {
368
+ const url = new URL(path, VERCEL_API_BASE);
369
+ if (this._teamId) url.searchParams.set("teamId", this._teamId);
370
+ return fetch(url.toString(), {
371
+ ...options,
372
+ headers: {
373
+ "Content-Type": "application/json",
374
+ Authorization: `Bearer ${this._token}`,
375
+ ...options.headers ?? {}
376
+ }
377
+ });
378
+ }
419
379
  };
420
-
421
- // src/serverless-provider.ts
422
- var vercelServerlessSandboxProvider = {
423
- id: "vercel-serverless",
424
- name: "Vercel Sandbox (Serverless)",
425
- description: "Serverless sandbox powered by Vercel Functions",
426
- configSchema: {
427
- type: "object",
428
- properties: {
429
- token: { type: "string", description: "Vercel API token" },
430
- teamId: { type: "string", description: "Vercel team ID" },
431
- projectName: { type: "string", description: "Existing Vercel project name" },
432
- regions: {
433
- type: "array",
434
- description: "Deployment regions",
435
- items: { type: "string" },
436
- default: ["iad1"]
437
- },
438
- maxDuration: { type: "number", description: "Function max duration in seconds", default: 60 },
439
- memory: { type: "number", description: "Function memory in MB", default: 1024 },
440
- env: {
441
- type: "object",
442
- description: "Environment variables",
443
- additionalProperties: { type: "string" }
444
- },
445
- commandTimeout: { type: "number", description: "Per-invocation timeout in ms", default: 55e3 }
446
- }
447
- },
448
- createSandbox: (config) => new VercelServerlessSandbox(config)
380
+ //#endregion
381
+ //#region src/serverless-provider.ts
382
+ const vercelServerlessSandboxProvider = {
383
+ id: "vercel-serverless",
384
+ name: "Vercel Sandbox (Serverless)",
385
+ description: "Serverless sandbox powered by Vercel Functions",
386
+ configSchema: {
387
+ type: "object",
388
+ properties: {
389
+ token: {
390
+ type: "string",
391
+ description: "Vercel API token"
392
+ },
393
+ teamId: {
394
+ type: "string",
395
+ description: "Vercel team ID"
396
+ },
397
+ projectName: {
398
+ type: "string",
399
+ description: "Existing Vercel project name"
400
+ },
401
+ regions: {
402
+ type: "array",
403
+ description: "Deployment regions",
404
+ items: { type: "string" },
405
+ default: ["iad1"]
406
+ },
407
+ maxDuration: {
408
+ type: "number",
409
+ description: "Function max duration in seconds",
410
+ default: 60
411
+ },
412
+ memory: {
413
+ type: "number",
414
+ description: "Function memory in MB",
415
+ default: 1024
416
+ },
417
+ env: {
418
+ type: "object",
419
+ description: "Environment variables",
420
+ additionalProperties: { type: "string" }
421
+ },
422
+ commandTimeout: {
423
+ type: "number",
424
+ description: "Per-invocation timeout in ms",
425
+ default: 55e3
426
+ }
427
+ }
428
+ },
429
+ createSandbox: (config) => new VercelServerlessSandbox(config)
449
430
  };
450
- var VercelSandboxProcessHandle = class extends workspace.ProcessHandle {
451
- pid;
452
- _command;
453
- _startTime;
454
- _timeout;
455
- _exitCode;
456
- _waitPromise = null;
457
- _streamingPromise = null;
458
- _killed = false;
459
- constructor(command, startTime, options) {
460
- super(options);
461
- this.pid = command.cmdId;
462
- this._command = command;
463
- this._startTime = startTime;
464
- this._timeout = options?.timeout;
465
- }
466
- get exitCode() {
467
- return this._exitCode;
468
- }
469
- /** @internal Set by the process manager after streaming starts. */
470
- set streamingPromise(p) {
471
- this._streamingPromise = p;
472
- }
473
- async wait() {
474
- if (!this._waitPromise) {
475
- this._waitPromise = this._doWait();
476
- }
477
- return this._waitPromise;
478
- }
479
- async _doWait() {
480
- const finishedPromise = this._command.wait().then((finished) => {
481
- if (this._exitCode === void 0) this._exitCode = finished.exitCode;
482
- }).catch(() => {
483
- if (this._exitCode === void 0) this._exitCode = 1;
484
- });
485
- if (this._timeout) {
486
- let timeoutId;
487
- const timeoutPromise = new Promise((resolve) => {
488
- timeoutId = setTimeout(() => resolve("timeout"), this._timeout);
489
- });
490
- const outcome = await Promise.race([finishedPromise.then(() => "done"), timeoutPromise]);
491
- clearTimeout(timeoutId);
492
- if (outcome === "timeout") {
493
- await this.kill();
494
- this._exitCode = 124;
495
- await this._streamingPromise?.catch(() => {
496
- });
497
- return {
498
- success: false,
499
- exitCode: 124,
500
- stdout: this.stdout,
501
- stderr: this.stderr || `Command timed out after ${this._timeout}ms`,
502
- executionTimeMs: Date.now() - this._startTime,
503
- killed: true,
504
- timedOut: true
505
- };
506
- }
507
- } else {
508
- await finishedPromise;
509
- }
510
- await this._streamingPromise?.catch(() => {
511
- });
512
- if (this._killed) {
513
- return {
514
- success: false,
515
- exitCode: this._exitCode ?? 137,
516
- stdout: this.stdout,
517
- stderr: this.stderr,
518
- executionTimeMs: Date.now() - this._startTime,
519
- killed: true,
520
- timedOut: false
521
- };
522
- }
523
- return {
524
- success: this._exitCode === 0,
525
- exitCode: this._exitCode ?? 1,
526
- stdout: this.stdout,
527
- stderr: this.stderr,
528
- executionTimeMs: Date.now() - this._startTime
529
- };
530
- }
531
- async kill() {
532
- if (this._exitCode !== void 0 && !this._killed) return false;
533
- this._killed = true;
534
- if (this._exitCode === void 0) this._exitCode = 137;
535
- try {
536
- await this._command.kill();
537
- } catch {
538
- }
539
- return true;
540
- }
541
- async sendStdin(_data) {
542
- throw new Error("VercelSandbox does not support sending stdin to running processes.");
543
- }
431
+ //#endregion
432
+ //#region src/microvm/process-manager.ts
433
+ /**
434
+ * Vercel Sandbox (MicroVM) Process Manager
435
+ *
436
+ * Implements SandboxProcessManager for the `@vercel/sandbox` SDK. Each spawn()
437
+ * starts a detached command via `sandbox.runCommand({ detached: true })` and
438
+ * streams its output through the command's async `logs()` iterator.
439
+ *
440
+ * The Vercel Sandbox SDK does not expose a stdin channel for running commands,
441
+ * so `sendStdin()` throws a clear "not supported" error.
442
+ */
443
+ /**
444
+ * Wraps a detached Vercel Sandbox {@link Command} to conform to Mastra's
445
+ * ProcessHandle. Not exported — internal to this module.
446
+ */
447
+ var VercelSandboxProcessHandle = class extends _mastra_core_workspace.ProcessHandle {
448
+ pid;
449
+ _command;
450
+ _startTime;
451
+ _timeout;
452
+ _exitCode;
453
+ _waitPromise = null;
454
+ _streamingPromise = null;
455
+ _killed = false;
456
+ constructor(command, startTime, options) {
457
+ super(options);
458
+ this.pid = command.cmdId;
459
+ this._command = command;
460
+ this._startTime = startTime;
461
+ this._timeout = options?.timeout;
462
+ }
463
+ get exitCode() {
464
+ return this._exitCode;
465
+ }
466
+ /** @internal Set by the process manager after streaming starts. */
467
+ set streamingPromise(p) {
468
+ this._streamingPromise = p;
469
+ }
470
+ async wait() {
471
+ if (!this._waitPromise) this._waitPromise = this._doWait();
472
+ return this._waitPromise;
473
+ }
474
+ async _doWait() {
475
+ const finishedPromise = this._command.wait().then((finished) => {
476
+ if (this._exitCode === void 0) this._exitCode = finished.exitCode;
477
+ }).catch(() => {
478
+ if (this._exitCode === void 0) this._exitCode = 1;
479
+ });
480
+ if (this._timeout) {
481
+ let timeoutId;
482
+ const timeoutPromise = new Promise((resolve) => {
483
+ timeoutId = setTimeout(() => resolve("timeout"), this._timeout);
484
+ });
485
+ const outcome = await Promise.race([finishedPromise.then(() => "done"), timeoutPromise]);
486
+ clearTimeout(timeoutId);
487
+ if (outcome === "timeout") {
488
+ await this.kill();
489
+ this._exitCode = 124;
490
+ await this._streamingPromise?.catch(() => {});
491
+ return {
492
+ success: false,
493
+ exitCode: 124,
494
+ stdout: this.stdout,
495
+ stderr: this.stderr || `Command timed out after ${this._timeout}ms`,
496
+ executionTimeMs: Date.now() - this._startTime,
497
+ killed: true,
498
+ timedOut: true
499
+ };
500
+ }
501
+ } else await finishedPromise;
502
+ await this._streamingPromise?.catch(() => {});
503
+ if (this._killed) return {
504
+ success: false,
505
+ exitCode: this._exitCode ?? 137,
506
+ stdout: this.stdout,
507
+ stderr: this.stderr,
508
+ executionTimeMs: Date.now() - this._startTime,
509
+ killed: true,
510
+ timedOut: false
511
+ };
512
+ return {
513
+ success: this._exitCode === 0,
514
+ exitCode: this._exitCode ?? 1,
515
+ stdout: this.stdout,
516
+ stderr: this.stderr,
517
+ executionTimeMs: Date.now() - this._startTime
518
+ };
519
+ }
520
+ async kill() {
521
+ if (this._exitCode !== void 0 && !this._killed) return false;
522
+ this._killed = true;
523
+ if (this._exitCode === void 0) this._exitCode = 137;
524
+ try {
525
+ await this._command.kill();
526
+ } catch {}
527
+ return true;
528
+ }
529
+ async sendStdin(_data) {
530
+ throw new Error("VercelSandbox does not support sending stdin to running processes.");
531
+ }
532
+ async closeStdin() {
533
+ throw new _mastra_core_workspace.UnsupportedStdinCloseError("VercelSandbox does not support closing stdin for running processes.");
534
+ }
544
535
  };
545
- var VercelSandboxProcessManager = class extends workspace.SandboxProcessManager {
546
- async spawn(command, options = {}) {
547
- const mergedEnv = { ...this.env, ...options.env };
548
- const env = Object.fromEntries(
549
- Object.entries(mergedEnv).filter((entry) => entry[1] !== void 0)
550
- );
551
- const cmd = await this.sandbox.sandbox.runCommand({
552
- cmd: "sh",
553
- args: ["-c", command],
554
- ...options.cwd ? { cwd: options.cwd } : {},
555
- ...Object.keys(env).length ? { env } : {},
556
- detached: true
557
- });
558
- const handle = new VercelSandboxProcessHandle(cmd, Date.now(), options);
559
- const streamingPromise = (async () => {
560
- for await (const log of cmd.logs()) {
561
- if (log.stream === "stdout") handle.emitStdout(log.data);
562
- else handle.emitStderr(log.data);
563
- }
564
- })().catch(() => {
565
- });
566
- handle.streamingPromise = streamingPromise;
567
- this._tracked.set(handle.pid, handle);
568
- return handle;
569
- }
570
- async list() {
571
- const result = [];
572
- for (const [pid, handle] of this._tracked) {
573
- result.push({
574
- pid,
575
- command: handle.command,
576
- running: handle.exitCode === void 0,
577
- exitCode: handle.exitCode
578
- });
579
- }
580
- return result;
581
- }
536
+ /**
537
+ * Vercel Sandbox implementation of SandboxProcessManager. Uses one detached
538
+ * `runCommand` per spawned process.
539
+ */
540
+ var VercelSandboxProcessManager = class extends _mastra_core_workspace.SandboxProcessManager {
541
+ async spawn(command, options = {}) {
542
+ const mergedEnv = {
543
+ ...this.env,
544
+ ...options.env
545
+ };
546
+ const env = Object.fromEntries(Object.entries(mergedEnv).filter((entry) => entry[1] !== void 0));
547
+ const cmd = await this.sandbox.sandbox.runCommand({
548
+ cmd: "sh",
549
+ args: ["-c", command],
550
+ ...options.cwd ? { cwd: options.cwd } : {},
551
+ ...Object.keys(env).length ? { env } : {},
552
+ detached: true
553
+ });
554
+ const handle = new VercelSandboxProcessHandle(cmd, Date.now(), options);
555
+ handle.streamingPromise = (async () => {
556
+ for await (const log of cmd.logs()) if (log.stream === "stdout") handle.emitStdout(log.data);
557
+ else handle.emitStderr(log.data);
558
+ })().catch(() => {});
559
+ this._tracked.set(handle.pid, handle);
560
+ return handle;
561
+ }
562
+ async list() {
563
+ const result = [];
564
+ for (const [pid, handle] of this._tracked) result.push({
565
+ pid,
566
+ command: handle.command,
567
+ running: handle.exitCode === void 0,
568
+ exitCode: handle.exitCode
569
+ });
570
+ return result;
571
+ }
582
572
  };
583
-
584
- // src/microvm/index.ts
585
- var LOG_PREFIX2 = "[VercelSandbox]";
586
- var VercelSandbox = class _VercelSandbox extends workspace.MastraSandbox {
587
- id;
588
- name = "VercelSandbox";
589
- provider = "vercel-sandbox";
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
- };
606
- _sandbox = null;
607
- /** True when `_sandbox` came from a resume-less lookup — `start()` must still resume it. */
608
- _attachedWithoutResume = false;
609
- _createdAt = null;
610
- _sandboxName;
611
- _token;
612
- _teamId;
613
- _projectId;
614
- _runtime;
615
- _timeout;
616
- _vcpus;
617
- _ports;
618
- _env;
619
- _metadata;
620
- _instructionsOverride;
621
- _constructorOptions;
622
- constructor(options = {}) {
623
- super({
624
- ...options,
625
- name: "VercelSandbox",
626
- processes: new VercelSandboxProcessManager({ env: options.env ?? {} })
627
- });
628
- this.id = options.id ?? `vercel-sandbox-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
629
- this._sandboxName = options.sandboxName;
630
- this._token = options.token ?? process.env.VERCEL_TOKEN;
631
- this._teamId = options.teamId ?? process.env.VERCEL_TEAM_ID;
632
- this._projectId = options.projectId ?? process.env.VERCEL_PROJECT_ID;
633
- this._runtime = options.runtime ?? "node24";
634
- this._timeout = options.timeout ?? 3e5;
635
- this._vcpus = options.resources?.vcpus;
636
- this._ports = options.ports;
637
- this._env = options.env ?? {};
638
- this._metadata = options.metadata ?? {};
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
- });
663
- }
664
- /**
665
- * The underlying `@vercel/sandbox` instance.
666
- * Throws if the sandbox has not been started yet.
667
- */
668
- get sandbox() {
669
- if (!this._sandbox) {
670
- throw new workspace.SandboxNotReadyError(this.id);
671
- }
672
- return this._sandbox;
673
- }
674
- // ---------------------------------------------------------------------------
675
- // Lifecycle
676
- // ---------------------------------------------------------------------------
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;
696
- }
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)) {
707
- throw new Error(
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.`
709
- );
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
- }
717
- this.logger.debug(`${LOG_PREFIX2} Creating sandbox...`, { runtime: this._runtime, timeout: this._timeout });
718
- const params = {
719
- runtime: this._runtime,
720
- timeout: this._timeout,
721
- ...this._vcpus ? { resources: { vcpus: this._vcpus } } : {},
722
- ...this._ports?.length ? { ports: this._ports } : {},
723
- ...Object.keys(this._env).length ? { env: this._env } : {},
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;
728
- this._createdAt = /* @__PURE__ */ new Date();
729
- this.logger.debug(`${LOG_PREFIX2} Sandbox ready: ${this._sandbox.name}`);
730
- }
731
- /** Snapshot-stop: the filesystem persists and a named sandbox resumes on the next `start()`. */
732
- async stop() {
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;
740
- }
741
- /** Permanently delete the sandbox and its snapshots. */
742
- async destroy() {
743
- const sandbox = this._sandbox ?? await this.attach();
744
- if (!sandbox) {
745
- return;
746
- }
747
- await sandbox.delete();
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 })));
761
- }
762
- // ---------------------------------------------------------------------------
763
- // Command Execution
764
- // ---------------------------------------------------------------------------
765
- async executeCommand(command, args, options) {
766
- await this.ensureRunning();
767
- const startTime = Date.now();
768
- const fullCommand = args?.length ? `${command} ${args.join(" ")}` : command;
769
- this.logger.debug(`${LOG_PREFIX2} Executing: ${fullCommand}`, { cwd: options?.cwd });
770
- const mergedEnv = { ...this._env, ...options?.env };
771
- const env = Object.fromEntries(
772
- Object.entries(mergedEnv).filter((entry) => entry[1] !== void 0)
773
- );
774
- let timeoutId;
775
- const abortController = new AbortController();
776
- const forwardAbort = () => abortController.abort();
777
- if (options?.abortSignal) {
778
- if (options.abortSignal.aborted) abortController.abort();
779
- else options.abortSignal.addEventListener("abort", forwardAbort, { once: true });
780
- }
781
- const signal = abortController.signal;
782
- const timeoutPromise = options?.timeout ? new Promise((resolve) => {
783
- timeoutId = setTimeout(() => resolve("timeout"), options.timeout);
784
- }) : null;
785
- try {
786
- const commandPromise = this.sandbox.runCommand({
787
- cmd: command,
788
- args: args ?? [],
789
- ...options?.cwd ? { cwd: options.cwd } : {},
790
- ...Object.keys(env).length ? { env } : {},
791
- signal
792
- });
793
- const finished = timeoutPromise ? await Promise.race([commandPromise, timeoutPromise]) : await commandPromise;
794
- if (finished === "timeout") {
795
- abortController.abort();
796
- return {
797
- command: fullCommand,
798
- args,
799
- success: false,
800
- exitCode: 124,
801
- stdout: "",
802
- stderr: `Command timed out after ${options.timeout}ms`,
803
- executionTimeMs: Date.now() - startTime,
804
- timedOut: true
805
- };
806
- }
807
- const [stdout, stderr] = await Promise.all([finished.stdout(), finished.stderr()]);
808
- if (options?.onStdout && stdout) options.onStdout(stdout);
809
- if (options?.onStderr && stderr) options.onStderr(stderr);
810
- return {
811
- command: fullCommand,
812
- args,
813
- success: finished.exitCode === 0,
814
- exitCode: finished.exitCode,
815
- stdout,
816
- stderr,
817
- executionTimeMs: Date.now() - startTime
818
- };
819
- } finally {
820
- if (timeoutId) clearTimeout(timeoutId);
821
- options?.abortSignal?.removeEventListener("abort", forwardAbort);
822
- }
823
- }
824
- // ---------------------------------------------------------------------------
825
- // Info & Instructions
826
- // ---------------------------------------------------------------------------
827
- getInfo() {
828
- const domains = {};
829
- if (this._sandbox && this._ports?.length) {
830
- for (const port of this._ports) {
831
- try {
832
- domains[port] = this._sandbox.domain(port);
833
- } catch {
834
- }
835
- }
836
- }
837
- return {
838
- id: this.id,
839
- name: this.name,
840
- provider: this.provider,
841
- status: this.status,
842
- createdAt: this._createdAt ?? /* @__PURE__ */ new Date(),
843
- metadata: {
844
- ...this._metadata,
845
- sandboxName: this._sandbox?.name,
846
- runtime: this._runtime,
847
- timeout: this._timeout,
848
- ...this._vcpus ? { vcpus: this._vcpus } : {},
849
- ...this._ports?.length ? { ports: this._ports, domains } : {}
850
- }
851
- };
852
- }
853
- // Matches the resolveInstructions pattern in @mastra/core/workspace.
854
- getInstructions(opts) {
855
- if (this._instructionsOverride === void 0) return this._getDefaultInstructions();
856
- if (typeof this._instructionsOverride === "string") return this._instructionsOverride;
857
- const defaultInstructions = this._getDefaultInstructions();
858
- return this._instructionsOverride({ defaultInstructions, requestContext: opts?.requestContext });
859
- }
860
- _getDefaultInstructions() {
861
- return [
862
- "Vercel Sandbox: an ephemeral Firecracker MicroVM running Amazon Linux 2023.",
863
- `- Runtime: ${this._runtime}. Working directory defaults to /vercel/sandbox.`,
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.",
865
- "- Runs as the vercel-sandbox user with sudo access (install packages via dnf).",
866
- `- The sandbox auto-terminates after ${Math.round(this._timeout / 1e3)} seconds.`,
867
- ...this._ports?.length ? [`- Exposed ports: ${this._ports.join(", ")} (reachable via public HTTPS domains).`] : [],
868
- "- Background/long-running processes are supported via the process tools.",
869
- "- Filesystem mounting (FUSE) is not supported."
870
- ].join("\n");
871
- }
573
+ //#endregion
574
+ //#region src/microvm/index.ts
575
+ const LOG_PREFIX = "[VercelSandbox]";
576
+ /**
577
+ * Vercel Sandbox (MicroVM) provider for Mastra workspaces.
578
+ *
579
+ * @example Basic usage
580
+ * ```typescript
581
+ * import { Workspace } from '@mastra/core/workspace';
582
+ * import { VercelSandbox } from '@mastra/vercel';
583
+ *
584
+ * const workspace = new Workspace({
585
+ * sandbox: new VercelSandbox({ runtime: 'node24', timeout: 600_000 }),
586
+ * });
587
+ *
588
+ * const result = await workspace.sandbox.executeCommand('node', ['--version']);
589
+ * ```
590
+ */
591
+ var VercelSandbox = class VercelSandbox extends _mastra_core_workspace.MastraSandbox {
592
+ id;
593
+ name = "VercelSandbox";
594
+ provider = "vercel-sandbox";
595
+ status = "pending";
596
+ /**
597
+ * Networking capability: public HTTPS URLs for exposed ports.
598
+ * A port must be declared in `ports` at construction time for a URL to exist.
599
+ */
600
+ networking = { getPortUrl: async (port) => {
601
+ const sandbox = this._sandbox ?? await this.attach();
602
+ if (!sandbox) return null;
603
+ try {
604
+ return sandbox.domain(port);
605
+ } catch {
606
+ return null;
607
+ }
608
+ } };
609
+ _sandbox = null;
610
+ /** True when `_sandbox` came from a resume-less lookup — `start()` must still resume it. */
611
+ _attachedWithoutResume = false;
612
+ _createdAt = null;
613
+ _sandboxName;
614
+ _token;
615
+ _teamId;
616
+ _projectId;
617
+ _runtime;
618
+ _timeout;
619
+ _vcpus;
620
+ _ports;
621
+ _env;
622
+ _metadata;
623
+ _instructionsOverride;
624
+ _constructorOptions;
625
+ constructor(options = {}) {
626
+ super({
627
+ ...options,
628
+ name: "VercelSandbox",
629
+ processes: new VercelSandboxProcessManager({ env: options.env ?? {} })
630
+ });
631
+ this.id = options.id ?? `vercel-sandbox-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
632
+ this._sandboxName = options.sandboxName;
633
+ this._token = options.token ?? process.env.VERCEL_TOKEN;
634
+ this._teamId = options.teamId ?? process.env.VERCEL_TEAM_ID;
635
+ this._projectId = options.projectId ?? process.env.VERCEL_PROJECT_ID;
636
+ this._runtime = options.runtime ?? "node24";
637
+ this._timeout = options.timeout ?? 3e5;
638
+ this._vcpus = options.resources?.vcpus;
639
+ this._ports = options.ports;
640
+ this._env = options.env ?? {};
641
+ this._metadata = options.metadata ?? {};
642
+ this._instructionsOverride = options.instructions;
643
+ this._constructorOptions = { ...options };
644
+ }
645
+ /**
646
+ * Construct a sibling `VercelSandbox` that inherits this sandbox's
647
+ * configuration (credentials, runtime, resources, ports, metadata,
648
+ * instructions) with per-instance overrides.
649
+ *
650
+ * Performs no I/O — the sandbox clone provisions a fresh MicroVM on its
651
+ * own `start()` (Vercel sandboxes cannot be reconnected to, so
652
+ * `options.sandboxId` is ignored). Use it when one configured sandbox acts
653
+ * as the template for a fleet of independent sandboxes (e.g. one per
654
+ * project).
655
+ *
656
+ * `options.idleTimeoutMinutes` maps to the Vercel sandbox `timeout` (ms).
657
+ */
658
+ clone(options = {}) {
659
+ const { id: _id, sandboxName: _sandboxName, ...base } = this._constructorOptions;
660
+ return new VercelSandbox({
661
+ ...base,
662
+ ...options.id !== void 0 && { id: options.id },
663
+ ...options.env !== void 0 && { env: options.env },
664
+ ...options.idleTimeoutMinutes !== void 0 && { timeout: options.idleTimeoutMinutes * 6e4 }
665
+ });
666
+ }
667
+ /**
668
+ * The underlying `@vercel/sandbox` instance.
669
+ * Throws if the sandbox has not been started yet.
670
+ */
671
+ get sandbox() {
672
+ if (!this._sandbox) throw new _mastra_core_workspace.SandboxNotReadyError(this.id);
673
+ return this._sandbox;
674
+ }
675
+ /**
676
+ * Attach to an existing named sandbox WITHOUT resuming it (`resume: false`),
677
+ * so lookups (URL resolution, stop, destroy) never wake a stopped sandbox
678
+ * and start billing. Returns null when unnamed or when no sandbox with this
679
+ * name exists.
680
+ */
681
+ async attach() {
682
+ if (this._sandbox) return this._sandbox;
683
+ if (!this._sandboxName) return null;
684
+ try {
685
+ this._sandbox = await _vercel_sandbox.Sandbox.get({
686
+ name: this._sandboxName,
687
+ resume: false,
688
+ ...this.credentialParams()
689
+ });
690
+ this._attachedWithoutResume = true;
691
+ return this._sandbox;
692
+ } catch {
693
+ return null;
694
+ }
695
+ }
696
+ /**
697
+ * The token is the credential: when provided, the SDK requires teamId and
698
+ * projectId alongside it. Without a token the SDK authenticates via the
699
+ * `VERCEL_OIDC_TOKEN`; a stray teamId/projectId (for example, an exported
700
+ * `VERCEL_TEAM_ID` in the shell) must not break OIDC auth, so it is ignored.
701
+ */
702
+ credentialParams() {
703
+ if (!this._token) return {};
704
+ if (!(this._teamId && this._projectId)) throw new Error(`${LOG_PREFIX} 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.`);
705
+ return {
706
+ token: this._token,
707
+ teamId: this._teamId,
708
+ projectId: this._projectId
709
+ };
710
+ }
711
+ async start() {
712
+ if (this._sandbox && !this._attachedWithoutResume) return;
713
+ this.logger.debug(`${LOG_PREFIX} Creating sandbox...`, {
714
+ runtime: this._runtime,
715
+ timeout: this._timeout
716
+ });
717
+ const params = {
718
+ runtime: this._runtime,
719
+ timeout: this._timeout,
720
+ ...this._vcpus ? { resources: { vcpus: this._vcpus } } : {},
721
+ ...this._ports?.length ? { ports: this._ports } : {},
722
+ ...Object.keys(this._env).length ? { env: this._env } : {},
723
+ ...this.credentialParams()
724
+ };
725
+ this._sandbox = this._sandboxName ? await _vercel_sandbox.Sandbox.getOrCreate({
726
+ ...params,
727
+ name: this._sandboxName
728
+ }) : await _vercel_sandbox.Sandbox.create(params);
729
+ this._attachedWithoutResume = false;
730
+ this._createdAt = /* @__PURE__ */ new Date();
731
+ this.logger.debug(`${LOG_PREFIX} Sandbox ready: ${this._sandbox.name}`);
732
+ }
733
+ /** Snapshot-stop: the filesystem persists and a named sandbox resumes on the next `start()`. */
734
+ async stop() {
735
+ const sandbox = this._sandbox ?? await this.attach();
736
+ if (!sandbox) return;
737
+ await sandbox.stop();
738
+ this._sandbox = null;
739
+ this._attachedWithoutResume = false;
740
+ }
741
+ /** Permanently delete the sandbox and its snapshots. */
742
+ async destroy() {
743
+ const sandbox = this._sandbox ?? await this.attach();
744
+ if (!sandbox) return;
745
+ await sandbox.delete();
746
+ this._sandbox = null;
747
+ this._attachedWithoutResume = false;
748
+ }
749
+ /**
750
+ * Bulk-write files into the sandbox filesystem via the SDK's native upload.
751
+ * Relative paths resolve against /vercel/sandbox.
752
+ */
753
+ async writeFiles(files) {
754
+ await this.ensureRunning();
755
+ await this.sandbox.writeFiles(files.map((f) => ({
756
+ path: f.path,
757
+ content: f.content
758
+ })));
759
+ }
760
+ async executeCommand(command, args, options) {
761
+ await this.ensureRunning();
762
+ const startTime = Date.now();
763
+ const fullCommand = args?.length ? `${command} ${args.join(" ")}` : command;
764
+ this.logger.debug(`${LOG_PREFIX} Executing: ${fullCommand}`, { cwd: options?.cwd });
765
+ const mergedEnv = {
766
+ ...this._env,
767
+ ...options?.env
768
+ };
769
+ const env = Object.fromEntries(Object.entries(mergedEnv).filter((entry) => entry[1] !== void 0));
770
+ let timeoutId;
771
+ const abortController = new AbortController();
772
+ const forwardAbort = () => abortController.abort();
773
+ if (options?.abortSignal) if (options.abortSignal.aborted) abortController.abort();
774
+ else options.abortSignal.addEventListener("abort", forwardAbort, { once: true });
775
+ const signal = abortController.signal;
776
+ const timeoutPromise = options?.timeout ? new Promise((resolve) => {
777
+ timeoutId = setTimeout(() => resolve("timeout"), options.timeout);
778
+ }) : null;
779
+ try {
780
+ const commandPromise = this.sandbox.runCommand({
781
+ cmd: command,
782
+ args: args ?? [],
783
+ ...options?.cwd ? { cwd: options.cwd } : {},
784
+ ...Object.keys(env).length ? { env } : {},
785
+ signal
786
+ });
787
+ const finished = timeoutPromise ? await Promise.race([commandPromise, timeoutPromise]) : await commandPromise;
788
+ if (finished === "timeout") {
789
+ abortController.abort();
790
+ return {
791
+ command: fullCommand,
792
+ args,
793
+ success: false,
794
+ exitCode: 124,
795
+ stdout: "",
796
+ stderr: `Command timed out after ${options.timeout}ms`,
797
+ executionTimeMs: Date.now() - startTime,
798
+ timedOut: true
799
+ };
800
+ }
801
+ const [stdout, stderr] = await Promise.all([finished.stdout(), finished.stderr()]);
802
+ if (options?.onStdout && stdout) options.onStdout(stdout);
803
+ if (options?.onStderr && stderr) options.onStderr(stderr);
804
+ return {
805
+ command: fullCommand,
806
+ args,
807
+ success: finished.exitCode === 0,
808
+ exitCode: finished.exitCode,
809
+ stdout,
810
+ stderr,
811
+ executionTimeMs: Date.now() - startTime
812
+ };
813
+ } finally {
814
+ if (timeoutId) clearTimeout(timeoutId);
815
+ options?.abortSignal?.removeEventListener("abort", forwardAbort);
816
+ }
817
+ }
818
+ getInfo() {
819
+ const domains = {};
820
+ if (this._sandbox && this._ports?.length) for (const port of this._ports) try {
821
+ domains[port] = this._sandbox.domain(port);
822
+ } catch {}
823
+ return {
824
+ id: this.id,
825
+ name: this.name,
826
+ provider: this.provider,
827
+ status: this.status,
828
+ createdAt: this._createdAt ?? /* @__PURE__ */ new Date(),
829
+ metadata: {
830
+ ...this._metadata,
831
+ sandboxName: this._sandbox?.name,
832
+ runtime: this._runtime,
833
+ timeout: this._timeout,
834
+ ...this._vcpus ? { vcpus: this._vcpus } : {},
835
+ ...this._ports?.length ? {
836
+ ports: this._ports,
837
+ domains
838
+ } : {}
839
+ }
840
+ };
841
+ }
842
+ getInstructions(opts) {
843
+ if (this._instructionsOverride === void 0) return this._getDefaultInstructions();
844
+ if (typeof this._instructionsOverride === "string") return this._instructionsOverride;
845
+ const defaultInstructions = this._getDefaultInstructions();
846
+ return this._instructionsOverride({
847
+ defaultInstructions,
848
+ requestContext: opts?.requestContext
849
+ });
850
+ }
851
+ _getDefaultInstructions() {
852
+ return [
853
+ "Vercel Sandbox: an ephemeral Firecracker MicroVM running Amazon Linux 2023.",
854
+ `- Runtime: ${this._runtime}. Working directory defaults to /vercel/sandbox.`,
855
+ 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.",
856
+ "- Runs as the vercel-sandbox user with sudo access (install packages via dnf).",
857
+ `- The sandbox auto-terminates after ${Math.round(this._timeout / 1e3)} seconds.`,
858
+ ...this._ports?.length ? [`- Exposed ports: ${this._ports.join(", ")} (reachable via public HTTPS domains).`] : [],
859
+ "- Background/long-running processes are supported via the process tools.",
860
+ "- Filesystem mounting (FUSE) is not supported."
861
+ ].join("\n");
862
+ }
872
863
  };
873
-
874
- // src/microvm-provider.ts
875
- var vercelSandboxProvider = {
876
- id: "vercel-sandbox",
877
- name: "Vercel Sandbox (MicroVM)",
878
- description: "Ephemeral Firecracker MicroVM sandbox powered by Vercel Sandbox",
879
- configSchema: {
880
- type: "object",
881
- properties: {
882
- token: { type: "string", description: "Vercel API token (falls back to VERCEL_TOKEN; omit to use OIDC)" },
883
- teamId: { type: "string", description: "Vercel team ID (falls back to VERCEL_TEAM_ID)" },
884
- projectId: { type: "string", description: "Vercel project ID (falls back to VERCEL_PROJECT_ID)" },
885
- runtime: {
886
- type: "string",
887
- description: "Sandbox runtime",
888
- enum: ["node24", "node22", "node26", "python3.13"],
889
- default: "node24"
890
- },
891
- timeout: { type: "number", description: "Auto-terminate timeout in milliseconds", default: 3e5 },
892
- vcpus: { type: "number", description: "Number of vCPUs (2048 MB memory per vCPU)" },
893
- ports: {
894
- type: "array",
895
- description: "Ports to expose (up to 4)",
896
- items: { type: "number" }
897
- },
898
- env: {
899
- type: "object",
900
- description: "Environment variables",
901
- additionalProperties: { type: "string" }
902
- }
903
- }
904
- },
905
- createSandbox: (config) => new VercelSandbox({
906
- token: config.token,
907
- teamId: config.teamId,
908
- projectId: config.projectId,
909
- runtime: config.runtime,
910
- timeout: config.timeout,
911
- ...config.vcpus ? { resources: { vcpus: config.vcpus } } : {},
912
- ports: config.ports,
913
- env: config.env
914
- })
864
+ //#endregion
865
+ //#region src/microvm-provider.ts
866
+ const vercelSandboxProvider = {
867
+ id: "vercel-sandbox",
868
+ name: "Vercel Sandbox (MicroVM)",
869
+ description: "Ephemeral Firecracker MicroVM sandbox powered by Vercel Sandbox",
870
+ configSchema: {
871
+ type: "object",
872
+ properties: {
873
+ token: {
874
+ type: "string",
875
+ description: "Vercel API token (falls back to VERCEL_TOKEN; omit to use OIDC)"
876
+ },
877
+ teamId: {
878
+ type: "string",
879
+ description: "Vercel team ID (falls back to VERCEL_TEAM_ID)"
880
+ },
881
+ projectId: {
882
+ type: "string",
883
+ description: "Vercel project ID (falls back to VERCEL_PROJECT_ID)"
884
+ },
885
+ runtime: {
886
+ type: "string",
887
+ description: "Sandbox runtime",
888
+ enum: [
889
+ "node24",
890
+ "node22",
891
+ "node26",
892
+ "python3.13"
893
+ ],
894
+ default: "node24"
895
+ },
896
+ timeout: {
897
+ type: "number",
898
+ description: "Auto-terminate timeout in milliseconds",
899
+ default: 3e5
900
+ },
901
+ vcpus: {
902
+ type: "number",
903
+ description: "Number of vCPUs (2048 MB memory per vCPU)"
904
+ },
905
+ ports: {
906
+ type: "array",
907
+ description: "Ports to expose (up to 4)",
908
+ items: { type: "number" }
909
+ },
910
+ env: {
911
+ type: "object",
912
+ description: "Environment variables",
913
+ additionalProperties: { type: "string" }
914
+ }
915
+ }
916
+ },
917
+ createSandbox: (config) => new VercelSandbox({
918
+ token: config.token,
919
+ teamId: config.teamId,
920
+ projectId: config.projectId,
921
+ runtime: config.runtime,
922
+ timeout: config.timeout,
923
+ ...config.vcpus ? { resources: { vcpus: config.vcpus } } : {},
924
+ ports: config.ports,
925
+ env: config.env
926
+ })
915
927
  };
916
-
928
+ //#endregion
917
929
  exports.VercelSandbox = VercelSandbox;
918
930
  exports.VercelSandboxProcessManager = VercelSandboxProcessManager;
919
931
  exports.VercelServerlessSandbox = VercelServerlessSandbox;
920
932
  exports.vercelSandboxProvider = vercelSandboxProvider;
921
933
  exports.vercelServerlessSandboxProvider = vercelServerlessSandboxProvider;
922
- //# sourceMappingURL=index.cjs.map
934
+
923
935
  //# sourceMappingURL=index.cjs.map