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