@mastra/platform-workspace 0.0.0-aggregate-trace-20261015182851

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 ADDED
@@ -0,0 +1,2712 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region \0rolldown/runtime.js
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
+ get: ((k) => from[k]).bind(null, key),
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
+ value: mod,
21
+ enumerable: true
22
+ }) : target, mod));
23
+ //#endregion
24
+ let buffer = require("buffer");
25
+ let path = require("path");
26
+ path = __toESM(path, 1);
27
+ let _mastra_core_workspace = require("@mastra/core/workspace");
28
+ let crypto = require("crypto");
29
+ let e2b = require("e2b");
30
+ let child_process = require("child_process");
31
+ let util = require("util");
32
+ //#region src/client.ts
33
+ const DEFAULT_PROXY_URL = "https://workspaces.mastra.ai";
34
+ const REGIONAL_PROXY_URLS = {
35
+ us: "https://workspaces.us.mastra.ai",
36
+ eu: "https://workspaces.eu.mastra.ai"
37
+ };
38
+ /**
39
+ * Resolves the workspace proxy URL, preferring an explicit
40
+ * `MASTRA_WORKSPACE_PROXY_URL` override, then a regional replica selected by
41
+ * `MASTRA_PLATFORM_REGION` (case-insensitive `us` or `eu`), then the global
42
+ * default. Unknown region values fall through to the global default.
43
+ */
44
+ function resolveProxyUrl() {
45
+ const override = process.env.MASTRA_WORKSPACE_PROXY_URL?.trim();
46
+ if (override) return override;
47
+ const region = process.env.MASTRA_PLATFORM_REGION?.trim().toLowerCase();
48
+ if (region === "us" || region === "eu") return REGIONAL_PROXY_URLS[region];
49
+ return DEFAULT_PROXY_URL;
50
+ }
51
+ /**
52
+ * Default per-request timeout for calls to the workspace proxy. Applied only
53
+ * when the caller doesn't already pass an `AbortSignal`. Long-running routes
54
+ * (e.g. `POST /sandbox/:id/exec`) pass their own longer signal.
55
+ */
56
+ const DEFAULT_REQUEST_TIMEOUT_MS = 6e4;
57
+ function requireOption(value, name) {
58
+ if (!value) throw new Error(`${name} is required`);
59
+ return value;
60
+ }
61
+ function resolveSandboxProvider(value) {
62
+ const provider = value?.trim() || "e2b";
63
+ if (provider !== "railway" && provider !== "e2b") throw new Error("SANDBOX_PROVIDER must be either \"railway\" or \"e2b\"");
64
+ return provider;
65
+ }
66
+ function resolvePlatformOptions(options) {
67
+ const environmentSandboxProvider = process.env.SANDBOX_PROVIDER?.trim();
68
+ const configuredSandboxProvider = options.sandboxProvider ?? environmentSandboxProvider;
69
+ return {
70
+ accessToken: requireOption(options.accessToken ?? (process.env.MASTRA_PLATFORM_ACCESS_TOKEN?.trim() || process.env.MASTRA_PLATFORM_SECRET_KEY?.trim()), "accessToken"),
71
+ projectId: requireOption(options.projectId ?? process.env.MASTRA_PROJECT_ID, "projectId"),
72
+ actingUserId: options.actingUserId?.trim() || void 0,
73
+ proxyUrl: resolveProxyUrl().replace(/\/$/, ""),
74
+ sandboxProvider: resolveSandboxProvider(configuredSandboxProvider),
75
+ sessionId: options.sessionId,
76
+ threadId: options.threadId,
77
+ fetch: options.fetch ?? fetch
78
+ };
79
+ }
80
+ function parseProxyError(body) {
81
+ if (!body) return void 0;
82
+ let parsed;
83
+ try {
84
+ parsed = JSON.parse(body);
85
+ } catch {
86
+ return;
87
+ }
88
+ if (typeof parsed !== "object" || parsed === null) return void 0;
89
+ const err = parsed.error;
90
+ if (typeof err !== "object" || err === null) return void 0;
91
+ const { message, type } = err;
92
+ if (typeof message !== "string" || typeof type !== "string") return void 0;
93
+ return {
94
+ message,
95
+ type
96
+ };
97
+ }
98
+ var PlatformApiError = class extends Error {
99
+ status;
100
+ body;
101
+ /** Machine-readable proxy error kind (e.g. `not_found`), when the response body matches `{ error: { message, type } }`. */
102
+ code;
103
+ /** Human-readable proxy error message, when the response body matches `{ error: { message, type } }`. */
104
+ proxyMessage;
105
+ constructor(status, body) {
106
+ const parsed = parseProxyError(body);
107
+ const summary = parsed ? `${parsed.type}: ${parsed.message}` : body;
108
+ super(`Platform proxy request failed with ${status}${summary ? `: ${summary}` : ""}`);
109
+ this.name = "PlatformApiError";
110
+ this.status = status;
111
+ this.body = body;
112
+ this.code = parsed?.type;
113
+ this.proxyMessage = parsed?.message;
114
+ }
115
+ };
116
+ var PlatformClient = class {
117
+ accessToken;
118
+ projectId;
119
+ actingUserId;
120
+ proxyUrl;
121
+ sandboxProvider;
122
+ /** Advisory session correlation id — see {@link PlatformClientOptions.sessionId}. */
123
+ sessionId;
124
+ /** Advisory thread correlation id — see {@link PlatformClientOptions.threadId}. */
125
+ threadId;
126
+ fetch;
127
+ constructor(options) {
128
+ const resolved = resolvePlatformOptions(options);
129
+ this.accessToken = resolved.accessToken;
130
+ this.projectId = resolved.projectId;
131
+ this.actingUserId = resolved.actingUserId;
132
+ this.proxyUrl = resolved.proxyUrl;
133
+ this.sandboxProvider = resolved.sandboxProvider;
134
+ this.sessionId = resolved.sessionId;
135
+ this.threadId = resolved.threadId;
136
+ this.fetch = resolved.fetch;
137
+ }
138
+ async request(path, options = {}) {
139
+ return this.requestAtPath(`/${this.sandboxProvider}`, path, options);
140
+ }
141
+ async requestProvider(path, options = {}) {
142
+ return this.requestAtPath(`/${this.sandboxProvider}`, path, options);
143
+ }
144
+ async requestAtPath(providerPath, path, options) {
145
+ const url = new URL(`${this.proxyUrl}/v1${providerPath}/projects/${encodeURIComponent(this.projectId)}${path}`);
146
+ for (const [key, value] of Object.entries(options.query ?? {})) if (value !== void 0) url.searchParams.set(key, String(value));
147
+ const headers = new Headers(options.headers);
148
+ headers.set("authorization", `Bearer ${this.accessToken}`);
149
+ if (this.actingUserId) headers.set("x-acting-user-id", this.actingUserId);
150
+ if (this.sessionId) headers.set("x-mastra-session-id", this.sessionId);
151
+ if (this.threadId) headers.set("x-mastra-thread-id", this.threadId);
152
+ const { query: _query, ...fetchOptions } = options;
153
+ const signal = fetchOptions.signal ?? AbortSignal.timeout(DEFAULT_REQUEST_TIMEOUT_MS);
154
+ const response = await this.fetch(url, {
155
+ ...fetchOptions,
156
+ headers,
157
+ signal
158
+ });
159
+ if (!response.ok) throw new PlatformApiError(response.status, await response.text());
160
+ return response;
161
+ }
162
+ };
163
+ //#endregion
164
+ //#region src/filesystem.ts
165
+ function normalizePath(input) {
166
+ if (!input || input === ".") return "/";
167
+ let normalized = input.startsWith("/") ? input : `/${input}`;
168
+ normalized = path.default.posix.normalize(normalized);
169
+ return normalized === "." ? "/" : normalized;
170
+ }
171
+ function keyFromPath(path$1) {
172
+ const normalized = normalizePath(path$1);
173
+ return normalized === "/" ? "" : normalized.slice(1);
174
+ }
175
+ /**
176
+ * Encode each `/`-delimited segment of an object key with `encodeURIComponent`
177
+ * so reserved URL characters (`?`, `#`, `%`, `&`, `+`, spaces, etc.) are
178
+ * treated as part of the key instead of URL syntax. Kept segment-aware so
179
+ * `/` continues to act as a path separator on the wire.
180
+ */
181
+ function encodeKeyPath(key) {
182
+ return key.split("/").map(encodeURIComponent).join("/");
183
+ }
184
+ function nameFromPath(path$2) {
185
+ const normalized = normalizePath(path$2);
186
+ if (normalized === "/") return "";
187
+ return normalized.slice(normalized.lastIndexOf("/") + 1);
188
+ }
189
+ function contentToBody(content) {
190
+ if (typeof content === "string") return content;
191
+ return buffer.Buffer.from(content);
192
+ }
193
+ function headerDate(headers, name) {
194
+ const value = headers.get(name);
195
+ return value ? new Date(value) : /* @__PURE__ */ new Date(0);
196
+ }
197
+ function headerSize(headers) {
198
+ const value = headers.get("content-length");
199
+ return value ? Number(value) : 0;
200
+ }
201
+ function isNotFound(error) {
202
+ return typeof error === "object" && error !== null && "status" in error && error.status === 404;
203
+ }
204
+ var PlatformFilesystem = class extends _mastra_core_workspace.MastraFilesystem {
205
+ id;
206
+ name = "PlatformFilesystem";
207
+ provider = "platform";
208
+ readOnly;
209
+ displayName;
210
+ icon;
211
+ description;
212
+ status = "pending";
213
+ _client;
214
+ _bucketName;
215
+ _instructionsOverride;
216
+ constructor(options = {}) {
217
+ super({
218
+ ...options,
219
+ name: "PlatformFilesystem"
220
+ });
221
+ this.id = options.id ?? this.generateId();
222
+ this._bucketName = options.bucketName ?? process.env.MASTRA_PLATFORM_BUCKET_NAME ?? "";
223
+ if (!this._bucketName) throw new Error("bucketName is required");
224
+ this.readOnly = options.readOnly;
225
+ this.displayName = options.displayName;
226
+ this.icon = options.icon ?? "cloud";
227
+ this.description = options.description;
228
+ this._instructionsOverride = options.instructions;
229
+ this._client = new PlatformClient(options);
230
+ }
231
+ generateId() {
232
+ return `platform-fs-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
233
+ }
234
+ async readFile(path$3, options) {
235
+ await this.ensureReady();
236
+ let response;
237
+ try {
238
+ response = await this._client.request(`/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(keyFromPath(path$3))}`);
239
+ } catch (error) {
240
+ if (isNotFound(error)) throw new _mastra_core_workspace.FileNotFoundError(path$3);
241
+ throw error;
242
+ }
243
+ const buffer$1 = buffer.Buffer.from(await response.arrayBuffer());
244
+ return options?.encoding ? buffer$1.toString(options.encoding) : buffer$1;
245
+ }
246
+ async writeFile(path$4, content, options) {
247
+ await this.ensureReady();
248
+ if (this.readOnly) throw new _mastra_core_workspace.WorkspaceReadOnlyError("writeFile");
249
+ const headers = {};
250
+ if (options?.mimeType) headers["content-type"] = options.mimeType;
251
+ if (options?.overwrite === false) headers["if-none-match"] = "*";
252
+ try {
253
+ await this._client.request(`/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(keyFromPath(path$4))}`, {
254
+ method: "PUT",
255
+ headers,
256
+ body: contentToBody(content)
257
+ });
258
+ } catch (error) {
259
+ if (typeof error === "object" && error !== null && "status" in error && error.status === 412) throw new _mastra_core_workspace.FileExistsError(path$4);
260
+ throw error;
261
+ }
262
+ }
263
+ /**
264
+ * Append bytes to a file.
265
+ *
266
+ * **Not atomic.** Object storage behind the workspace proxy has no native
267
+ * append or compare-and-swap primitive, so this implementation is a
268
+ * read-modify-write: it reads the current contents, concatenates the new
269
+ * bytes, and PUTs the whole object back. Concurrent `appendFile` calls to
270
+ * the same path can overwrite each other's writes ("last write wins").
271
+ * Use `writeFile` with distinct keys for concurrent writers.
272
+ */
273
+ async appendFile(path$5, content) {
274
+ const existing = await this.exists(path$5) ? await this.readFile(path$5) : buffer.Buffer.alloc(0);
275
+ await this.writeFile(path$5, buffer.Buffer.concat([buffer.Buffer.isBuffer(existing) ? existing : buffer.Buffer.from(existing), buffer.Buffer.from(content)]));
276
+ }
277
+ async deleteFile(path$6, options) {
278
+ await this.ensureReady();
279
+ if (this.readOnly) throw new _mastra_core_workspace.WorkspaceReadOnlyError("deleteFile");
280
+ try {
281
+ await this._client.request(`/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(keyFromPath(path$6))}`, {
282
+ method: "DELETE",
283
+ query: { recursive: options?.recursive }
284
+ });
285
+ } catch (error) {
286
+ if (isNotFound(error) && options?.force) return;
287
+ if (isNotFound(error)) throw new _mastra_core_workspace.FileNotFoundError(path$6);
288
+ throw error;
289
+ }
290
+ }
291
+ async copyFile(src, dest, options) {
292
+ await this.ensureReady();
293
+ if (this.readOnly) throw new _mastra_core_workspace.WorkspaceReadOnlyError("copyFile");
294
+ if (options?.overwrite === false) throw new Error("PlatformFilesystem.copyFile does not support overwrite: false — the proxy always overwrites.");
295
+ await this._client.request(`/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(keyFromPath(src))}`, {
296
+ method: "POST",
297
+ query: { op: "copy" },
298
+ headers: { "content-type": "application/json" },
299
+ body: JSON.stringify({ destination: keyFromPath(dest) })
300
+ });
301
+ }
302
+ async moveFile(src, dest, options) {
303
+ await this.ensureReady();
304
+ if (this.readOnly) throw new _mastra_core_workspace.WorkspaceReadOnlyError("moveFile");
305
+ if (options?.overwrite === false) throw new Error("PlatformFilesystem.moveFile does not support overwrite: false — the proxy always overwrites.");
306
+ await this._client.request(`/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(keyFromPath(src))}`, {
307
+ method: "POST",
308
+ query: { op: "rename" },
309
+ headers: { "content-type": "application/json" },
310
+ body: JSON.stringify({ destination: keyFromPath(dest) })
311
+ });
312
+ }
313
+ async mkdir(path$7, _options) {
314
+ await this.ensureReady();
315
+ if (this.readOnly) throw new _mastra_core_workspace.WorkspaceReadOnlyError("mkdir");
316
+ await this._client.request(`/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(keyFromPath(path$7))}`, {
317
+ method: "POST",
318
+ query: { op: "mkdir" }
319
+ });
320
+ }
321
+ async rmdir(path$8, options) {
322
+ await this.deleteFile(path$8.endsWith("/") ? path$8 : `${path$8}/`, {
323
+ recursive: true,
324
+ force: options?.force
325
+ });
326
+ }
327
+ async readdir(path$9, options) {
328
+ await this.ensureReady();
329
+ const json = await this.listPrefix(keyFromPath(path$9), options?.recursive);
330
+ return [...(json.commonPrefixes ?? []).map((prefix) => ({
331
+ name: nameFromPath(prefix.replace(/\/$/, "")),
332
+ type: "directory"
333
+ })), ...(json.contents ?? []).filter((object) => object.key && !object.key.endsWith("/")).map((object) => ({
334
+ name: nameFromPath(object.key),
335
+ type: "file",
336
+ size: object.size
337
+ }))].filter((entry) => !options?.extension || entry.type === "directory" || matchesExtension(entry.name, options.extension));
338
+ }
339
+ async listPrefix(prefix, recursive) {
340
+ const normalized = prefix.replace(/\/$/, "");
341
+ return await (await this._client.request(`/fs/${encodeURIComponent(this._bucketName)}/`, { query: {
342
+ delimiter: recursive ? void 0 : "/",
343
+ prefix: normalized ? `${normalized}/` : void 0
344
+ } })).json();
345
+ }
346
+ async exists(path$10) {
347
+ try {
348
+ await this.stat(path$10);
349
+ return true;
350
+ } catch (error) {
351
+ if (isNotFound(error) || error instanceof _mastra_core_workspace.FileNotFoundError) return false;
352
+ throw error;
353
+ }
354
+ }
355
+ async stat(path$11) {
356
+ await this.ensureReady();
357
+ const normalized = normalizePath(path$11);
358
+ if (normalized === "/") return {
359
+ name: "",
360
+ path: "/",
361
+ type: "directory",
362
+ size: 0,
363
+ createdAt: /* @__PURE__ */ new Date(0),
364
+ modifiedAt: /* @__PURE__ */ new Date(0)
365
+ };
366
+ let response;
367
+ try {
368
+ response = await this._client.request(`/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(keyFromPath(path$11))}`, { method: "HEAD" });
369
+ } catch (error) {
370
+ if (!isNotFound(error)) throw error;
371
+ const listing = await this.listPrefix(keyFromPath(path$11));
372
+ if (!listing.contents?.length && !listing.commonPrefixes?.length) throw new _mastra_core_workspace.FileNotFoundError(path$11);
373
+ return {
374
+ name: nameFromPath(path$11),
375
+ path: normalized,
376
+ type: "directory",
377
+ size: 0,
378
+ createdAt: /* @__PURE__ */ new Date(0),
379
+ modifiedAt: /* @__PURE__ */ new Date(0)
380
+ };
381
+ }
382
+ return {
383
+ name: nameFromPath(path$11),
384
+ path: normalized,
385
+ type: normalized.endsWith("/") ? "directory" : "file",
386
+ size: headerSize(response.headers),
387
+ createdAt: headerDate(response.headers, "last-modified"),
388
+ modifiedAt: headerDate(response.headers, "last-modified"),
389
+ mimeType: response.headers.get("content-type") ?? void 0
390
+ };
391
+ }
392
+ realpath(path$12) {
393
+ return Promise.resolve(normalizePath(path$12));
394
+ }
395
+ getInstructions(opts) {
396
+ const defaultInstructions = `Platform filesystem backed by Mastra Platform bucket ${this._bucketName}. Use absolute workspace paths.`;
397
+ if (typeof this._instructionsOverride === "function") return this._instructionsOverride({
398
+ defaultInstructions,
399
+ requestContext: opts?.requestContext
400
+ });
401
+ if (typeof this._instructionsOverride === "string") return this._instructionsOverride;
402
+ return defaultInstructions;
403
+ }
404
+ getInfo() {
405
+ return {
406
+ id: this.id,
407
+ name: this.name,
408
+ provider: this.provider,
409
+ status: this.status,
410
+ readOnly: this.readOnly,
411
+ icon: this.icon,
412
+ metadata: {
413
+ bucketName: this._bucketName,
414
+ ...this.displayName && { displayName: this.displayName },
415
+ ...this.description && { description: this.description }
416
+ }
417
+ };
418
+ }
419
+ };
420
+ function matchesExtension(name, extension) {
421
+ return (Array.isArray(extension) ? extension : [extension]).some((ext) => name.endsWith(ext));
422
+ }
423
+ //#endregion
424
+ //#region src/template.ts
425
+ const SERIALIZE_TEMPLATE = Symbol("serializeTemplate");
426
+ const GET_TEMPLATE_BUILD_ENVS = Symbol("getTemplateBuildEnvs");
427
+ const MAX_OPERATIONS = 256;
428
+ const MAX_SERIALIZED_BYTES = 256 * 1024;
429
+ const MAX_STRING_LENGTH = 32 * 1024;
430
+ const MAX_COLLECTION_ITEMS = 512;
431
+ const MAX_FAMILY_LENGTH = 200;
432
+ var SerializableSandboxTemplateBuilder = class SerializableSandboxTemplateBuilder {
433
+ #operations;
434
+ #family;
435
+ #buildEnvs;
436
+ constructor(operations = [], family, buildEnvs = {}) {
437
+ this.#operations = operations;
438
+ this.#family = family;
439
+ this.#buildEnvs = buildEnvs;
440
+ }
441
+ cpuCount(count) {
442
+ return this.#append("cpuCount", [validateResourceValue(count, "count")]);
443
+ }
444
+ memoryMB(memoryMB) {
445
+ return this.#append("memoryMB", [validateResourceValue(memoryMB, "memoryMB")]);
446
+ }
447
+ async build(options = {}) {
448
+ return buildSandboxTemplate(this, options);
449
+ }
450
+ runCmd(command) {
451
+ return this.#append("runCmd", [validateStringOrStrings(command, "command")]);
452
+ }
453
+ setWorkdir(path) {
454
+ return this.#append("setWorkdir", [validateString(path, "path")]);
455
+ }
456
+ setEnvs(envs, options) {
457
+ const copy = validateStringRecord(envs, "envs", "environment variable");
458
+ if ((options === void 0 ? void 0 : validateBooleanOptions(options, ["ephemeral"]))?.ephemeral === true) return new SerializableSandboxTemplateBuilder(this.#operations, this.#family, {
459
+ ...this.#buildEnvs,
460
+ ...copy
461
+ });
462
+ return this.#append("setEnvs", [copy]);
463
+ }
464
+ aptInstall(packages, options) {
465
+ const args = [validateStringOrStrings(packages, "packages")];
466
+ if (options !== void 0) args.push(validateBooleanOptions(options, ["noInstallRecommends", "fixMissing"]));
467
+ return this.#append("aptInstall", args);
468
+ }
469
+ pipInstall(packages, options) {
470
+ return this.#appendOptionalInstall("pipInstall", packages, options, ["g"]);
471
+ }
472
+ npmInstall(packages, options) {
473
+ return this.#appendOptionalInstall("npmInstall", packages, options, ["g", "dev"]);
474
+ }
475
+ withFamily(family) {
476
+ if (typeof family !== "string" || family.length === 0) throw new TypeError("family must be a non-empty string");
477
+ if (family.length > MAX_FAMILY_LENGTH) throw new RangeError(`family cannot exceed ${MAX_FAMILY_LENGTH} characters`);
478
+ assertSerializedSize(this.#operations, family);
479
+ return new SerializableSandboxTemplateBuilder(this.#operations, family, this.#buildEnvs);
480
+ }
481
+ [GET_TEMPLATE_BUILD_ENVS]() {
482
+ return Object.keys(this.#buildEnvs).length > 0 ? { ...this.#buildEnvs } : void 0;
483
+ }
484
+ [SERIALIZE_TEMPLATE]() {
485
+ return {
486
+ schemaVersion: 1,
487
+ operations: this.#operations.map((operation) => ({
488
+ method: operation.method,
489
+ args: cloneJson(operation.args)
490
+ })),
491
+ ...this.#family !== void 0 && { family: this.#family }
492
+ };
493
+ }
494
+ #appendOptionalInstall(method, packages, options, optionKeys) {
495
+ const args = [];
496
+ if (packages !== void 0) args.push(validateStringOrStrings(packages, "packages"));
497
+ if (options !== void 0) {
498
+ if (packages === void 0) args.push(null);
499
+ args.push(validateBooleanOptions(options, optionKeys));
500
+ }
501
+ return this.#append(method, args);
502
+ }
503
+ #append(method, args) {
504
+ if (this.#operations.length >= MAX_OPERATIONS) throw new RangeError(`Sandbox template cannot contain more than ${MAX_OPERATIONS} operations`);
505
+ const operation = {
506
+ method,
507
+ args: cloneJson(args)
508
+ };
509
+ const operations = [...this.#operations, operation];
510
+ assertSerializedSize(operations, this.#family);
511
+ return new SerializableSandboxTemplateBuilder(operations, this.#family, this.#buildEnvs);
512
+ }
513
+ };
514
+ function assertSerializedSize(operations, family) {
515
+ const serialized = JSON.stringify({
516
+ schemaVersion: 1,
517
+ operations,
518
+ ...family !== void 0 && { family }
519
+ });
520
+ if (new TextEncoder().encode(serialized).byteLength > MAX_SERIALIZED_BYTES) throw new RangeError(`Serialized sandbox template cannot exceed ${MAX_SERIALIZED_BYTES} bytes`);
521
+ }
522
+ function Template() {
523
+ return new SerializableSandboxTemplateBuilder();
524
+ }
525
+ function isSandboxTemplateBuilder(value) {
526
+ return value instanceof SerializableSandboxTemplateBuilder;
527
+ }
528
+ function serializeSandboxTemplate(template) {
529
+ if (!isSandboxTemplateBuilder(template)) throw new TypeError("template must be created with Template()");
530
+ return template[SERIALIZE_TEMPLATE]();
531
+ }
532
+ function getSandboxTemplateBuildEnvs(template) {
533
+ if (!isSandboxTemplateBuilder(template)) throw new TypeError("template must be created with Template()");
534
+ return template[GET_TEMPLATE_BUILD_ENVS]();
535
+ }
536
+ async function buildSandboxTemplate(template, options) {
537
+ const environmentId = options.environmentId ?? process.env.MASTRA_ENVIRONMENT_ID;
538
+ if (!environmentId) throw new Error("environmentId is required. Pass it or set MASTRA_ENVIRONMENT_ID.");
539
+ const client = new PlatformClient(options);
540
+ const templateBuildEnvs = getSandboxTemplateBuildEnvs(template);
541
+ return await (await client.requestProvider("/sandbox/templates/builds", {
542
+ method: "POST",
543
+ headers: { "content-type": "application/json" },
544
+ body: JSON.stringify({
545
+ environmentId,
546
+ templateDefinition: serializeSandboxTemplate(template),
547
+ ...templateBuildEnvs !== void 0 && { templateBuildEnvs }
548
+ })
549
+ })).json();
550
+ }
551
+ function validateResourceValue(value, name) {
552
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) throw new TypeError(`${name} must be a positive safe integer`);
553
+ return value;
554
+ }
555
+ function validateString(value, name, allowEmpty = false) {
556
+ if (typeof value !== "string") throw new TypeError(`${name} must be a string`);
557
+ if (!allowEmpty && value.length === 0) throw new TypeError(`${name} must not be empty`);
558
+ if (value.length > MAX_STRING_LENGTH) throw new RangeError(`${name} cannot exceed ${MAX_STRING_LENGTH} characters`);
559
+ return value;
560
+ }
561
+ function validateStringOrStrings(value, name) {
562
+ if (typeof value === "string") return validateString(value, name);
563
+ if (!Array.isArray(value)) throw new TypeError(`${name} must be a string or an array of strings`);
564
+ assertCollectionSize(value.length, name);
565
+ if (value.length === 0) throw new TypeError(`${name} must not be empty`);
566
+ return Array.from(value, (item, index) => validateString(item, `${name}[${index}]`));
567
+ }
568
+ function validateStringRecord(value, name, entryName) {
569
+ assertPlainObject(value, name);
570
+ const entries = Object.entries(value);
571
+ assertCollectionSize(entries.length, name);
572
+ return Object.fromEntries(entries.map(([key, item]) => [validateString(key, `${entryName} name`), validateString(item, `${entryName} ${key}`, true)]));
573
+ }
574
+ function validateBooleanOptions(value, keys) {
575
+ assertPlainObject(value, "options");
576
+ const options = value;
577
+ const unknownKey = Object.keys(options).find((key) => !keys.includes(key));
578
+ if (unknownKey) throw new TypeError(`Unsupported option: ${unknownKey}`);
579
+ const copy = {};
580
+ for (const key of keys) {
581
+ const option = options[key];
582
+ if (option === void 0) continue;
583
+ if (typeof option !== "boolean") throw new TypeError(`${key} must be a boolean`);
584
+ copy[key] = option;
585
+ }
586
+ return copy;
587
+ }
588
+ function assertPlainObject(value, name) {
589
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError(`${name} must be a plain object`);
590
+ const prototype = Object.getPrototypeOf(value);
591
+ if (prototype !== Object.prototype && prototype !== null) throw new TypeError(`${name} must be a plain object`);
592
+ }
593
+ function assertCollectionSize(size, name) {
594
+ if (size > MAX_COLLECTION_ITEMS) throw new RangeError(`${name} cannot contain more than ${MAX_COLLECTION_ITEMS} items`);
595
+ }
596
+ function cloneJson(value) {
597
+ if (Array.isArray(value)) return value.map((item) => cloneJson(item));
598
+ if (typeof value === "object" && value !== null) return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, cloneJson(item)]));
599
+ if (typeof value === "number" && !Number.isFinite(value)) throw new TypeError("Sandbox template values must contain only finite numbers");
600
+ return value;
601
+ }
602
+ //#endregion
603
+ //#region src/direct-exec.ts
604
+ /**
605
+ * Direct exec client — opens Railway's tcp-proxy exec WebSocket directly using
606
+ * a short-lived JWT minted by the workspace proxy's exec-lease endpoint. This
607
+ * removes the platform data plane from the exec stdout/stderr path entirely
608
+ * (see `docs/factory/direct-sandbox-connection.md` in the Platform repo),
609
+ * cutting payload-scaled Cloud Run egress and RTT for commands like
610
+ * `pnpm install` that stream tens of MB of output.
611
+ *
612
+ * The frame protocol below mirrors `connectExecWs()` in `railway@3.5.5`
613
+ * (`workspaces/railway/node_modules/railway/dist/index.js`). The `railway`
614
+ * SDK's version is pinned on both sides (platform + here); a version bump
615
+ * signals the protocol may have drifted and this module must be revisited.
616
+ */
617
+ /** Byte-0 tag on binary WS frames for stdout output. */
618
+ const STDOUT_FRAME = 1;
619
+ /** Byte-0 tag on binary WS frames for stderr output. */
620
+ const STDERR_FRAME = 3;
621
+ /**
622
+ * Upper bound on how long we'll wait for the WebSocket to open when the
623
+ * caller didn't supply a `timeoutMs`. Guards against a stalled TLS/WS
624
+ * handshake leaving the promise unresolved forever. Not applied once the
625
+ * socket has opened — a caller with no timeout has opted in to unbounded
626
+ * command runtime, just not to unbounded connection setup.
627
+ */
628
+ const HANDSHAKE_DEADLINE_MS = 3e4;
629
+ const DEFAULT_WS_FACTORY = (endpoint, subprotocols) => {
630
+ const WS = globalThis.WebSocket;
631
+ if (!WS) throw new Error("Direct exec requires a WebSocket implementation. Node 22+ provides one globally; on older runtimes, pass webSocketFactory explicitly.");
632
+ return new WS(endpoint, subprotocols);
633
+ };
634
+ /**
635
+ * Open the provider exec WebSocket using `lease`, run `command`, and resolve
636
+ * with the accumulated stdout/stderr + exit code. See the module docstring
637
+ * for the wire protocol reference.
638
+ *
639
+ * The client sends `stdin_close` immediately after `init_exec`, matching the
640
+ * SDK's own one-shot exec behavior — we never stream stdin from the caller.
641
+ */
642
+ function execViaLease(lease, options) {
643
+ const factory = options.webSocketFactory ?? DEFAULT_WS_FACTORY;
644
+ const stdoutDecoder = new TextDecoder();
645
+ const stderrDecoder = new TextDecoder();
646
+ return new Promise((resolve) => {
647
+ let stdout = "";
648
+ let stderr = "";
649
+ let exitCode = null;
650
+ let timedOut = false;
651
+ let settled = false;
652
+ let opened = false;
653
+ let closeCode;
654
+ let closeReason;
655
+ let timer;
656
+ let handshakeTimer;
657
+ const settle = () => {
658
+ if (settled) return;
659
+ settled = true;
660
+ if (timer) clearTimeout(timer);
661
+ if (handshakeTimer) clearTimeout(handshakeTimer);
662
+ const stdoutTail = stdoutDecoder.decode();
663
+ if (stdoutTail) {
664
+ stdout += stdoutTail;
665
+ options.onStdout?.(stdoutTail);
666
+ }
667
+ const stderrTail = stderrDecoder.decode();
668
+ if (stderrTail) {
669
+ stderr += stderrTail;
670
+ options.onStderr?.(stderrTail);
671
+ }
672
+ try {
673
+ socket.close(1e3, "");
674
+ } catch {}
675
+ resolve({
676
+ exitCode,
677
+ stdout,
678
+ stderr,
679
+ truncated: false,
680
+ timedOut,
681
+ ...closeCode !== void 0 && { closeCode },
682
+ ...closeReason !== void 0 && { closeReason },
683
+ opened
684
+ });
685
+ };
686
+ if (options.timeoutMs !== void 0 && options.timeoutMs > 0) timer = setTimeout(() => {
687
+ timedOut = true;
688
+ if (exitCode === null) exitCode = 124;
689
+ settle();
690
+ }, options.timeoutMs);
691
+ else handshakeTimer = setTimeout(() => {
692
+ if (!opened) settle();
693
+ }, HANDSHAKE_DEADLINE_MS);
694
+ const socket = factory(lease.wsEndpoint, [lease.subprotocol, lease.jwt]);
695
+ socket.binaryType = "arraybuffer";
696
+ socket.onopen = () => {
697
+ opened = true;
698
+ if (handshakeTimer) {
699
+ clearTimeout(handshakeTimer);
700
+ handshakeTimer = void 0;
701
+ }
702
+ const data = { command: options.command };
703
+ if (options.cwd) data.cwd = options.cwd;
704
+ if (options.env && Object.keys(options.env).length > 0) data.env = options.env;
705
+ socket.send(JSON.stringify({
706
+ type: "init_exec",
707
+ data
708
+ }));
709
+ socket.send(JSON.stringify({ type: "stdin_close" }));
710
+ };
711
+ socket.onmessage = (event) => {
712
+ const { data } = event;
713
+ if (data instanceof ArrayBuffer) handleBinaryFrame(data);
714
+ else if (typeof data === "string") handleTextFrame(data);
715
+ };
716
+ socket.onclose = (event) => {
717
+ closeCode = event.code;
718
+ closeReason = event.reason;
719
+ if (!opened) {
720
+ settle();
721
+ return;
722
+ }
723
+ settle();
724
+ };
725
+ socket.onerror = () => {
726
+ if (settled) return;
727
+ if (!opened) settle();
728
+ };
729
+ function handleBinaryFrame(buffer) {
730
+ const view = new Uint8Array(buffer);
731
+ if (view.length <= 1) return;
732
+ if (view[0] === STDOUT_FRAME) {
733
+ const chunk = stdoutDecoder.decode(view.subarray(1), { stream: true });
734
+ stdout += chunk;
735
+ options.onStdout?.(chunk);
736
+ } else if (view[0] === STDERR_FRAME) {
737
+ const chunk = stderrDecoder.decode(view.subarray(1), { stream: true });
738
+ stderr += chunk;
739
+ options.onStderr?.(chunk);
740
+ }
741
+ }
742
+ function handleTextFrame(text) {
743
+ let frame;
744
+ try {
745
+ frame = JSON.parse(text);
746
+ } catch {
747
+ return;
748
+ }
749
+ if (frame.type === "exit") {
750
+ exitCode = frame.data?.exit_code ?? 0;
751
+ settle();
752
+ }
753
+ }
754
+ });
755
+ }
756
+ //#endregion
757
+ //#region src/e2b-exec.ts
758
+ const E2B_ENVD_VERSION = "0.4.0";
759
+ const execViaE2BLease = async (lease, options) => {
760
+ const stdoutChunks = [];
761
+ const stderrChunks = [];
762
+ const onStdout = (data) => {
763
+ stdoutChunks.push(data);
764
+ options.onStdout?.(data);
765
+ };
766
+ const onStderr = (data) => {
767
+ stderrChunks.push(data);
768
+ options.onStderr?.(data);
769
+ };
770
+ try {
771
+ const result = await new e2b.Sandbox({
772
+ sandboxId: lease.sandboxId,
773
+ envdVersion: E2B_ENVD_VERSION,
774
+ envdAccessToken: lease.jwt,
775
+ sandboxUrl: lease.wsEndpoint,
776
+ validateApiKey: false
777
+ }).commands.run(options.command, {
778
+ cwd: options.cwd,
779
+ envs: options.env,
780
+ timeoutMs: options.timeoutMs,
781
+ onStdout,
782
+ onStderr
783
+ });
784
+ return {
785
+ exitCode: result.exitCode,
786
+ stdout: result.stdout,
787
+ stderr: result.stderr,
788
+ truncated: false,
789
+ timedOut: false,
790
+ opened: true
791
+ };
792
+ } catch (error) {
793
+ if (error instanceof e2b.CommandExitError) return {
794
+ exitCode: error.exitCode,
795
+ stdout: error.stdout,
796
+ stderr: error.stderr,
797
+ truncated: false,
798
+ timedOut: false,
799
+ opened: true
800
+ };
801
+ return {
802
+ exitCode: null,
803
+ stdout: stdoutChunks.join(""),
804
+ stderr: stderrChunks.join(""),
805
+ truncated: false,
806
+ timedOut: error instanceof e2b.TimeoutError,
807
+ closeReason: error instanceof Error ? error.message : String(error),
808
+ opened: true
809
+ };
810
+ }
811
+ };
812
+ //#endregion
813
+ //#region src/private-net-exec.ts
814
+ /**
815
+ * Thrown by {@link execViaPrivateNetwork} when the sidecar returns a non-2xx
816
+ * HTTP response. This is an *application* error, not a transport error — the
817
+ * sidecar is reachable and answered, it just refused the exec. Callers should
818
+ * fall back to the lease path for this one call but MUST NOT invalidate the
819
+ * cached `instanceUrl` (the address is still good).
820
+ */
821
+ var PrivateNetExecHttpError = class extends Error {
822
+ status;
823
+ body;
824
+ constructor(status, body) {
825
+ super(`Sidecar /exec returned ${status}${body ? `: ${body.slice(0, 200)}` : ""}`);
826
+ this.name = "PrivateNetExecHttpError";
827
+ this.status = status;
828
+ this.body = body;
829
+ }
830
+ };
831
+ const DEFAULT_FETCH = (input, init) => {
832
+ const f = globalThis.fetch;
833
+ if (!f) throw new Error("Private-network exec requires a fetch implementation. Node 22+ provides one globally; on older runtimes, pass fetch explicitly.");
834
+ return f(input, init);
835
+ };
836
+ /**
837
+ * Dial `${instanceUrl}/exec` and stream the response, resolving with the
838
+ * accumulated stdout/stderr + exit code.
839
+ *
840
+ * Errors:
841
+ * - Connection failure (DNS, refused, reset) → resolves with
842
+ * `{opened:false, exitCode:null, transportErrorMessage}`. Never throws for
843
+ * transport failures — the shape matches the lease-path result so the
844
+ * caller can treat both transports uniformly.
845
+ * - Non-2xx HTTP response from the sidecar → throws {@link PrivateNetExecHttpError}.
846
+ * Application-level; caller decides whether to fall back.
847
+ * - Stream ends without an `exit` frame → resolves with
848
+ * `{opened:true, exitCode:null}`, matching the lease-path semantics for a
849
+ * mid-stream drop.
850
+ * - `timeoutMs` elapsed → aborts the request, resolves with
851
+ * `{timedOut:true, exitCode:124}`.
852
+ */
853
+ async function execViaPrivateNetwork(instanceUrl, options) {
854
+ const fetchImpl = options.fetch ?? DEFAULT_FETCH;
855
+ const url = `${instanceUrl.replace(/\/$/, "")}/exec`;
856
+ const controller = new AbortController();
857
+ let timedOut = false;
858
+ let timeoutTimer;
859
+ if (options.timeoutMs !== void 0 && options.timeoutMs > 0) timeoutTimer = setTimeout(() => {
860
+ timedOut = true;
861
+ controller.abort();
862
+ }, options.timeoutMs);
863
+ const body = { command: options.command };
864
+ if (options.cwd) body.cwd = options.cwd;
865
+ if (options.env && Object.keys(options.env).length > 0) body.env = options.env;
866
+ if (options.timeoutMs !== void 0 && options.timeoutMs > 0) body.timeoutMs = options.timeoutMs;
867
+ const headers = { "content-type": "application/json" };
868
+ if (options.bearerToken) headers.authorization = `Bearer ${options.bearerToken}`;
869
+ let response;
870
+ try {
871
+ response = await fetchImpl(url, {
872
+ method: "POST",
873
+ headers,
874
+ body: JSON.stringify(body),
875
+ signal: controller.signal
876
+ });
877
+ } catch (error) {
878
+ if (timeoutTimer) clearTimeout(timeoutTimer);
879
+ if (timedOut) return {
880
+ exitCode: 124,
881
+ stdout: "",
882
+ stderr: "",
883
+ timedOut: true,
884
+ opened: false
885
+ };
886
+ return {
887
+ exitCode: null,
888
+ stdout: "",
889
+ stderr: "",
890
+ timedOut: false,
891
+ opened: false,
892
+ transportErrorMessage: error instanceof Error ? error.message : String(error)
893
+ };
894
+ }
895
+ if (!response.ok) {
896
+ if (timeoutTimer) clearTimeout(timeoutTimer);
897
+ const text = await response.text().catch(() => "");
898
+ throw new PrivateNetExecHttpError(response.status, text);
899
+ }
900
+ if (!response.body) {
901
+ if (timeoutTimer) clearTimeout(timeoutTimer);
902
+ return {
903
+ exitCode: null,
904
+ stdout: "",
905
+ stderr: "",
906
+ timedOut: false,
907
+ opened: true,
908
+ status: response.status
909
+ };
910
+ }
911
+ let stdout = "";
912
+ let stderr = "";
913
+ let exitCode = null;
914
+ const decoder = new TextDecoder();
915
+ let buffer = "";
916
+ const handleLine = (line) => {
917
+ if (!line) return;
918
+ let frame;
919
+ try {
920
+ frame = JSON.parse(line);
921
+ } catch {
922
+ return;
923
+ }
924
+ if (!frame || typeof frame !== "object") return;
925
+ if (frame.type === "stdout" && typeof frame.data === "string") {
926
+ stdout += frame.data;
927
+ options.onStdout?.(frame.data);
928
+ } else if (frame.type === "stderr" && typeof frame.data === "string") {
929
+ stderr += frame.data;
930
+ options.onStderr?.(frame.data);
931
+ } else if (frame.type === "exit" && typeof frame.code === "number") exitCode = frame.code;
932
+ };
933
+ try {
934
+ const reader = response.body.getReader();
935
+ while (true) {
936
+ const { value, done } = await reader.read();
937
+ if (done) break;
938
+ buffer += decoder.decode(value, { stream: true });
939
+ let newlineIdx = buffer.indexOf("\n");
940
+ while (newlineIdx !== -1) {
941
+ const line = buffer.slice(0, newlineIdx).trim();
942
+ buffer = buffer.slice(newlineIdx + 1);
943
+ handleLine(line);
944
+ newlineIdx = buffer.indexOf("\n");
945
+ }
946
+ }
947
+ buffer += decoder.decode();
948
+ const trailing = buffer.trim();
949
+ if (trailing) handleLine(trailing);
950
+ } catch (error) {
951
+ if (timeoutTimer) clearTimeout(timeoutTimer);
952
+ if (timedOut) return {
953
+ exitCode: 124,
954
+ stdout,
955
+ stderr,
956
+ timedOut: true,
957
+ opened: true,
958
+ status: response.status
959
+ };
960
+ return {
961
+ exitCode,
962
+ stdout,
963
+ stderr,
964
+ timedOut: false,
965
+ opened: true,
966
+ status: response.status,
967
+ transportErrorMessage: error instanceof Error ? error.message : String(error)
968
+ };
969
+ } finally {
970
+ if (timeoutTimer) clearTimeout(timeoutTimer);
971
+ }
972
+ return {
973
+ exitCode,
974
+ stdout,
975
+ stderr,
976
+ timedOut: false,
977
+ opened: true,
978
+ status: response.status
979
+ };
980
+ }
981
+ //#endregion
982
+ //#region src/sandbox.ts
983
+ /**
984
+ * How long before a lease's stated `expiresAt` we should treat it as
985
+ * expired. Avoids a race where the JWT is valid at cache-hit time but the
986
+ * server rejects it by the time the WebSocket handshake completes.
987
+ */
988
+ const LEASE_REFRESH_MARGIN_MS = 6e4;
989
+ /** Max attempts for `POST /sandbox` when the proxy returns transient 5xx errors. */
990
+ const CREATE_MAX_ATTEMPTS = 3;
991
+ /** Base delay between create retries; multiplied by the attempt number. */
992
+ const CREATE_RETRY_BASE_DELAY_MS = 2e3;
993
+ /**
994
+ * How long to wait for the in-sandbox sidecar's `/health` endpoint to respond
995
+ * before giving up and leaving the address registry unpopulated (execs fall
996
+ * back to the lease path). This bounds the fire-and-forget probe that runs
997
+ * after `start()` resolves; the sandbox is usable immediately — the probe
998
+ * only controls whether early execs go via private-net or lease.
999
+ */
1000
+ const SIDECAR_PROBE_TIMEOUT_MS = 3e4;
1001
+ /** Delay between sidecar probe attempts. */
1002
+ const SIDECAR_PROBE_INTERVAL_MS = 250;
1003
+ /**
1004
+ * How long `executeCommand` waits for the transport to become ready before
1005
+ * falling back to the lease path. This is much shorter than
1006
+ * `SIDECAR_PROBE_TIMEOUT_MS` because we want execs to proceed quickly if
1007
+ * the sidecar is slow to boot — the probe continues in the background and
1008
+ * later execs will use private-net once it succeeds.
1009
+ */
1010
+ const TRANSPORT_READY_WAIT_MS = 5e3;
1011
+ /**
1012
+ * Diagnostic error thrown when the direct-exec WebSocket transport fails
1013
+ * twice in a row (opening handshake refused or socket closed mid-stream
1014
+ * without an `exit` frame). Distinguishes "the sandbox transport is broken"
1015
+ * from "your command failed" so callers can decide whether to retry at a
1016
+ * higher level (e.g. reprovision the sandbox) or surface the error.
1017
+ *
1018
+ * `opened` is `true` when the WebSocket completed its handshake at least
1019
+ * once before closing; `false` when Railway refused the upgrade outright.
1020
+ */
1021
+ var SandboxExecTransportError = class extends Error {
1022
+ sandboxId;
1023
+ command;
1024
+ attempts;
1025
+ opened;
1026
+ closeCode;
1027
+ closeReason;
1028
+ wsEndpoint;
1029
+ constructor(message, diagnostics) {
1030
+ super(message);
1031
+ this.name = "SandboxExecTransportError";
1032
+ this.sandboxId = diagnostics.sandboxId;
1033
+ this.command = diagnostics.command;
1034
+ this.attempts = diagnostics.attempts;
1035
+ this.opened = diagnostics.opened;
1036
+ this.closeCode = diagnostics.closeCode;
1037
+ this.closeReason = diagnostics.closeReason;
1038
+ this.wsEndpoint = diagnostics.wsEndpoint;
1039
+ }
1040
+ };
1041
+ /**
1042
+ * Thrown when `/exec-lease` returns 410 Gone — the sandbox has been destroyed
1043
+ * (Railway destroy, quota reclamation, etc.). The client cannot recover from
1044
+ * this on its own because it does not own the binding store; only the fleet
1045
+ * layer can clear the stale sandbox id and provision a fresh one. Callers
1046
+ * (typically `SandboxFleet`) must catch this and reprovision-and-replay.
1047
+ *
1048
+ * When this is thrown the cached `_lease` and `_sandboxId` on the sandbox
1049
+ * instance are cleared, so the next `ensureRunning()` on a reused instance
1050
+ * will re-provision cleanly.
1051
+ */
1052
+ var SandboxDestroyedError = class extends Error {
1053
+ sandboxId;
1054
+ command;
1055
+ attempts;
1056
+ constructor(message, diagnostics) {
1057
+ super(message);
1058
+ this.name = "SandboxDestroyedError";
1059
+ this.sandboxId = diagnostics.sandboxId;
1060
+ this.command = diagnostics.command;
1061
+ this.attempts = diagnostics.attempts;
1062
+ }
1063
+ };
1064
+ /**
1065
+ * Compose a shell command line from a `command` string and optional `args`.
1066
+ *
1067
+ * IMPORTANT: `command` is treated as a **shell string** and passed to the
1068
+ * remote shell verbatim so callers can use pipes, redirects, and chaining
1069
+ * (`ls -la | grep foo`). This matches the contract of {@link MastraSandbox}
1070
+ * and the local sandbox implementation. `args` are always shell-quoted so
1071
+ * they cannot inject syntax.
1072
+ *
1073
+ * Callers MUST NOT pass untrusted input as `command`. Untrusted values must
1074
+ * be passed via `args`, where they are safely quoted. Passing untrusted
1075
+ * input as `command` allows arbitrary shell syntax execution on the remote
1076
+ * sandbox.
1077
+ */
1078
+ function buildCommand(command, args) {
1079
+ return args?.length ? `${command} ${args.map(shellQuote$2).join(" ")}` : command;
1080
+ }
1081
+ function shellQuote$2(arg) {
1082
+ if (/^[a-zA-Z0-9._\-/=:@]+$/.test(arg)) return arg;
1083
+ return `'${arg.replace(/'/g, `'\\''`)}'`;
1084
+ }
1085
+ var PlatformProcessHandle = class extends _mastra_core_workspace.ProcessHandle {
1086
+ pid;
1087
+ resultPromise;
1088
+ exitCodeValue;
1089
+ constructor(pid, resultPromise, options) {
1090
+ super(options);
1091
+ this.pid = pid;
1092
+ this.resultPromise = resultPromise.then((result) => {
1093
+ this.exitCodeValue = result.exitCode;
1094
+ if (result.stdout) this.emitStdout(result.stdout);
1095
+ if (result.stderr) this.emitStderr(result.stderr);
1096
+ return result;
1097
+ });
1098
+ }
1099
+ get exitCode() {
1100
+ return this.exitCodeValue;
1101
+ }
1102
+ async wait() {
1103
+ return this.resultPromise;
1104
+ }
1105
+ async kill() {
1106
+ throw new Error("Platform sandbox command execution does not support killing individual processes");
1107
+ }
1108
+ async sendStdin() {
1109
+ throw new Error("Platform sandbox command execution does not support stdin");
1110
+ }
1111
+ async closeStdin() {
1112
+ throw new _mastra_core_workspace.UnsupportedStdinCloseError("Platform sandbox command execution does not support closing stdin");
1113
+ }
1114
+ };
1115
+ var PlatformProcessManager = class extends _mastra_core_workspace.SandboxProcessManager {
1116
+ spawnCounter = 0;
1117
+ /**
1118
+ * Spawn a process on the remote sandbox.
1119
+ *
1120
+ * `command` is interpreted as a shell string by the remote shell, matching
1121
+ * the {@link MastraSandbox} contract. See {@link PlatformSandbox.executeCommand}
1122
+ * for the untrusted-input caveat: never pass untrusted values as `command`.
1123
+ */
1124
+ async spawn(command, options = {}) {
1125
+ const handle = new PlatformProcessHandle(`platform-proc-${Date.now().toString(36)}-${(this.spawnCounter++).toString(36)}`, this.sandbox.executeCommand(command, void 0, options), options);
1126
+ this._tracked.set(handle.pid, handle);
1127
+ return handle;
1128
+ }
1129
+ async list() {
1130
+ return Array.from(this._tracked.values()).map((handle) => ({
1131
+ pid: handle.pid,
1132
+ command: handle.command,
1133
+ running: handle.exitCode === void 0,
1134
+ ...handle.exitCode !== void 0 && { exitCode: handle.exitCode }
1135
+ }));
1136
+ }
1137
+ };
1138
+ var PlatformSandbox = class PlatformSandbox extends _mastra_core_workspace.MastraSandbox {
1139
+ id;
1140
+ name = "PlatformSandbox";
1141
+ provider = "platform";
1142
+ status = "pending";
1143
+ /**
1144
+ * Populated from the platform's create/reattach response when the sandbox
1145
+ * booted from a prior member of the same template family or the provider
1146
+ * base template while the requested exact template continues to build in
1147
+ * the background.
1148
+ * `undefined` when the sandbox booted on the exact template (or when no
1149
+ * template was requested). Observability-only; consumers reconcile freshness
1150
+ * in their own runtime setup and reprovision to pick up the ready template
1151
+ * on a later start.
1152
+ */
1153
+ templatePending;
1154
+ /**
1155
+ * The platform's id for the provisioned sandbox, as returned by the create
1156
+ * or reattach response. Persist this to reattach later via the `sandboxId`
1157
+ * option. Undefined until the sandbox has been started in this process; a
1158
+ * `sandboxId` passed to the constructor is only a hint for `start()` and is
1159
+ * not reported here until the proxy confirms it.
1160
+ */
1161
+ get sandboxId() {
1162
+ return this.status === "running" ? this._sandboxId : void 0;
1163
+ }
1164
+ _client;
1165
+ _usesProviderRoutes;
1166
+ _environmentId;
1167
+ _sandboxId;
1168
+ _reattach;
1169
+ _seedCheckpointName;
1170
+ _templateDefinition;
1171
+ _templateBuildEnvs;
1172
+ _template;
1173
+ _templateResolutionInFlight;
1174
+ _idleTimeoutMinutes;
1175
+ _networkIsolation;
1176
+ _env;
1177
+ _timeout;
1178
+ _instructionsOverride;
1179
+ _createdAt = null;
1180
+ _webSocketFactory;
1181
+ _e2bExecRunner;
1182
+ _privateNetFetch;
1183
+ /**
1184
+ * Registry that maps `sandboxId → instanceUrl` for the private-network
1185
+ * exec path. Injected by the composition site via
1186
+ * {@link PlatformSandboxOptions.addressRegistry} and populated by this
1187
+ * class itself in `start()` when the workspace-proxy's create/reattach
1188
+ * response includes an `instanceUrl` field. The registry IS the cache —
1189
+ * there is no per-instance mirror on `PlatformSandbox`, so every exec is
1190
+ * a `Map.get()` (in the default in-process impl) against the live view.
1191
+ * When absent, executes go straight to the lease path with no extra
1192
+ * round-trip.
1193
+ */
1194
+ _addressRegistry;
1195
+ /**
1196
+ * Cached exec lease for this sandbox. `null` before the first exec and
1197
+ * after {@link destroy}. Refreshed when `expiresAt - LEASE_REFRESH_MARGIN_MS < now`
1198
+ * (see {@link _ensureLease}); a lease without a disclosed `expiresAt`
1199
+ * is refreshed on every call.
1200
+ */
1201
+ _lease = null;
1202
+ /**
1203
+ * In-flight mint request; concurrent `_ensureLease` callers on a cold or
1204
+ * near-expiry cache all await this single promise so we don't burn N
1205
+ * `POST /exec-lease` round-trips when the sandbox is doing N parallel execs.
1206
+ * Cleared (regardless of success or failure) when the request settles.
1207
+ */
1208
+ _leaseInFlight = null;
1209
+ /**
1210
+ * True when this sandbox was constructed with a caller-supplied `id` (the
1211
+ * recovery key the proxy hashes into an on-provider checkpoint name).
1212
+ * `captureCheckpoint()` needs this to distinguish "no checkpoint intent"
1213
+ * (auto-generated random id — capture would land under a name no future
1214
+ * boot would look for) from "capture on demand". Cloned sandboxes route
1215
+ * `checkpointName` through `id`, so both entry points set this the same
1216
+ * way.
1217
+ */
1218
+ _hasRecoveryKey;
1219
+ /**
1220
+ * In-flight `captureCheckpoint()` request. Concurrent callers on the same
1221
+ * instance coalesce onto this single promise so we don't burn N `POST
1222
+ * /checkpoint` round-trips when the fleet fires several turn-end captures
1223
+ * before the first one resolves. Cleared when the request settles.
1224
+ */
1225
+ _captureInFlight = null;
1226
+ /**
1227
+ * Generation token for the sidecar probe. Incremented on every `start()`
1228
+ * and on teardown. The probe captures this value when it begins; if the
1229
+ * generation has changed by the time the probe succeeds, the probe skips
1230
+ * the `set()` to avoid re-populating a deleted or superseded sandbox entry.
1231
+ */
1232
+ _probeGeneration = 0;
1233
+ /**
1234
+ * In-flight sidecar probe promise. Concurrent `executeCommand` callers that
1235
+ * arrive before the registry is populated all await this single promise so
1236
+ * we don't fire N independent lease requests during the sidecar boot window.
1237
+ * Once the probe resolves (success or timeout), callers check the registry
1238
+ * and proceed — either via private-net (probe succeeded) or via lease (probe
1239
+ * failed/timed out, but now coalesced via `_leaseInFlight`).
1240
+ */
1241
+ _transportReadyPromise = null;
1242
+ /**
1243
+ * The sidecar address of the most recent `start()`, kept so a timed-out
1244
+ * probe can be restarted by a later exec ({@link _awaitTransportReady})
1245
+ * instead of pinning the sandbox to the lease path for its lifetime.
1246
+ */
1247
+ _probeTarget = null;
1248
+ constructor(options = {}) {
1249
+ super({
1250
+ ...options,
1251
+ name: "PlatformSandbox",
1252
+ processes: new PlatformProcessManager()
1253
+ });
1254
+ this._hasRecoveryKey = options.id !== void 0;
1255
+ this.id = options.id ?? this.generateId();
1256
+ this._client = new PlatformClient(options);
1257
+ this._environmentId = options.environmentId ?? process.env.MASTRA_ENVIRONMENT_ID ?? "";
1258
+ if (!this._environmentId && !options.sandboxId) throw new Error("environmentId is required");
1259
+ this._sandboxId = options.sandboxId;
1260
+ this._reattach = options.reattach ?? "best-effort";
1261
+ this._seedCheckpointName = options.seedCheckpointName;
1262
+ this._usesProviderRoutes = options.template !== void 0;
1263
+ this._template = options.template;
1264
+ this._idleTimeoutMinutes = options.idleTimeoutMinutes;
1265
+ this._networkIsolation = options.networkIsolation;
1266
+ this._env = options.env ?? {};
1267
+ this._timeout = options.timeout;
1268
+ this._instructionsOverride = options.instructions;
1269
+ this._webSocketFactory = options.webSocketFactory;
1270
+ this._e2bExecRunner = options.e2bExecRunner ?? execViaE2BLease;
1271
+ this._privateNetFetch = options.privateNetFetch;
1272
+ this._addressRegistry = options.addressRegistry;
1273
+ }
1274
+ generateId() {
1275
+ return `platform-sandbox-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
1276
+ }
1277
+ _failIfReattachRequired(reason, cause) {
1278
+ if (this._reattach !== "required") return;
1279
+ throw new _mastra_core_workspace.SandboxError(`Platform sandbox ${this._sandboxId} could not be reattached (${reason}); refusing to provision a replacement because reattach is 'required'. Clear the persisted sandboxId to start a fresh sandbox.`, "SANDBOX_REATTACH_FAILED", {
1280
+ provider: "platform",
1281
+ sandboxId: this._sandboxId,
1282
+ logicalId: this.id,
1283
+ reason,
1284
+ ...cause !== void 0 && { cause }
1285
+ });
1286
+ }
1287
+ _request(path, options = {}) {
1288
+ return this._usesProviderRoutes ? this._client.requestProvider(path, options) : this._client.request(path, options);
1289
+ }
1290
+ /**
1291
+ * Construct a sibling {@link PlatformSandbox} that inherits this sandbox's
1292
+ * credentials and defaults (access token, project, environment, network
1293
+ * isolation, timeout, instructions, env, idle timeout) with per-instance
1294
+ * overrides from `options`.
1295
+ *
1296
+ * Performs no I/O and does not require this sandbox to be started — the
1297
+ * returned sandbox is not started and provisions (or reattaches, when
1298
+ * `sandboxId` is set) on its own `start()`. Use it when one configured
1299
+ * sandbox acts as the template for a fleet of independent sandboxes
1300
+ * (e.g. one per project).
1301
+ */
1302
+ clone(options = {}) {
1303
+ const id = options.id ?? options.checkpointName;
1304
+ const seedCheckpointName = options.seedCheckpointName ?? (this._client.sandboxProvider === "e2b" ? options.checkpointName : void 0) ?? this._seedCheckpointName;
1305
+ const clone = new PlatformSandbox({
1306
+ ...id !== void 0 && { id },
1307
+ accessToken: this._client.accessToken,
1308
+ projectId: this._client.projectId,
1309
+ ...this._usesProviderRoutes || this._client.sandboxProvider !== "railway" ? { sandboxProvider: this._client.sandboxProvider } : {},
1310
+ actingUserId: options.actingUserId ?? this._client.actingUserId,
1311
+ ...this._client.sessionId !== void 0 && { sessionId: this._client.sessionId },
1312
+ ...this._client.threadId !== void 0 && { threadId: this._client.threadId },
1313
+ fetch: this._client.fetch,
1314
+ environmentId: this._environmentId,
1315
+ ...options.sandboxId !== void 0 && { sandboxId: options.sandboxId },
1316
+ reattach: this._reattach,
1317
+ ...seedCheckpointName !== void 0 && { seedCheckpointName },
1318
+ ...this._template !== void 0 && { template: this._template },
1319
+ idleTimeoutMinutes: options.idleTimeoutMinutes ?? this._idleTimeoutMinutes,
1320
+ ...this._networkIsolation !== void 0 && { networkIsolation: this._networkIsolation },
1321
+ env: options.env ?? this._env,
1322
+ ...this._timeout !== void 0 && { timeout: this._timeout },
1323
+ ...this._instructionsOverride !== void 0 && { instructions: this._instructionsOverride },
1324
+ ...this._webSocketFactory !== void 0 && { webSocketFactory: this._webSocketFactory },
1325
+ e2bExecRunner: this._e2bExecRunner,
1326
+ ...this._privateNetFetch !== void 0 && { privateNetFetch: this._privateNetFetch },
1327
+ ...this._addressRegistry !== void 0 && { addressRegistry: this._addressRegistry }
1328
+ });
1329
+ clone._templateDefinition = this._templateDefinition ? structuredClone(this._templateDefinition) : void 0;
1330
+ clone._templateBuildEnvs = this._templateBuildEnvs ? { ...this._templateBuildEnvs } : void 0;
1331
+ return clone;
1332
+ }
1333
+ /**
1334
+ * Start the sandbox: reattach to a known provider `sandboxId` when one is
1335
+ * set and still live, otherwise provision a fresh sandbox via the proxy.
1336
+ *
1337
+ * Concurrent-caller coalescing lives in the `MastraSandbox` base class
1338
+ * (constructor-wrapped `start()`): joined callers share one attempt and
1339
+ * observe its result; the in-flight slot is cleared on settle so a failed
1340
+ * attempt is not a permanent latch.
1341
+ *
1342
+ * Reports `outcome: 'connected'` on reattach and `outcome: 'created'` on provision.
1343
+ * Note: a `POST /sandbox` seeded from an id-keyed checkpoint is still a
1344
+ * fresh VM and reports `outcome: 'created'`.
1345
+ */
1346
+ async start() {
1347
+ const startedAt = Date.now();
1348
+ if (this._sandboxId) try {
1349
+ const requestStartedAt = Date.now();
1350
+ const response = await this._request(`/sandbox/${encodeURIComponent(this._sandboxId)}`);
1351
+ const requestMs = Date.now() - requestStartedAt;
1352
+ const json = await response.json();
1353
+ if (!json.destroyedAt) {
1354
+ this._createdAt = json.createdAt ? new Date(json.createdAt) : /* @__PURE__ */ new Date();
1355
+ this._populateAddressFromResponse(json);
1356
+ this._logStartComplete(json.id, startedAt, requestMs, "reattach");
1357
+ return { outcome: "connected" };
1358
+ }
1359
+ this._failIfReattachRequired("destroyed");
1360
+ this._sandboxId = void 0;
1361
+ } catch (error) {
1362
+ if (!(error instanceof PlatformApiError) || error.status !== 404 && error.status !== 410) throw error;
1363
+ this._failIfReattachRequired(String(error.status), error);
1364
+ this._sandboxId = void 0;
1365
+ }
1366
+ if (!this._environmentId) throw new Error("environmentId is required");
1367
+ await this._prepareLazyTemplate();
1368
+ const createBody = () => JSON.stringify({
1369
+ id: this.id,
1370
+ seedCheckpointName: this._seedCheckpointName,
1371
+ templateDefinition: this._templateDefinition,
1372
+ templateBuildEnvs: this._templateBuildEnvs,
1373
+ environmentId: this._environmentId,
1374
+ idleTimeoutMinutes: this._idleTimeoutMinutes,
1375
+ networkIsolation: this._networkIsolation,
1376
+ env: this._env
1377
+ });
1378
+ let response;
1379
+ const requestStartedAt = Date.now();
1380
+ for (let attempt = 1;; attempt++) try {
1381
+ response = await this._request("/sandbox", {
1382
+ method: "POST",
1383
+ headers: { "content-type": "application/json" },
1384
+ body: createBody()
1385
+ });
1386
+ break;
1387
+ } catch (error) {
1388
+ if (!(error instanceof PlatformApiError && error.status >= 500) || attempt >= CREATE_MAX_ATTEMPTS) throw error;
1389
+ await new Promise((resolve) => setTimeout(resolve, CREATE_RETRY_BASE_DELAY_MS * attempt));
1390
+ }
1391
+ const requestMs = Date.now() - requestStartedAt;
1392
+ const json = await response.json();
1393
+ this._sandboxId = json.id;
1394
+ this._createdAt = json.createdAt ? new Date(json.createdAt) : /* @__PURE__ */ new Date();
1395
+ this.templatePending = json.templatePending;
1396
+ this._populateAddressFromResponse(json);
1397
+ this._logStartComplete(json.id, startedAt, requestMs, "provision");
1398
+ return { outcome: "created" };
1399
+ }
1400
+ async _prepareLazyTemplate() {
1401
+ if (this._templateDefinition !== void 0 || this._template === void 0) return;
1402
+ if (!this._templateResolutionInFlight) {
1403
+ const attempt = this._resolveTemplate();
1404
+ this._templateResolutionInFlight = attempt.finally(() => {
1405
+ this._templateResolutionInFlight = void 0;
1406
+ });
1407
+ }
1408
+ await this._templateResolutionInFlight;
1409
+ }
1410
+ async _resolveTemplate() {
1411
+ try {
1412
+ const resolved = typeof this._template === "function" ? await this._template() : this._template;
1413
+ if (!resolved) return;
1414
+ this._templateDefinition = serializeSandboxTemplate(resolved);
1415
+ this._templateBuildEnvs = getSandboxTemplateBuildEnvs(resolved);
1416
+ } catch (error) {
1417
+ this.logger.warn(`Platform sandbox template resolution failed; using provider default template: ${String(error)}`);
1418
+ }
1419
+ }
1420
+ /**
1421
+ * One timing summary per completed `start()` — the whole
1422
+ * `PlatformSandbox`-visible boot in a single greppable line.
1423
+ *
1424
+ * `requestMs` is the proxy round-trip (`GET /sandbox/:id` on reattach,
1425
+ * `POST /sandbox` including transient-5xx retries on provision) — a black
1426
+ * box from this side that rolls up Railway RPC, sidecar launch, and the
1427
+ * proxy's discovery exec. Sidecar probe cost is intentionally NOT here: the
1428
+ * probe is fire-and-forget and outlives `start()` by design, so its
1429
+ * duration lands on the `platform-workspace probe ok` line instead.
1430
+ */
1431
+ _logStartComplete(sandboxId, startedAt, requestMs, mode) {
1432
+ this.logger.info("platform-workspace start complete", {
1433
+ sandboxId,
1434
+ sessionId: this._client.sessionId,
1435
+ mode,
1436
+ totalMs: Date.now() - startedAt,
1437
+ requestMs,
1438
+ ...mode === "provision" && this._templateDefinition ? {
1439
+ templateHash: templateHash(this._templateDefinition),
1440
+ templateBoot: this.templatePending ? "pending" : "exact",
1441
+ ...this.templatePending ? { pendingTemplateId: this.templatePending.templateId } : {}
1442
+ } : {}
1443
+ });
1444
+ }
1445
+ /**
1446
+ * Copy `response.instanceUrl` into the injected {@link SandboxAddressRegistry}
1447
+ * when both are present. Called from both {@link start} branches (fresh
1448
+ * provision + reattach) with the workspace-proxy response for this sandbox.
1449
+ *
1450
+ * The proxy discovers the IPv6 during `Sandbox.create()` and stores it in
1451
+ * `environment_sandboxes.instance_url`; both the create response and
1452
+ * `GET /sandbox/:id` echo the same field. The runtime does not do any
1453
+ * discovery of its own — it only mirrors the field into an in-process map
1454
+ * so {@link executeCommand} can `Map.get()` before every exec without an
1455
+ * HTTP round-trip.
1456
+ *
1457
+ * `null`/absent `instanceUrl` (proxy discovery failed, or an older proxy
1458
+ * that predates the field) evicts any stale registry address and leaves
1459
+ * executes on the lease path.
1460
+ */
1461
+ _populateAddressFromResponse(json) {
1462
+ if (!this._addressRegistry) return;
1463
+ if (!json.instanceUrl) {
1464
+ this._probeGeneration++;
1465
+ this._probeTarget = null;
1466
+ this._transportReadyPromise = null;
1467
+ this._addressRegistry.delete(json.id);
1468
+ return;
1469
+ }
1470
+ this._addressRegistry.delete(json.id);
1471
+ const generation = ++this._probeGeneration;
1472
+ this._probeTarget = {
1473
+ sandboxId: json.id,
1474
+ instanceUrl: json.instanceUrl
1475
+ };
1476
+ this._transportReadyPromise = this._probeSidecarThenRegister(json.id, json.instanceUrl, generation);
1477
+ }
1478
+ /**
1479
+ * Fire-and-forget probe that polls the sidecar's `/health` endpoint until
1480
+ * it responds, then populates the address registry. Runs detached from
1481
+ * `start()` so sandbox provision latency is unchanged; early execs simply
1482
+ * fall back to the lease path until the probe succeeds.
1483
+ *
1484
+ * If the sidecar never comes up within {@link SIDECAR_PROBE_TIMEOUT_MS},
1485
+ * the registry stays unpopulated, `_transportReadyPromise` is cleared,
1486
+ * and a later {@link _awaitTransportReady} call restarts the probe
1487
+ * instead of pinning this sandbox to the lease path.
1488
+ *
1489
+ * @param generation - The probe generation captured at call time. If this
1490
+ * no longer matches `_probeGeneration` when the probe succeeds, the probe
1491
+ * was superseded by a teardown or a new `start()`, so we skip the `set()`.
1492
+ */
1493
+ async _probeSidecarThenRegister(sandboxId, instanceUrl, generation) {
1494
+ const probeStartedAt = Date.now();
1495
+ const deadline = probeStartedAt + SIDECAR_PROBE_TIMEOUT_MS;
1496
+ const fetchFn = this._privateNetFetch ?? fetch;
1497
+ let attempts = 0;
1498
+ while (Date.now() < deadline) {
1499
+ if (generation !== this._probeGeneration) return;
1500
+ attempts++;
1501
+ try {
1502
+ const res = await fetchFn(`${instanceUrl}/health`, {
1503
+ method: "GET",
1504
+ signal: AbortSignal.timeout(1e3)
1505
+ });
1506
+ const ok = res.ok;
1507
+ await res.body?.cancel().catch(() => {});
1508
+ if (ok) {
1509
+ this.logger.info("platform-workspace probe ok", {
1510
+ sandboxId,
1511
+ sessionId: this._client.sessionId,
1512
+ probeDurationMs: Date.now() - probeStartedAt,
1513
+ attempts
1514
+ });
1515
+ if (generation === this._probeGeneration && this._sandboxId === sandboxId) this._addressRegistry?.set(sandboxId, instanceUrl);
1516
+ return;
1517
+ }
1518
+ } catch {}
1519
+ await new Promise((r) => setTimeout(r, SIDECAR_PROBE_INTERVAL_MS));
1520
+ }
1521
+ if (generation === this._probeGeneration && this._transportReadyPromise) this._transportReadyPromise = null;
1522
+ this.logger.warn("platform-workspace probe timed out", {
1523
+ sandboxId,
1524
+ sessionId: this._client.sessionId,
1525
+ timeoutMs: SIDECAR_PROBE_TIMEOUT_MS,
1526
+ attempts
1527
+ });
1528
+ }
1529
+ /**
1530
+ * Wait for the transport to become ready (sidecar probe succeeds) or time
1531
+ * out. Concurrent callers all await the same probe promise, coalescing the
1532
+ * cold-start storm into a single warmup attempt.
1533
+ *
1534
+ * If no probe is in flight (no registry, or registry already populated),
1535
+ * this returns immediately. After the wait (success or timeout), callers
1536
+ * check the registry and proceed — either via private-net or lease. The
1537
+ * lease path is still coalesced via `_leaseInFlight`, so even if the probe
1538
+ * times out, we only mint one lease for all concurrent execs.
1539
+ */
1540
+ async _awaitTransportReady() {
1541
+ if (this._sandboxId && this._addressRegistry?.get(this._sandboxId)) return;
1542
+ if (!this._transportReadyPromise) {
1543
+ const target = this._probeTarget;
1544
+ if (!target || this._sandboxId !== target.sandboxId) return;
1545
+ const generation = ++this._probeGeneration;
1546
+ this._transportReadyPromise = this._probeSidecarThenRegister(target.sandboxId, target.instanceUrl, generation);
1547
+ }
1548
+ await Promise.race([this._transportReadyPromise, new Promise((r) => setTimeout(r, TRANSPORT_READY_WAIT_MS))]);
1549
+ }
1550
+ /**
1551
+ * Stop this process's use of the sandbox without touching the remote one.
1552
+ *
1553
+ * Nothing is sent to workspace-proxy. The VM keeps running and idles out
1554
+ * under the environment's own idle policy, the recovery checkpoint stays,
1555
+ * and `_sandboxId` is kept so a later `start()` on this instance, or on a
1556
+ * new instance constructed with the same `id` or `sandboxId`, reattaches
1557
+ * instead of provisioning. `Mastra.shutdown()` stops every registered
1558
+ * workspace on SIGINT; releasing the VM here would destroy every live
1559
+ * session on a host restart. Use {@link destroy} to release the VM and
1560
+ * its checkpoint.
1561
+ *
1562
+ * Any in-flight capture is awaited first so the checkpoint reflects the
1563
+ * latest disk state the caller asked for.
1564
+ */
1565
+ async stop() {
1566
+ if (this._captureInFlight) await this._captureInFlight.catch((error) => {
1567
+ this.logger.warn(`stop(): failed to flush in-flight capture before stop:`, error);
1568
+ });
1569
+ this._probeGeneration++;
1570
+ this._probeTarget = null;
1571
+ this._transportReadyPromise = null;
1572
+ this._lease = null;
1573
+ }
1574
+ /**
1575
+ * Destroy the sandbox **and release its recovery checkpoint**.
1576
+ *
1577
+ * Semantic parity with `@mastra/railway` `RailwaySandbox.destroy()`:
1578
+ * cancels any in-flight capture (the checkpoint is about to be deleted
1579
+ * — no reason to burn a capture on state we're releasing), asks the
1580
+ * proxy to delete the checkpoint, then releases the VM. Both remote
1581
+ * operations are best-effort logged failures — a stray checkpoint or a
1582
+ * transient proxy error must not leave the caller with a half-torn-down
1583
+ * sandbox they can't safely retry.
1584
+ *
1585
+ * Railway requires a caller-supplied recovery `id` before it can have a
1586
+ * checkpoint to delete. On E2B the sandbox itself is the persistent thing
1587
+ * (idle sandboxes pause and resume in place), so destroy only kills the
1588
+ * VM; any snapshot a caller captured on purpose is the caller's to manage.
1589
+ */
1590
+ async destroy() {
1591
+ if (!this._sandboxId) return;
1592
+ const destroyedSandboxId = this._sandboxId;
1593
+ this._captureInFlight = null;
1594
+ if (this._hasRecoveryKey && this._client.sandboxProvider !== "e2b") try {
1595
+ await this._request(`/sandbox/${encodeURIComponent(destroyedSandboxId)}/checkpoint`, {
1596
+ method: "DELETE",
1597
+ headers: { "content-type": "application/json" },
1598
+ body: JSON.stringify({ id: this.id })
1599
+ });
1600
+ } catch (error) {
1601
+ if (error instanceof PlatformApiError && (error.status === 404 || error.status === 410)) this.logger.debug(`destroy(): checkpoint already absent upstream (status=${error.status})`);
1602
+ else this.logger.warn(`destroy(): failed to delete checkpoint upstream:`, error);
1603
+ }
1604
+ await this._teardownSandbox();
1605
+ }
1606
+ /**
1607
+ * Release the remote sandbox VM and clear the local state pointing at it.
1608
+ *
1609
+ * Body of {@link destroy}, called after the checkpoint has been released.
1610
+ * The proxy's DELETE route releases the VM (on E2B that kills it), so
1611
+ * only destroy() may reach here; stop() never does.
1612
+ */
1613
+ async _teardownSandbox() {
1614
+ if (!this._sandboxId) return;
1615
+ const destroyedSandboxId = this._sandboxId;
1616
+ this._probeGeneration++;
1617
+ this._probeTarget = null;
1618
+ this._transportReadyPromise = null;
1619
+ await this._request(`/sandbox/${encodeURIComponent(destroyedSandboxId)}`, { method: "DELETE" });
1620
+ this._sandboxId = void 0;
1621
+ this._createdAt = null;
1622
+ this._lease = null;
1623
+ this._addressRegistry?.delete(destroyedSandboxId);
1624
+ }
1625
+ /** Persist the configured recovery checkpoint when available. */
1626
+ async snapshot() {
1627
+ await this.captureCheckpoint();
1628
+ }
1629
+ /** Snapshots persist real checkpoints that can seed future sandboxes. */
1630
+ supportsCheckpoints = true;
1631
+ /**
1632
+ * Capture the sandbox's checkpoint on demand, outside any refresh timer the
1633
+ * workspace-proxy owns internally.
1634
+ *
1635
+ * Intended for callers (e.g. a factory-side scheduler) that want to refresh
1636
+ * the recovery checkpoint at semantic moments — turn end, session-idle,
1637
+ * pre-teardown — rather than only just before the upstream's idle destroy.
1638
+ *
1639
+ * Mirrors the OSS `@mastra/railway` `RailwaySandbox.captureCheckpoint()`
1640
+ * shape so factory can call `sandbox.captureCheckpoint()` uniformly and
1641
+ * branch on `status`/`reason` without knowing which provider is underneath.
1642
+ * Both `captured` and `coalesced` carry the checkpoint name inline so the
1643
+ * caller can persist a session→checkpoint binding atomically with the
1644
+ * awaited capture.
1645
+ *
1646
+ * Skip semantics:
1647
+ * - No caller-supplied `id`: returns `{ status: 'skipped', reason:
1648
+ * 'no-checkpoint-name-configured' }`. An auto-generated random id is
1649
+ * never a meaningful recovery key (no future boot would look for a
1650
+ * checkpoint under it), so capturing would silently produce dead data.
1651
+ * - Not started (no `_sandboxId`): returns `{ status: 'skipped', reason:
1652
+ * 'sandbox-not-running' }` without a round-trip.
1653
+ * - Upstream 410 (workspace-proxy or Railway reports the sandbox is
1654
+ * already destroyed): returns the same `sandbox-not-running` skip so
1655
+ * the discriminant matches the pre-flight case. Local state
1656
+ * (`_sandboxId`, `_lease`, sidecar address) is cleared as a side
1657
+ * effect so the next `start()` provisions fresh instead of reattaching
1658
+ * to a dead id. The diagnostic distinction (pre-flight vs post-hoc)
1659
+ * is preserved in log level: debug for the expected pre-flight skip,
1660
+ * warn for the surprise upstream destroy.
1661
+ *
1662
+ * Concurrent callers on the same instance coalesce onto a single in-flight
1663
+ * `POST /checkpoint` so N simultaneous turn-end fires (e.g. several tabs)
1664
+ * do not each round-trip the proxy. Both the originator and joiners
1665
+ * receive `{ status: 'coalesced', ... }` for the joined result — the
1666
+ * outer contract does not distinguish who started the request, only that
1667
+ * one upstream capture was made.
1668
+ *
1669
+ * Never throws for expected outcomes. Transport failures (5xx, 4xx other
1670
+ * than 410) propagate as {@link PlatformApiError}; a 410 is normalized
1671
+ * to a skip as described above.
1672
+ */
1673
+ async captureCheckpoint() {
1674
+ if (!this._hasRecoveryKey && this._client.sandboxProvider !== "e2b") {
1675
+ this.logger.debug(`captureCheckpoint skipped: no recovery key configured for sandbox ${this._sandboxId ?? "(unstarted)"}`);
1676
+ return {
1677
+ status: "skipped",
1678
+ reason: "no-checkpoint-name-configured"
1679
+ };
1680
+ }
1681
+ if (!this._sandboxId) {
1682
+ this.logger.debug(`captureCheckpoint skipped: sandbox not running (local pre-flight, id=${this.id})`);
1683
+ return {
1684
+ status: "skipped",
1685
+ reason: "sandbox-not-running"
1686
+ };
1687
+ }
1688
+ if (this._captureInFlight) return this._captureInFlight;
1689
+ const sandboxId = this._sandboxId;
1690
+ const capture = this._doCaptureCheckpoint(sandboxId).finally(() => {
1691
+ if (this._captureInFlight === capture) this._captureInFlight = null;
1692
+ });
1693
+ this._captureInFlight = capture;
1694
+ return capture;
1695
+ }
1696
+ /**
1697
+ * The single `POST /checkpoint` attempt behind {@link captureCheckpoint}.
1698
+ *
1699
+ * Split out so the coalescing wrapper can install a shared in-flight
1700
+ * promise without inlining the transport + response-mapping logic.
1701
+ * Joined callers observe `{ status: 'coalesced', ... }` — the initiator
1702
+ * sees the underlying `captured` / `coalesced` / `skipped` result the
1703
+ * proxy returned. Both are legitimate: the OSS mirror uses the same
1704
+ * "initiator sees the truth, joiners see coalesced" split.
1705
+ */
1706
+ async _doCaptureCheckpoint(sandboxId) {
1707
+ let response;
1708
+ try {
1709
+ response = await this._request(`/sandbox/${encodeURIComponent(sandboxId)}/checkpoint`, {
1710
+ method: "POST",
1711
+ headers: { "content-type": "application/json" },
1712
+ body: JSON.stringify({ id: this.id })
1713
+ });
1714
+ } catch (error) {
1715
+ if (error instanceof PlatformApiError && error.status === 410) {
1716
+ this.logger.warn(`captureCheckpoint skipped: sandbox destroyed upstream (proxy 410, sandboxId=${sandboxId})`);
1717
+ this._clearDestroyedState(sandboxId);
1718
+ return {
1719
+ status: "skipped",
1720
+ reason: "sandbox-not-running"
1721
+ };
1722
+ }
1723
+ throw error;
1724
+ }
1725
+ const json = await response.json();
1726
+ if (json.status === "skipped") {
1727
+ this.logger.warn(`captureCheckpoint skipped: sandbox destroyed upstream (proxy reported skipped, sandboxId=${sandboxId})`);
1728
+ this._clearDestroyedState(sandboxId);
1729
+ return {
1730
+ status: "skipped",
1731
+ reason: "sandbox-not-running"
1732
+ };
1733
+ }
1734
+ return {
1735
+ status: json.status,
1736
+ checkpointName: json.checkpointName
1737
+ };
1738
+ }
1739
+ /**
1740
+ * Clear local state that would otherwise let the caller keep exec'ing
1741
+ * against a sandbox the upstream has already destroyed. Mirrors what
1742
+ * `destroy()` does minus the outbound DELETE — the sandbox is already
1743
+ * gone, so all that remains is to stop pointing at it.
1744
+ *
1745
+ * Also resets `status` to `'pending'` so a subsequent `_start()` on this
1746
+ * reused instance re-runs provisioning instead of short-circuiting on
1747
+ * the cached `'running'` state (see `MastraSandbox._start`).
1748
+ */
1749
+ _clearDestroyedState(destroyedSandboxId) {
1750
+ this._probeGeneration++;
1751
+ this._probeTarget = null;
1752
+ this._transportReadyPromise = null;
1753
+ this._sandboxId = void 0;
1754
+ this._createdAt = null;
1755
+ this._lease = null;
1756
+ this._addressRegistry?.delete(destroyedSandboxId);
1757
+ this.status = "pending";
1758
+ }
1759
+ /**
1760
+ * Execute a command on the remote sandbox.
1761
+ *
1762
+ * `command` is a **shell string**: it is concatenated verbatim into the
1763
+ * command line sent to the remote shell, which lets callers use pipes,
1764
+ * redirects, and chaining (`ls -la | grep foo`). This matches the contract
1765
+ * of {@link MastraSandbox} and the local sandbox implementation.
1766
+ *
1767
+ * `args`, when provided, are always shell-quoted so they cannot inject
1768
+ * additional shell syntax.
1769
+ *
1770
+ * Security: callers MUST NOT pass untrusted input as `command`. If any part
1771
+ * of the invocation is derived from an untrusted source, pass it through
1772
+ * `args` (which is safely quoted) or shell-quote it yourself before
1773
+ * inclusion. Untrusted `command` values allow arbitrary shell syntax
1774
+ * execution on the remote sandbox.
1775
+ */
1776
+ async executeCommand(command, args, options) {
1777
+ await this.ensureRunning();
1778
+ if (!this._sandboxId) throw new _mastra_core_workspace.SandboxNotReadyError(this.id);
1779
+ const started = Date.now();
1780
+ const fullCommand = buildCommand(command, args);
1781
+ const effectiveTimeout = options?.timeout ?? this._timeout;
1782
+ const sandboxEnv = this.getEnv();
1783
+ const execCallOptions = Object.keys(sandboxEnv).length > 0 ? {
1784
+ ...options,
1785
+ env: {
1786
+ ...sandboxEnv,
1787
+ ...options?.env
1788
+ }
1789
+ } : options;
1790
+ await this._awaitTransportReady();
1791
+ const instanceUrl = this._addressRegistry?.get(this._sandboxId);
1792
+ if (instanceUrl) {
1793
+ const privateNet = await this._tryExecViaPrivateNetwork(instanceUrl, fullCommand, effectiveTimeout, execCallOptions);
1794
+ if (privateNet) {
1795
+ const privateExit = privateNet.exitCode ?? 124;
1796
+ return {
1797
+ success: privateExit === 0,
1798
+ exitCode: privateExit,
1799
+ stdout: privateNet.stdout,
1800
+ stderr: privateNet.stderr,
1801
+ timedOut: privateNet.timedOut,
1802
+ command: fullCommand,
1803
+ executionTimeMs: Date.now() - started
1804
+ };
1805
+ }
1806
+ }
1807
+ const result = await this._runDirectExec(fullCommand, effectiveTimeout, execCallOptions);
1808
+ const exitCode = result.exitCode ?? 124;
1809
+ return {
1810
+ success: exitCode === 0,
1811
+ exitCode,
1812
+ stdout: result.stdout,
1813
+ stderr: result.stderr,
1814
+ timedOut: result.timedOut,
1815
+ command: fullCommand,
1816
+ executionTimeMs: Date.now() - started
1817
+ };
1818
+ }
1819
+ /**
1820
+ * Run a single exec against the direct-exec transport, with one in-flight
1821
+ * retry on WebSocket transport failure (socket closed without an `exit`
1822
+ * frame and the exec did not time out). The retry mints a fresh lease
1823
+ * — the failure could be a stale JWT — and reopens a new WebSocket.
1824
+ *
1825
+ * Error taxonomy:
1826
+ * - **410 on `/exec-lease`** (either attempt) → the sandbox is gone.
1827
+ * Nulls the cached `_lease` and `_sandboxId` and throws
1828
+ * {@link SandboxDestroyedError}. Callers (typically `SandboxFleet`) must
1829
+ * catch this, clear the stale binding, and reprovision + replay.
1830
+ * - **Persistent transport failure** (both WS attempts close without an
1831
+ * `exit` frame against a live sandbox) → {@link SandboxExecTransportError}
1832
+ * with WebSocket close diagnostics.
1833
+ * - **Other `PlatformApiError`s** (404/500/501) propagate directly.
1834
+ * - **Real command result** (exit code from Railway's exit frame, or
1835
+ * `timedOut: true`) returns normally.
1836
+ *
1837
+ * Returns a result with a real `exitCode` OR `timedOut: true`. Never
1838
+ * returns `{ exitCode: null, timedOut: false }` — that case throws.
1839
+ */
1840
+ /**
1841
+ * Drop undefined values so the result matches the Record<string, string>
1842
+ * shape the exec transports expect (`ExecuteCommandOptions.env` is
1843
+ * NodeJS.ProcessEnv). The sandbox's own env is already merged in by
1844
+ * `executeCommand` before a transport sees these options. Returns undefined
1845
+ * when there is nothing to send.
1846
+ */
1847
+ _execEnv(options) {
1848
+ if (!options?.env) return void 0;
1849
+ const filtered = Object.fromEntries(Object.entries(options.env).filter((entry) => entry[1] !== void 0));
1850
+ return Object.keys(filtered).length > 0 ? filtered : void 0;
1851
+ }
1852
+ async _runDirectExec(fullCommand, effectiveTimeout, options) {
1853
+ const filteredEnv = this._execEnv(options);
1854
+ let lastResult;
1855
+ let lastLease;
1856
+ let attemptsMade = 0;
1857
+ for (let attempt = 0; attempt < 2; attempt++) {
1858
+ if (attempt > 0 && lastLease && this._lease === lastLease) this._lease = null;
1859
+ let lease;
1860
+ try {
1861
+ lease = await this._ensureLease();
1862
+ } catch (error) {
1863
+ if (error instanceof PlatformApiError && error.status === 410) {
1864
+ this._lease = null;
1865
+ const priorSandboxId = this._sandboxId;
1866
+ this._sandboxId = void 0;
1867
+ this.status = "stopped";
1868
+ throw new SandboxDestroyedError(`Sandbox ${priorSandboxId ?? "(unknown)"} was destroyed; /exec-lease returned 410`, {
1869
+ ...priorSandboxId && { sandboxId: priorSandboxId },
1870
+ command: fullCommand,
1871
+ attempts: attempt + 1
1872
+ });
1873
+ }
1874
+ throw error;
1875
+ }
1876
+ lastLease = lease;
1877
+ attemptsMade = attempt + 1;
1878
+ const leaseCwd = options?.cwd ?? this.workingDirectory;
1879
+ const execOptions = {
1880
+ command: fullCommand,
1881
+ ...leaseCwd !== void 0 && { cwd: leaseCwd },
1882
+ ...filteredEnv !== void 0 && { env: filteredEnv },
1883
+ ...effectiveTimeout != null && effectiveTimeout > 0 && { timeoutMs: effectiveTimeout },
1884
+ ...this._webSocketFactory && { webSocketFactory: this._webSocketFactory }
1885
+ };
1886
+ const result = lease.provider === "e2b" ? await this._e2bExecRunner(lease, execOptions) : await execViaLease(lease, execOptions);
1887
+ lastResult = result;
1888
+ if (result.exitCode !== null || result.timedOut) return result;
1889
+ }
1890
+ const result = lastResult;
1891
+ const lease = lastLease;
1892
+ if (this._lease === lease) this._lease = null;
1893
+ throw new SandboxExecTransportError(`Direct-exec transport failed for sandbox ${this._sandboxId ?? "(unknown)"} after ${attemptsMade} attempt(s)` + (result.closeCode !== void 0 ? ` (close ${result.closeCode}${result.closeReason ? ` ${result.closeReason}` : ""})` : ""), {
1894
+ ...this._sandboxId && { sandboxId: this._sandboxId },
1895
+ command: fullCommand,
1896
+ attempts: attemptsMade,
1897
+ opened: result.opened ?? false,
1898
+ ...result.closeCode !== void 0 && { closeCode: result.closeCode },
1899
+ ...result.closeReason !== void 0 && { closeReason: result.closeReason },
1900
+ wsEndpoint: lease.wsEndpoint
1901
+ });
1902
+ }
1903
+ /**
1904
+ * Try to run the exec against the in-sandbox sidecar over Railway's private
1905
+ * network. Returns the result on success (including non-zero exit codes and
1906
+ * timeouts — those are real command results, not failures). Returns
1907
+ * `undefined` when the caller should fall back to the lease path:
1908
+ *
1909
+ * - Transport failure (connection refused, mid-stream drop, no `exit`
1910
+ * frame). The registry entry is evicted so subsequent execs skip the
1911
+ * private-net dial until the sidecar re-registers.
1912
+ * - Sidecar answered with a non-2xx HTTP status. Registry is left intact —
1913
+ * the address is still valid; something else is wrong (bad request,
1914
+ * sidecar bug). Only this specific exec falls back.
1915
+ */
1916
+ async _tryExecViaPrivateNetwork(instanceUrl, fullCommand, effectiveTimeout, options) {
1917
+ const filteredEnv = this._execEnv(options);
1918
+ const privateNetCwd = options?.cwd ?? this.workingDirectory;
1919
+ const execOptions = {
1920
+ command: fullCommand,
1921
+ ...privateNetCwd !== void 0 && { cwd: privateNetCwd },
1922
+ ...filteredEnv !== void 0 && { env: filteredEnv },
1923
+ ...effectiveTimeout != null && effectiveTimeout > 0 && { timeoutMs: effectiveTimeout },
1924
+ ...this._privateNetFetch && { fetch: this._privateNetFetch }
1925
+ };
1926
+ let result;
1927
+ try {
1928
+ result = await execViaPrivateNetwork(instanceUrl, execOptions);
1929
+ } catch (error) {
1930
+ if (error instanceof PrivateNetExecHttpError) return;
1931
+ this._invalidateAddress();
1932
+ return;
1933
+ }
1934
+ if (result.timedOut) {
1935
+ if (!result.opened) this._invalidateAddress();
1936
+ return result;
1937
+ }
1938
+ if (!result.opened || result.exitCode === null) {
1939
+ this._invalidateAddress();
1940
+ return;
1941
+ }
1942
+ return result;
1943
+ }
1944
+ /**
1945
+ * Evict this sandbox's entry from the address registry after an observed
1946
+ * transport failure. The entry stays gone until the next start() re-reads
1947
+ * `instanceUrl` from a workspace-proxy response — until then, execs skip
1948
+ * the private-net dial and go straight to the lease path.
1949
+ */
1950
+ _invalidateAddress() {
1951
+ if (this._sandboxId) this._addressRegistry?.delete(this._sandboxId);
1952
+ }
1953
+ /**
1954
+ * Return a cached exec lease, minting a fresh one when the cache is empty
1955
+ * or the JWT is within {@link LEASE_REFRESH_MARGIN_MS} of `expiresAt`.
1956
+ *
1957
+ * Callers are expected to be on the "sandbox is running" path; we don't
1958
+ * re-check `_sandboxId` here because `executeCommand` already gated on it.
1959
+ */
1960
+ async _ensureLease() {
1961
+ const now = Date.now();
1962
+ if (this._lease && this._lease.expiresAtMs !== null && this._lease.expiresAtMs - LEASE_REFRESH_MARGIN_MS > now) return this._lease;
1963
+ if (this._leaseInFlight) return this._leaseInFlight;
1964
+ if (!this._sandboxId) throw new _mastra_core_workspace.SandboxNotReadyError(this.id);
1965
+ const sandboxId = this._sandboxId;
1966
+ const inFlight = (async () => {
1967
+ const json = await (await this._request(`/sandbox/${encodeURIComponent(sandboxId)}/exec-lease`, { method: "POST" })).json();
1968
+ const expiresAtMs = json.expiresAt ? Date.parse(json.expiresAt) : null;
1969
+ const lease = {
1970
+ provider: json.provider,
1971
+ sandboxId: json.sandboxId,
1972
+ providerResourceId: json.providerResourceId,
1973
+ jwt: json.jwt,
1974
+ wsEndpoint: json.wsEndpoint,
1975
+ subprotocol: json.subprotocol,
1976
+ expiresAt: json.expiresAt,
1977
+ expiresAtMs: expiresAtMs !== null && !Number.isNaN(expiresAtMs) ? expiresAtMs : null
1978
+ };
1979
+ this._lease = lease;
1980
+ return lease;
1981
+ })();
1982
+ this._leaseInFlight = inFlight;
1983
+ try {
1984
+ return await inFlight;
1985
+ } finally {
1986
+ if (this._leaseInFlight === inFlight) this._leaseInFlight = null;
1987
+ }
1988
+ }
1989
+ async getInfo() {
1990
+ if (!this._sandboxId || this.status !== "running") return {
1991
+ id: this.id,
1992
+ name: this.name,
1993
+ provider: this.provider,
1994
+ status: this.status,
1995
+ createdAt: this._createdAt ?? /* @__PURE__ */ new Date()
1996
+ };
1997
+ if (this._addressRegistry?.get(this._sandboxId)) return {
1998
+ id: this._sandboxId,
1999
+ name: this.name,
2000
+ provider: this.provider,
2001
+ status: this.status,
2002
+ createdAt: this._createdAt ?? /* @__PURE__ */ new Date(),
2003
+ metadata: { sandboxId: this._sandboxId }
2004
+ };
2005
+ const json = await (await this._request(`/sandbox/${encodeURIComponent(this._sandboxId)}`)).json();
2006
+ return {
2007
+ id: json.id,
2008
+ name: this.name,
2009
+ provider: this.provider,
2010
+ status: this.status,
2011
+ createdAt: json.createdAt ? new Date(json.createdAt) : this._createdAt ?? /* @__PURE__ */ new Date(),
2012
+ metadata: {
2013
+ sandboxId: json.id,
2014
+ providerResourceId: json.providerResourceId ?? void 0,
2015
+ platformStatus: json.status
2016
+ }
2017
+ };
2018
+ }
2019
+ getInstructions(opts) {
2020
+ const defaultInstructions = `Platform sandbox${this._sandboxId ? ` ${this._sandboxId}` : ""}. Execute commands with the sandbox command APIs.`;
2021
+ if (typeof this._instructionsOverride === "function") return this._instructionsOverride({
2022
+ defaultInstructions,
2023
+ requestContext: opts?.requestContext
2024
+ });
2025
+ if (typeof this._instructionsOverride === "string") return this._instructionsOverride;
2026
+ return defaultInstructions;
2027
+ }
2028
+ };
2029
+ /**
2030
+ * Diagnostic fingerprint of the serialized template a sandbox was provisioned
2031
+ * with: the same definition (repositories, pinned heads, setup commands,
2032
+ * resources) hashes the same on warm and cold boots. `family` is excluded, as
2033
+ * in the server's exact-content identity. Not the server's cache digest, which
2034
+ * also normalizes resources.
2035
+ */
2036
+ function templateHash(definition) {
2037
+ const { family: _family, ...content } = definition;
2038
+ return (0, crypto.createHash)("sha256").update(JSON.stringify(content)).digest("hex").slice(0, 16);
2039
+ }
2040
+ //#endregion
2041
+ //#region ../../packages/_internals/workspace/dist/index.js
2042
+ /** Directory, relative to the template's build cwd, that holds every marker below. */
2043
+ const SETUP_MARKER_DIR = ".mastra-sandbox";
2044
+ /**
2045
+ * Setup completion marker shared by repo templates and their consumers.
2046
+ *
2047
+ * A repo template writes this file beside the checkout as its last build
2048
+ * step, so it exists only in images where every setup command succeeded. Its
2049
+ * content is a digest of the setup commands the image ran, letting a sandbox
2050
+ * booted from the image tell whether the setup it is about to run already
2051
+ * happened. Relative to the template's build cwd, which is also the runtime
2052
+ * working directory the repo was cloned into.
2053
+ *
2054
+ * This is the single-repository marker. Templates built from a repository
2055
+ * list write one marker per repository instead ({@link repoSetupMarkerPath}).
2056
+ */
2057
+ const SETUP_MARKER_PATH = ".mastra-sandbox/setup";
2058
+ /**
2059
+ * Marker for the workspace-level setup of a multi-repository template: the
2060
+ * commands that ran at the working directory after every repository was set
2061
+ * up. Written even when there were no such commands, so a consumer can tell
2062
+ * "ran nothing" from "never built".
2063
+ */
2064
+ const WORKSPACE_SETUP_MARKER_PATH = ".mastra-sandbox/workspace-setup";
2065
+ /**
2066
+ * One line per repository directory whose setup failed while the build was
2067
+ * told to continue. Absent when nothing failed. Consumers check this before
2068
+ * trusting a per-repository marker: that marker means every step ran, not
2069
+ * that every step succeeded.
2070
+ */
2071
+ const SETUP_FAILED_MARKER_PATH = ".mastra-sandbox/setup-failed";
2072
+ /** Per-repository marker of a multi-repository template, keyed by the clone directory name. */
2073
+ function repoSetupMarkerPath(repoDir) {
2074
+ return `${SETUP_MARKER_DIR}/repos/${repoDir}`;
2075
+ }
2076
+ /** Blank entries never become build steps, so they never count toward the digest either. */
2077
+ function normalizeSetupCommands(setupCommand) {
2078
+ return (setupCommand === void 0 ? [] : Array.isArray(setupCommand) ? setupCommand : [setupCommand]).filter((command) => command.trim() !== "");
2079
+ }
2080
+ /** The marker content for a setup command list: `sha256:<hex>` over the commands joined by newlines. */
2081
+ function setupMarkerContent(setupCommand) {
2082
+ return `sha256:${(0, crypto.createHash)("sha256").update(normalizeSetupCommands(setupCommand).join("\n")).digest("hex")}`;
2083
+ }
2084
+ /** Shell step that writes the marker relative to the cwd. `content` is a digest, so it is shell-safe. */
2085
+ function setupMarkerCommand(content, markerPath = SETUP_MARKER_PATH) {
2086
+ return `mkdir -p "$(dirname "${markerPath}")" && printf '%s' '${content}' > "${markerPath}"`;
2087
+ }
2088
+ /** A clone directory name is one path segment of word characters, dots and dashes, so it never needs quoting. */
2089
+ const REPO_DIR_PATTERN = /^[\w.-]+$/;
2090
+ /**
2091
+ * Shell step that runs one setup command inside a repository clone.
2092
+ *
2093
+ * Without the guard this is the plain `cd "<dir>" && <cmd>` step. With it,
2094
+ * the `cd` sits inside the parenthesized group so that the failure branch
2095
+ * runs back at the build cwd and the failure list lands at the workspace
2096
+ * level, never inside the repository.
2097
+ */
2098
+ function guardedSetupCommand({ repoDir, command, continueOnFailure }) {
2099
+ if (!REPO_DIR_PATTERN.test(repoDir)) throw new TypeError(`Repository directory "${repoDir}" must match ${REPO_DIR_PATTERN}.`);
2100
+ if (!continueOnFailure) return `cd "${repoDir}" && ${command}`;
2101
+ return `( cd "${repoDir}" && sh -c ${shellQuote$1(command)} ) || { mkdir -p "${SETUP_MARKER_DIR}" && grep -qxF -- '${repoDir}' "${SETUP_FAILED_MARKER_PATH}" 2>/dev/null || printf '%s\\n' '${repoDir}' >> "${SETUP_FAILED_MARKER_PATH}"; }`;
2102
+ }
2103
+ function shellQuote$1(value) {
2104
+ return `'${value.replace(/'/g, `'\\''`)}'`;
2105
+ }
2106
+ function repoCloneCommand({ cloneUrl, destination, branch, tokenEnv }) {
2107
+ return `git ${tokenEnv ? `${gitAuthFlag$1(tokenEnv)} ` : ""}clone --depth=1 --single-branch ${branch ? `--branch ${shellQuote(branch)} ` : ""}${shellQuote(cloneUrl)} ${shellQuote(destination)}`;
2108
+ }
2109
+ /** Per-invocation auth header; `-c` config never reaches `.git/config`. */
2110
+ function gitAuthFlag$1(tokenEnv) {
2111
+ return `-c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$${tokenEnv}" | base64 -w0)"`;
2112
+ }
2113
+ function shellQuote(value) {
2114
+ return `'${value.replace(/'/g, `'\\''`)}'`;
2115
+ }
2116
+ //#endregion
2117
+ //#region src/repo-template.ts
2118
+ const execFileAsync = (0, util.promisify)(child_process.execFile);
2119
+ const SHA_PATTERN = /^[0-9a-f]{7,40}$/i;
2120
+ const BUILD_TOKEN_ENV = "MASTRA_REPOSITORY_ACCESS_TOKEN";
2121
+ /**
2122
+ * Clone URLs interpolate into the template's build commands, so constrain
2123
+ * them to https plus plain host/path characters. Every regex here is a
2124
+ * single anchored character class, so matching stays linear on adversarial
2125
+ * input; the structural checks go through WHATWG URL parsing instead of one
2126
+ * big backtracking pattern.
2127
+ */
2128
+ const CLONE_URL_ALLOWED_CHARS = /^[a-z0-9:/._-]+$/i;
2129
+ const CLONE_URL_HOST_PATTERN = /^[a-z0-9.-]+$/i;
2130
+ const CLONE_URL_SEGMENT_PATTERN = /^[\w.-]+$/;
2131
+ /** Last default-branch head resolved per clone URL, shared across resolvers in this process. */
2132
+ const lastKnownHeads = /* @__PURE__ */ new Map();
2133
+ const MAX_LAST_KNOWN_HEADS = 1e3;
2134
+ function rememberHead(cloneUrl, sha) {
2135
+ lastKnownHeads.delete(cloneUrl);
2136
+ lastKnownHeads.set(cloneUrl, sha);
2137
+ if (lastKnownHeads.size > MAX_LAST_KNOWN_HEADS) lastKnownHeads.delete(lastKnownHeads.keys().next().value);
2138
+ }
2139
+ /**
2140
+ * Create a lazy repository template definition for PlatformSandbox, mirroring
2141
+ * `@mastra/e2b`'s `createRepoTemplate`: pass the sandbox context through and a
2142
+ * repo-less session boots the provider default.
2143
+ *
2144
+ * The resolver performs no work until a fresh sandbox starts. It clones the
2145
+ * URL `getRepositoryAccess` resolves — the only source of the clone URL, so
2146
+ * what gets cloned and what the template is identified by can't drift — and
2147
+ * pins repositories to their current default-branch commit. Private repository
2148
+ * credentials are used for head resolution and sent to the provider as
2149
+ * transient build envs; they never enter the serialized definition. A failed
2150
+ * head lookup reuses the last head resolved for the same clone URL in this
2151
+ * process. If the repository cannot be resolved, or no head has been resolved
2152
+ * yet, the resolver keeps `cpuCount` and
2153
+ * `memoryMB` in a resources-only template so the sandbox still boots at the
2154
+ * requested size, and the caller's runtime setup materializes the checkout.
2155
+ */
2156
+ function createRepoTemplate(options) {
2157
+ if (options.getRepositoryAccess && options.repos) throw new TypeError("createRepoTemplate: pass either getRepositoryAccess or repos, not both");
2158
+ if (!options.repos && (options.workspaceSetupCommand !== void 0 || options.continueOnSetupFailure !== void 0)) throw new TypeError("createRepoTemplate: workspaceSetupCommand and continueOnSetupFailure require repos");
2159
+ const isList = options.repos !== void 0;
2160
+ const entries = options.repos ? options.repos : options.getRepositoryAccess ? [{
2161
+ getRepositoryAccess: options.getRepositoryAccess,
2162
+ setupCommand: options.setupCommand
2163
+ }] : [];
2164
+ const resourcesOnly = () => {
2165
+ if (options.cpuCount === void 0 && options.memoryMB === void 0) return void 0;
2166
+ return withResources(Template(), options);
2167
+ };
2168
+ if (entries.length === 0) {
2169
+ const template = resourcesOnly();
2170
+ return template ? async () => template : void 0;
2171
+ }
2172
+ const resolveHead = options.resolveHead ?? resolveDefaultBranchHead;
2173
+ const continueOnFailure = options.continueOnSetupFailure ?? false;
2174
+ return async () => {
2175
+ const repos = [];
2176
+ for (const [index, entry] of entries.entries()) {
2177
+ let accessError;
2178
+ const access = await entry.getRepositoryAccess().catch((error) => {
2179
+ accessError = error;
2180
+ });
2181
+ if (!access?.cloneUrl) {
2182
+ console.warn("[platform-workspace] repo template skipped: repository access unavailable", {
2183
+ ...isList ? { index } : {},
2184
+ error: redactSecrets(accessError)
2185
+ });
2186
+ return resourcesOnly();
2187
+ }
2188
+ const cloneUrl = normalizeCloneUrl(access.cloneUrl);
2189
+ if (!isValidCloneUrl(cloneUrl)) {
2190
+ console.warn("[platform-workspace] repo template skipped: clone URL failed validation", {
2191
+ ...isList ? { index } : {},
2192
+ cloneUrl: redactSecrets(cloneUrl)
2193
+ });
2194
+ return resourcesOnly();
2195
+ }
2196
+ const token = access.authorization?.token;
2197
+ let headError;
2198
+ const resolved = await (token ? resolveHead(cloneUrl, token) : resolveHead(cloneUrl)).catch((error) => {
2199
+ headError = error;
2200
+ });
2201
+ let sha;
2202
+ if (resolved && SHA_PATTERN.test(resolved)) {
2203
+ sha = resolved;
2204
+ rememberHead(cloneUrl, sha);
2205
+ } else {
2206
+ const lastKnown = lastKnownHeads.get(cloneUrl);
2207
+ if (lastKnown) {
2208
+ console.warn("[platform-workspace] repo template pinned to the last known default-branch head", {
2209
+ cloneUrl,
2210
+ sha: lastKnown,
2211
+ resolved,
2212
+ error: redactSecrets(headError)
2213
+ });
2214
+ sha = lastKnown;
2215
+ } else if (isList) console.warn("[platform-workspace] repo template clones unpinned: could not resolve default-branch head", {
2216
+ cloneUrl,
2217
+ sha: resolved,
2218
+ error: redactSecrets(headError)
2219
+ });
2220
+ else {
2221
+ console.warn("[platform-workspace] repo template skipped: could not resolve default-branch head", {
2222
+ cloneUrl,
2223
+ sha: resolved,
2224
+ error: redactSecrets(headError)
2225
+ });
2226
+ return resourcesOnly();
2227
+ }
2228
+ }
2229
+ const repoDir = repoDirName(cloneUrl);
2230
+ repos.push({
2231
+ index,
2232
+ cloneUrl,
2233
+ repoDir,
2234
+ token,
2235
+ tokenEnv: token ? isList ? `${BUILD_TOKEN_ENV}_${index}` : BUILD_TOKEN_ENV : void 0,
2236
+ sha,
2237
+ setupCommands: normalizeSetupCommands(entry.setupCommand)
2238
+ });
2239
+ }
2240
+ const seenDirs = /* @__PURE__ */ new Map();
2241
+ for (const repo of repos) {
2242
+ const other = seenDirs.get(repo.repoDir);
2243
+ if (other) throw new Error(`createRepoTemplate: repositories ${other} and ${repo.cloneUrl} would both clone into "${repo.repoDir}"`);
2244
+ seenDirs.set(repo.repoDir, repo.cloneUrl);
2245
+ }
2246
+ const workingDirectory = options.workingDirectory === void 0 ? void 0 : trimTrailingSlashes(assertWorkingDirectory(options.workingDirectory));
2247
+ const family = isList ? `repos:${(0, crypto.createHash)("sha256").update(JSON.stringify([workingDirectory ?? "", repos.map((repo) => [repo.cloneUrl, repo.repoDir])])).digest("hex").slice(0, 32)}` : `repo:${repos[0].cloneUrl}:${workingDirectory ?? ""}/${repos[0].repoDir}`;
2248
+ let template = Template();
2249
+ const buildEnv = { ...options.buildEnv };
2250
+ for (const repo of repos) if (repo.tokenEnv && repo.token) buildEnv[repo.tokenEnv] = repo.token;
2251
+ if (Object.keys(buildEnv).length > 0) template = template.setEnvs(buildEnv, { ephemeral: true });
2252
+ template = withResources(template, options);
2253
+ if (workingDirectory) template = template.runCmd(`mkdir -p "${workingDirectory}"`).setWorkdir(workingDirectory);
2254
+ const ordered = [...repos.filter((repo) => !repo.token), ...repos.filter((repo) => repo.token)];
2255
+ for (const repo of ordered) {
2256
+ const { repoDir, sha, tokenEnv, setupCommands } = repo;
2257
+ const auth = tokenEnv ? `${gitAuthFlag(tokenEnv)} ` : "";
2258
+ template = template.runCmd(repoCloneCommand({
2259
+ cloneUrl: repo.cloneUrl,
2260
+ destination: repoDir,
2261
+ ...tokenEnv ? { tokenEnv } : {}
2262
+ }));
2263
+ if (sha) template = template.runCmd(`git -C "${repoDir}" ${auth}fetch origin ${sha}`).runCmd(`git -C "${repoDir}" checkout ${sha}`);
2264
+ for (const command of setupCommands) template = template.runCmd(guardedSetupCommand({
2265
+ repoDir,
2266
+ command,
2267
+ continueOnFailure
2268
+ }));
2269
+ const content = setupMarkerContent(setupCommands);
2270
+ template = template.runCmd(isList ? setupMarkerCommand(content, repoSetupMarkerPath(repoDir)) : setupMarkerCommand(content));
2271
+ }
2272
+ if (isList) {
2273
+ const workspaceCommands = normalizeSetupCommands(options.workspaceSetupCommand);
2274
+ for (const command of workspaceCommands) template = template.runCmd(command);
2275
+ template = template.runCmd(setupMarkerCommand(setupMarkerContent(workspaceCommands), WORKSPACE_SETUP_MARKER_PATH));
2276
+ }
2277
+ return template.withFamily(family);
2278
+ };
2279
+ }
2280
+ function withResources(template, options) {
2281
+ if (options.cpuCount !== void 0) template = template.cpuCount(options.cpuCount);
2282
+ if (options.memoryMB !== void 0) template = template.memoryMB(options.memoryMB);
2283
+ return template;
2284
+ }
2285
+ function isValidCloneUrl(cloneUrl) {
2286
+ if (cloneUrl.length > 2048 || !CLONE_URL_ALLOWED_CHARS.test(cloneUrl)) return false;
2287
+ let url;
2288
+ try {
2289
+ url = new URL(cloneUrl);
2290
+ } catch {
2291
+ return false;
2292
+ }
2293
+ if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash) return false;
2294
+ if (!CLONE_URL_HOST_PATTERN.test(url.hostname)) return false;
2295
+ const segments = url.pathname.split("/").slice(1);
2296
+ return segments.length > 0 && segments.every((segment) => CLONE_URL_SEGMENT_PATTERN.test(segment));
2297
+ }
2298
+ /**
2299
+ * Canonical form used for identity, the family key, and the build's clone:
2300
+ * lowercase host, no trailing `.git` or slash. Two spellings of one
2301
+ * repository must not produce two templates.
2302
+ */
2303
+ function normalizeCloneUrl(cloneUrl) {
2304
+ let end = cloneUrl.length;
2305
+ while (end > 0 && cloneUrl[end - 1] === "/") end--;
2306
+ return cloneUrl.slice(0, end).replace(/\.git$/i, "").replace(/^(https:\/\/)([^/]+)/i, (_match, scheme, host) => {
2307
+ return `${scheme.toLowerCase()}${host.toLowerCase()}`;
2308
+ });
2309
+ }
2310
+ function repoDirName(cloneUrl) {
2311
+ return (normalizeCloneUrl(cloneUrl).split("/").at(-1) ?? "").replace(/[^\w.-]/g, "-").replace(/^\.+/, "") || "repo";
2312
+ }
2313
+ function trimTrailingSlashes(path) {
2314
+ let end = path.length;
2315
+ while (end > 1 && path[end - 1] === "/") end--;
2316
+ return path.slice(0, end);
2317
+ }
2318
+ /** Validate a literal absolute path before embedding it in shell build steps. */
2319
+ function assertWorkingDirectory(dir) {
2320
+ if (!(/^\/[A-Za-z0-9._/-]*$/.test(dir) && !dir.split("/").includes(".."))) throw new Error(`Repo template workingDirectory must be an absolute path of plain path characters (got ${JSON.stringify(dir)}); ~ and $HOME are not expanded.`);
2321
+ return dir;
2322
+ }
2323
+ /**
2324
+ * Render a caught value for a warning without leaking credentials: URL
2325
+ * userinfo, HTTP authorization values, and GitHub token shapes are masked.
2326
+ */
2327
+ function redactSecrets(value) {
2328
+ if (value === void 0 || value === null) return void 0;
2329
+ return (value instanceof Error ? value.message : typeof value === "string" ? value : String(value)).replace(/\/\/[^/@\s]+@/g, "//***@").replace(/\b(bearer|basic)\s+[^\s"']+/gi, "$1 ***").replace(/\b(gh[pousr]_|github_pat_)[A-Za-z0-9_]+/g, "$1***");
2330
+ }
2331
+ function gitAuthFlag(tokenEnv) {
2332
+ return `-c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$${tokenEnv}" | base64 -w0)"`;
2333
+ }
2334
+ /**
2335
+ * `owner/repo` for a github.com clone URL, else undefined. Only the public
2336
+ * host is API-resolvable: GitHub Enterprise and other forges keep the git
2337
+ * path below.
2338
+ */
2339
+ function parseGithubRepo(cloneUrl) {
2340
+ let url;
2341
+ try {
2342
+ url = new URL(cloneUrl);
2343
+ } catch {
2344
+ return;
2345
+ }
2346
+ if (url.hostname.toLowerCase() !== "github.com") return void 0;
2347
+ const [owner, repo, ...rest] = url.pathname.split("/").filter(Boolean);
2348
+ if (!owner || !repo || rest.length > 0) return void 0;
2349
+ return {
2350
+ owner,
2351
+ repo: repo.replace(/\.git$/i, "")
2352
+ };
2353
+ }
2354
+ /**
2355
+ * Resolve the default-branch head. github.com repositories go through the
2356
+ * REST API so resolution works wherever the host runs, including deployed
2357
+ * images without a git binary; other hosts shell out to `git ls-remote`.
2358
+ * Throws with a redaction-safe message when the head cannot be resolved.
2359
+ */
2360
+ async function resolveDefaultBranchHead(cloneUrl, token, execute = execFileAsync, fetchImpl = fetch) {
2361
+ const github = parseGithubRepo(cloneUrl);
2362
+ if (github) {
2363
+ const response = await fetchImpl(`https://api.github.com/repos/${github.owner}/${github.repo}/commits/HEAD`, {
2364
+ headers: {
2365
+ Accept: "application/vnd.github.sha",
2366
+ "X-GitHub-Api-Version": "2022-11-28",
2367
+ "User-Agent": "mastra-platform-workspace",
2368
+ ...token ? { Authorization: `Bearer ${token}` } : {}
2369
+ },
2370
+ signal: AbortSignal.timeout(1e4)
2371
+ }).catch((error) => {
2372
+ throw new Error(`GitHub head lookup failed: ${error instanceof Error ? error.message : String(error)}`);
2373
+ });
2374
+ if (!response.ok) throw new Error(`GitHub head lookup failed: ${response.status} ${response.statusText}`.trim());
2375
+ const sha = (await response.text()).trim();
2376
+ return SHA_PATTERN.test(sha) ? sha : void 0;
2377
+ }
2378
+ try {
2379
+ const env = {
2380
+ ...process.env,
2381
+ GIT_TERMINAL_PROMPT: "0"
2382
+ };
2383
+ if (token) {
2384
+ env.GIT_CONFIG_COUNT = "1";
2385
+ env.GIT_CONFIG_KEY_0 = "http.extraheader";
2386
+ env.GIT_CONFIG_VALUE_0 = `AUTHORIZATION: basic ${Buffer.from(`x-access-token:${token}`).toString("base64")}`;
2387
+ }
2388
+ const { stdout } = await execute("git", [
2389
+ "ls-remote",
2390
+ "--",
2391
+ cloneUrl,
2392
+ "HEAD"
2393
+ ], {
2394
+ timeout: 1e4,
2395
+ maxBuffer: 1024 * 1024,
2396
+ env
2397
+ });
2398
+ const sha = stdout.trim().split(/\s+/, 1)[0];
2399
+ return sha && SHA_PATTERN.test(sha) ? sha : void 0;
2400
+ } catch (error) {
2401
+ const stderr = error.stderr;
2402
+ const detail = typeof stderr === "string" && stderr.trim() ? stderr.trim() : String(error);
2403
+ throw new Error(`git ls-remote failed: ${detail}`);
2404
+ }
2405
+ }
2406
+ //#endregion
2407
+ //#region src/provider.ts
2408
+ const platformSandboxProvider = {
2409
+ id: "platform",
2410
+ name: "Mastra Platform Sandbox",
2411
+ description: "Environment-scoped sandbox execution through Mastra Platform workspace proxy",
2412
+ configSchema: {
2413
+ type: "object",
2414
+ properties: {
2415
+ accessToken: {
2416
+ type: "string",
2417
+ description: "Mastra Platform credential (falls back to MASTRA_PLATFORM_ACCESS_TOKEN, then MASTRA_PLATFORM_SECRET_KEY)"
2418
+ },
2419
+ projectId: {
2420
+ type: "string",
2421
+ description: "Platform project ID (falls back to MASTRA_PROJECT_ID)"
2422
+ },
2423
+ actingUserId: {
2424
+ type: "string",
2425
+ description: "Opaque user subject attributed to sandbox requests"
2426
+ },
2427
+ sandboxProvider: {
2428
+ type: "string",
2429
+ description: "Sandbox provider (falls back to SANDBOX_PROVIDER, then e2b)",
2430
+ enum: ["railway", "e2b"],
2431
+ default: "e2b"
2432
+ },
2433
+ environmentId: {
2434
+ type: "string",
2435
+ description: "Platform environment ID (falls back to MASTRA_ENVIRONMENT_ID)"
2436
+ },
2437
+ sandboxId: {
2438
+ type: "string",
2439
+ description: "Reattach to an existing Platform sandbox by ID"
2440
+ },
2441
+ idleTimeoutMinutes: {
2442
+ type: "number",
2443
+ description: "Minutes before the sandbox can be destroyed while idle"
2444
+ },
2445
+ networkIsolation: {
2446
+ type: "string",
2447
+ description: "Network isolation mode",
2448
+ enum: ["ISOLATED", "PRIVATE"],
2449
+ default: "ISOLATED"
2450
+ },
2451
+ env: {
2452
+ type: "object",
2453
+ description: "Environment variables",
2454
+ additionalProperties: { type: "string" }
2455
+ },
2456
+ timeout: {
2457
+ type: "number",
2458
+ description: "Default command timeout in ms"
2459
+ }
2460
+ }
2461
+ },
2462
+ createSandbox: (config) => new PlatformSandbox(config)
2463
+ };
2464
+ const platformFilesystemProvider = {
2465
+ id: "platform",
2466
+ name: "Mastra Platform Filesystem",
2467
+ description: "Bucket-backed filesystem access through Mastra Platform workspace proxy",
2468
+ configSchema: {
2469
+ type: "object",
2470
+ properties: {
2471
+ accessToken: {
2472
+ type: "string",
2473
+ description: "Mastra Platform credential (falls back to MASTRA_PLATFORM_ACCESS_TOKEN, then MASTRA_PLATFORM_SECRET_KEY)"
2474
+ },
2475
+ projectId: {
2476
+ type: "string",
2477
+ description: "Platform project ID (falls back to MASTRA_PROJECT_ID)"
2478
+ },
2479
+ bucketName: {
2480
+ type: "string",
2481
+ description: "Platform workspace bucket name (falls back to MASTRA_PLATFORM_BUCKET_NAME)"
2482
+ },
2483
+ readOnly: {
2484
+ type: "boolean",
2485
+ description: "Mount as read-only",
2486
+ default: false
2487
+ }
2488
+ }
2489
+ },
2490
+ createFilesystem: (config) => new PlatformFilesystem(config)
2491
+ };
2492
+ //#endregion
2493
+ //#region src/factory-sandbox.ts
2494
+ /** Applied when neither the environment setting nor a host default is set. */
2495
+ const DEFAULT_SETTINGS = {
2496
+ cpuCount: 2,
2497
+ memoryMb: 1024,
2498
+ idleTimeoutMinutes: 5
2499
+ };
2500
+ const SETTINGS_SCHEMA = {
2501
+ type: "object",
2502
+ properties: {
2503
+ cpuCount: {
2504
+ type: "integer",
2505
+ title: "CPU",
2506
+ description: "vCPUs for the sandbox template",
2507
+ default: DEFAULT_SETTINGS.cpuCount,
2508
+ minimum: 1,
2509
+ maximum: 64
2510
+ },
2511
+ memoryMb: {
2512
+ type: "integer",
2513
+ title: "Memory",
2514
+ description: "Memory for the sandbox template",
2515
+ default: DEFAULT_SETTINGS.memoryMb,
2516
+ oneOf: [
2517
+ {
2518
+ const: 512,
2519
+ title: "512 MB"
2520
+ },
2521
+ {
2522
+ const: 1024,
2523
+ title: "1 GB"
2524
+ },
2525
+ {
2526
+ const: 2048,
2527
+ title: "2 GB"
2528
+ },
2529
+ {
2530
+ const: 4096,
2531
+ title: "4 GB"
2532
+ },
2533
+ {
2534
+ const: 8192,
2535
+ title: "8 GB"
2536
+ }
2537
+ ]
2538
+ },
2539
+ idleTimeoutMinutes: {
2540
+ type: "integer",
2541
+ title: "Idle timeout (minutes)",
2542
+ description: "Minutes idle before the sandbox pauses",
2543
+ default: DEFAULT_SETTINGS.idleTimeoutMinutes,
2544
+ minimum: 1,
2545
+ maximum: 1440
2546
+ }
2547
+ },
2548
+ additionalProperties: false
2549
+ };
2550
+ /**
2551
+ * The settings schema with the provider's effective defaults as `default`:
2552
+ * the built-in values, overridden by the host's `idleTimeoutMinutes` option and
2553
+ * then its `defaults` option. The schema
2554
+ * is what clients show as placeholders, so it must match what the provider
2555
+ * applies when a setting is unset.
2556
+ */
2557
+ function settingsSchema(defaults) {
2558
+ const effective = {
2559
+ ...DEFAULT_SETTINGS,
2560
+ ...defaults
2561
+ };
2562
+ const properties = Object.fromEntries(Object.entries(SETTINGS_SCHEMA.properties).map(([key, property]) => [key, {
2563
+ ...property,
2564
+ default: effective[key]
2565
+ }]));
2566
+ return {
2567
+ ...SETTINGS_SCHEMA,
2568
+ properties
2569
+ };
2570
+ }
2571
+ /**
2572
+ * The platform host contract for factory: every session sandbox is a
2573
+ * {@link PlatformSandbox} whose template is {@link createRepoTemplate} over
2574
+ * the session's repositories, sized by the factory's environment settings.
2575
+ */
2576
+ var PlatformFactorySandbox = class extends _mastra_core_workspace.FactorySandbox {
2577
+ provider = "platform";
2578
+ settings;
2579
+ #options;
2580
+ /**
2581
+ * Builders by template id from this process's `builds.start` calls. Platform
2582
+ * has no build status endpoint; re-calling the same builder's idempotent
2583
+ * `build()` is the status poll. After a restart earlier builds read as
2584
+ * `unknown`.
2585
+ *
2586
+ * TODO: once the platform API exposes build status and build history, read
2587
+ * `get` from the API instead of this in-memory cache and add `builds.list`.
2588
+ */
2589
+ #builders = /* @__PURE__ */ new Map();
2590
+ builds = {
2591
+ start: (ctx, settings) => this.#startBuild(ctx, settings),
2592
+ get: (ctx, settings, buildId) => this.#getBuild(ctx, settings, buildId)
2593
+ };
2594
+ constructor(options = {}) {
2595
+ super();
2596
+ this.#options = options;
2597
+ this.settings = settingsSchema({
2598
+ ...options.idleTimeoutMinutes !== void 0 ? { idleTimeoutMinutes: options.idleTimeoutMinutes } : {},
2599
+ ...options.defaults
2600
+ });
2601
+ }
2602
+ template(ctx, settings) {
2603
+ const { defaults, template } = this.#options;
2604
+ return createRepoTemplate({
2605
+ ...ctx,
2606
+ ...template?.buildEnv ? { buildEnv: template.buildEnv } : {},
2607
+ cpuCount: settings.cpuCount ?? defaults?.cpuCount ?? DEFAULT_SETTINGS.cpuCount,
2608
+ memoryMB: settings.memoryMb ?? defaults?.memoryMb ?? DEFAULT_SETTINGS.memoryMb
2609
+ });
2610
+ }
2611
+ create(ctx, settings) {
2612
+ const { defaults, template: _template, ...options } = this.#options;
2613
+ return new PlatformSandbox({
2614
+ ...options,
2615
+ id: ctx.sessionId,
2616
+ sessionId: ctx.sessionId,
2617
+ sandboxId: ctx.sandboxId,
2618
+ template: this.template(ctx, settings),
2619
+ ...ctx.workingDirectory ? { workingDirectory: ctx.workingDirectory } : {},
2620
+ idleTimeoutMinutes: settings.idleTimeoutMinutes ?? defaults?.idleTimeoutMinutes ?? options.idleTimeoutMinutes ?? DEFAULT_SETTINGS.idleTimeoutMinutes
2621
+ });
2622
+ }
2623
+ async #startBuild(ctx, settings) {
2624
+ const builder = await this.#resolveBuilder(ctx, settings);
2625
+ const result = await builder.build(this.#buildOptions());
2626
+ this.#builders.set(result.templateId, builder);
2627
+ return {
2628
+ buildId: result.templateId,
2629
+ templateId: result.templateId,
2630
+ status: mapStatus(result.status)
2631
+ };
2632
+ }
2633
+ async #getBuild(_ctx, _settings, buildId) {
2634
+ const builder = this.#builders.get(buildId);
2635
+ if (!builder) return {
2636
+ buildId,
2637
+ status: "unknown",
2638
+ error: `Build ${buildId} was not started by this process; its status cannot be read.`
2639
+ };
2640
+ return toBuild(await builder.build(this.#buildOptions()));
2641
+ }
2642
+ async #resolveBuilder(ctx, settings) {
2643
+ const builder = await this.template(ctx, settings)?.();
2644
+ if (!builder) throw new Error("PlatformFactorySandbox.builds: the session context yields no template to build");
2645
+ return builder;
2646
+ }
2647
+ #buildOptions() {
2648
+ const { defaults: _defaults, template: _template, env: _env, ...options } = this.#options;
2649
+ return options;
2650
+ }
2651
+ };
2652
+ function mapStatus(status) {
2653
+ return status;
2654
+ }
2655
+ function toBuild(result) {
2656
+ return {
2657
+ buildId: result.templateId,
2658
+ templateId: result.templateId,
2659
+ status: mapStatus(result.status),
2660
+ ...result.error ? { error: result.error } : {}
2661
+ };
2662
+ }
2663
+ //#endregion
2664
+ //#region src/address-registry.ts
2665
+ /**
2666
+ * Concrete in-process {@link SandboxAddressRegistry}. Backed by a `Map`; no
2667
+ * eviction policy, no TTL — entries live until an observed transport failure
2668
+ * calls `delete`, until the sandbox is explicitly destroyed, or until the
2669
+ * process exits.
2670
+ */
2671
+ var InProcessSandboxAddressRegistry = class {
2672
+ #map = /* @__PURE__ */ new Map();
2673
+ get(sandboxId) {
2674
+ return this.#map.get(sandboxId);
2675
+ }
2676
+ /**
2677
+ * Populate or overwrite the address for a sandbox. Called by
2678
+ * {@link PlatformSandbox.start} on every fresh provision and every reattach;
2679
+ * overwriting is intentional so a re-provision with a fresh IPv6 heals the
2680
+ * map without a branch.
2681
+ */
2682
+ set(sandboxId, instanceUrl) {
2683
+ this.#map.set(sandboxId, instanceUrl);
2684
+ }
2685
+ delete(sandboxId) {
2686
+ this.#map.delete(sandboxId);
2687
+ }
2688
+ /**
2689
+ * Test-only introspection. Not part of {@link SandboxAddressRegistry} —
2690
+ * production callers must not read the registry as a whole.
2691
+ */
2692
+ get size() {
2693
+ return this.#map.size;
2694
+ }
2695
+ };
2696
+ //#endregion
2697
+ exports.InProcessSandboxAddressRegistry = InProcessSandboxAddressRegistry;
2698
+ exports.PlatformApiError = PlatformApiError;
2699
+ exports.PlatformClient = PlatformClient;
2700
+ exports.PlatformFactorySandbox = PlatformFactorySandbox;
2701
+ exports.PlatformFilesystem = PlatformFilesystem;
2702
+ exports.PlatformSandbox = PlatformSandbox;
2703
+ exports.PrivateNetExecHttpError = PrivateNetExecHttpError;
2704
+ exports.SandboxDestroyedError = SandboxDestroyedError;
2705
+ exports.SandboxExecTransportError = SandboxExecTransportError;
2706
+ exports.Template = Template;
2707
+ exports.createRepoTemplate = createRepoTemplate;
2708
+ exports.execViaPrivateNetwork = execViaPrivateNetwork;
2709
+ exports.platformFilesystemProvider = platformFilesystemProvider;
2710
+ exports.platformSandboxProvider = platformSandboxProvider;
2711
+
2712
+ //# sourceMappingURL=index.cjs.map