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