@mastra/platform-workspace 0.2.1 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,632 +1,935 @@
1
- import { Buffer } from 'buffer';
2
- import nodePath from 'path';
3
- import { MastraFilesystem, FileNotFoundError, WorkspaceReadOnlyError, FileExistsError, MastraSandbox, SandboxNotReadyError, SandboxProcessManager, ProcessHandle } from '@mastra/core/workspace';
4
-
5
- // src/client.ts
6
- var DEFAULT_PROXY_URL = "https://workspaces.mastra.ai";
7
- var DEFAULT_REQUEST_TIMEOUT_MS = 6e4;
1
+ import { Buffer } from "buffer";
2
+ import nodePath from "path";
3
+ import { FileExistsError, FileNotFoundError, MastraFilesystem, MastraSandbox, ProcessHandle, SandboxNotReadyError, SandboxProcessManager, WorkspaceReadOnlyError } from "@mastra/core/workspace";
4
+ //#region src/client.ts
5
+ const DEFAULT_PROXY_URL = "https://workspaces.mastra.ai";
6
+ /**
7
+ * Default per-request timeout for calls to the workspace proxy. Applied only
8
+ * when the caller doesn't already pass an `AbortSignal`. Long-running routes
9
+ * (e.g. `POST /sandbox/:id/exec`) pass their own longer signal.
10
+ */
11
+ const DEFAULT_REQUEST_TIMEOUT_MS = 6e4;
8
12
  function requireOption(value, name) {
9
- if (!value) throw new Error(`${name} is required`);
10
- return value;
13
+ if (!value) throw new Error(`${name} is required`);
14
+ return value;
11
15
  }
12
16
  function resolvePlatformOptions(options) {
13
- return {
14
- accessToken: requireOption(
15
- options.accessToken ?? process.env.MASTRA_PLATFORM_SECRET_KEY ?? // Deprecated alias — prefer MASTRA_PLATFORM_SECRET_KEY.
16
- process.env.MASTRA_PLATFORM_ACCESS_TOKEN,
17
- "accessToken"
18
- ),
19
- projectId: requireOption(options.projectId ?? process.env.MASTRA_PROJECT_ID, "projectId"),
20
- proxyUrl: (process.env.MASTRA_WORKSPACE_PROXY_URL ?? DEFAULT_PROXY_URL).replace(/\/$/, ""),
21
- fetch: options.fetch ?? fetch
22
- };
17
+ return {
18
+ accessToken: requireOption(options.accessToken ?? process.env.MASTRA_PLATFORM_SECRET_KEY ?? process.env.MASTRA_PLATFORM_ACCESS_TOKEN, "accessToken"),
19
+ projectId: requireOption(options.projectId ?? process.env.MASTRA_PROJECT_ID, "projectId"),
20
+ proxyUrl: (process.env.MASTRA_WORKSPACE_PROXY_URL ?? DEFAULT_PROXY_URL).replace(/\/$/, ""),
21
+ fetch: options.fetch ?? fetch
22
+ };
23
23
  }
24
24
  function parseProxyError(body) {
25
- if (!body) return void 0;
26
- let parsed;
27
- try {
28
- parsed = JSON.parse(body);
29
- } catch {
30
- return void 0;
31
- }
32
- if (typeof parsed !== "object" || parsed === null) return void 0;
33
- const err = parsed.error;
34
- if (typeof err !== "object" || err === null) return void 0;
35
- const { message, type } = err;
36
- if (typeof message !== "string" || typeof type !== "string") return void 0;
37
- return { message, type };
25
+ if (!body) return void 0;
26
+ let parsed;
27
+ try {
28
+ parsed = JSON.parse(body);
29
+ } catch {
30
+ return;
31
+ }
32
+ if (typeof parsed !== "object" || parsed === null) return void 0;
33
+ const err = parsed.error;
34
+ if (typeof err !== "object" || err === null) return void 0;
35
+ const { message, type } = err;
36
+ if (typeof message !== "string" || typeof type !== "string") return void 0;
37
+ return {
38
+ message,
39
+ type
40
+ };
38
41
  }
39
42
  var PlatformApiError = class extends Error {
40
- status;
41
- body;
42
- /** Machine-readable proxy error kind (e.g. `not_found`), when the response body matches `{ error: { message, type } }`. */
43
- code;
44
- /** Human-readable proxy error message, when the response body matches `{ error: { message, type } }`. */
45
- proxyMessage;
46
- constructor(status, body) {
47
- const parsed = parseProxyError(body);
48
- const summary = parsed ? `${parsed.type}: ${parsed.message}` : body;
49
- super(`Platform proxy request failed with ${status}${summary ? `: ${summary}` : ""}`);
50
- this.name = "PlatformApiError";
51
- this.status = status;
52
- this.body = body;
53
- this.code = parsed?.type;
54
- this.proxyMessage = parsed?.message;
55
- }
43
+ status;
44
+ body;
45
+ /** Machine-readable proxy error kind (e.g. `not_found`), when the response body matches `{ error: { message, type } }`. */
46
+ code;
47
+ /** Human-readable proxy error message, when the response body matches `{ error: { message, type } }`. */
48
+ proxyMessage;
49
+ constructor(status, body) {
50
+ const parsed = parseProxyError(body);
51
+ const summary = parsed ? `${parsed.type}: ${parsed.message}` : body;
52
+ super(`Platform proxy request failed with ${status}${summary ? `: ${summary}` : ""}`);
53
+ this.name = "PlatformApiError";
54
+ this.status = status;
55
+ this.body = body;
56
+ this.code = parsed?.type;
57
+ this.proxyMessage = parsed?.message;
58
+ }
56
59
  };
57
60
  var PlatformClient = class {
58
- accessToken;
59
- projectId;
60
- proxyUrl;
61
- fetch;
62
- constructor(options) {
63
- const resolved = resolvePlatformOptions(options);
64
- this.accessToken = resolved.accessToken;
65
- this.projectId = resolved.projectId;
66
- this.proxyUrl = resolved.proxyUrl;
67
- this.fetch = resolved.fetch;
68
- }
69
- async request(path, options = {}) {
70
- const url = new URL(`${this.proxyUrl}/v1/projects/${encodeURIComponent(this.projectId)}${path}`);
71
- for (const [key, value] of Object.entries(options.query ?? {})) {
72
- if (value !== void 0) url.searchParams.set(key, String(value));
73
- }
74
- const headers = new Headers(options.headers);
75
- headers.set("authorization", `Bearer ${this.accessToken}`);
76
- const { query: _query, ...fetchOptions } = options;
77
- const signal = fetchOptions.signal ?? AbortSignal.timeout(DEFAULT_REQUEST_TIMEOUT_MS);
78
- const response = await this.fetch(url, { ...fetchOptions, headers, signal });
79
- if (!response.ok) {
80
- throw new PlatformApiError(response.status, await response.text());
81
- }
82
- return response;
83
- }
61
+ accessToken;
62
+ projectId;
63
+ proxyUrl;
64
+ fetch;
65
+ constructor(options) {
66
+ const resolved = resolvePlatformOptions(options);
67
+ this.accessToken = resolved.accessToken;
68
+ this.projectId = resolved.projectId;
69
+ this.proxyUrl = resolved.proxyUrl;
70
+ this.fetch = resolved.fetch;
71
+ }
72
+ async request(path, options = {}) {
73
+ const url = new URL(`${this.proxyUrl}/v1/projects/${encodeURIComponent(this.projectId)}${path}`);
74
+ for (const [key, value] of Object.entries(options.query ?? {})) if (value !== void 0) url.searchParams.set(key, String(value));
75
+ const headers = new Headers(options.headers);
76
+ headers.set("authorization", `Bearer ${this.accessToken}`);
77
+ const { query: _query, ...fetchOptions } = options;
78
+ const signal = fetchOptions.signal ?? AbortSignal.timeout(DEFAULT_REQUEST_TIMEOUT_MS);
79
+ const response = await this.fetch(url, {
80
+ ...fetchOptions,
81
+ headers,
82
+ signal
83
+ });
84
+ if (!response.ok) throw new PlatformApiError(response.status, await response.text());
85
+ return response;
86
+ }
84
87
  };
88
+ //#endregion
89
+ //#region src/filesystem.ts
85
90
  function normalizePath(input) {
86
- if (!input || input === ".") return "/";
87
- let normalized = input.startsWith("/") ? input : `/${input}`;
88
- normalized = nodePath.posix.normalize(normalized);
89
- return normalized === "." ? "/" : normalized;
91
+ if (!input || input === ".") return "/";
92
+ let normalized = input.startsWith("/") ? input : `/${input}`;
93
+ normalized = nodePath.posix.normalize(normalized);
94
+ return normalized === "." ? "/" : normalized;
90
95
  }
91
96
  function keyFromPath(path) {
92
- const normalized = normalizePath(path);
93
- return normalized === "/" ? "" : normalized.slice(1);
97
+ const normalized = normalizePath(path);
98
+ return normalized === "/" ? "" : normalized.slice(1);
94
99
  }
100
+ /**
101
+ * Encode each `/`-delimited segment of an object key with `encodeURIComponent`
102
+ * so reserved URL characters (`?`, `#`, `%`, `&`, `+`, spaces, etc.) are
103
+ * treated as part of the key instead of URL syntax. Kept segment-aware so
104
+ * `/` continues to act as a path separator on the wire.
105
+ */
95
106
  function encodeKeyPath(key) {
96
- return key.split("/").map(encodeURIComponent).join("/");
107
+ return key.split("/").map(encodeURIComponent).join("/");
97
108
  }
98
109
  function nameFromPath(path) {
99
- const normalized = normalizePath(path);
100
- if (normalized === "/") return "";
101
- return normalized.slice(normalized.lastIndexOf("/") + 1);
110
+ const normalized = normalizePath(path);
111
+ if (normalized === "/") return "";
112
+ return normalized.slice(normalized.lastIndexOf("/") + 1);
102
113
  }
103
114
  function contentToBody(content) {
104
- if (typeof content === "string") return content;
105
- return Buffer.from(content);
115
+ if (typeof content === "string") return content;
116
+ return Buffer.from(content);
106
117
  }
107
118
  function headerDate(headers, name) {
108
- const value = headers.get(name);
109
- return value ? new Date(value) : /* @__PURE__ */ new Date(0);
119
+ const value = headers.get(name);
120
+ return value ? new Date(value) : /* @__PURE__ */ new Date(0);
110
121
  }
111
122
  function headerSize(headers) {
112
- const value = headers.get("content-length");
113
- return value ? Number(value) : 0;
123
+ const value = headers.get("content-length");
124
+ return value ? Number(value) : 0;
114
125
  }
115
126
  function isNotFound(error) {
116
- return typeof error === "object" && error !== null && "status" in error && error.status === 404;
127
+ return typeof error === "object" && error !== null && "status" in error && error.status === 404;
117
128
  }
118
129
  var PlatformFilesystem = class extends MastraFilesystem {
119
- id;
120
- name = "PlatformFilesystem";
121
- provider = "platform";
122
- readOnly;
123
- displayName;
124
- icon;
125
- description;
126
- status = "pending";
127
- _client;
128
- _bucketName;
129
- _instructionsOverride;
130
- constructor(options = {}) {
131
- super({ ...options, name: "PlatformFilesystem" });
132
- this.id = options.id ?? this.generateId();
133
- this._bucketName = options.bucketName ?? process.env.MASTRA_PLATFORM_BUCKET_NAME ?? "";
134
- if (!this._bucketName) throw new Error("bucketName is required");
135
- this.readOnly = options.readOnly;
136
- this.displayName = options.displayName;
137
- this.icon = options.icon ?? "cloud";
138
- this.description = options.description;
139
- this._instructionsOverride = options.instructions;
140
- this._client = new PlatformClient(options);
141
- }
142
- generateId() {
143
- return `platform-fs-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
144
- }
145
- async readFile(path, options) {
146
- await this.ensureReady();
147
- let response;
148
- try {
149
- response = await this._client.request(
150
- `/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(keyFromPath(path))}`
151
- );
152
- } catch (error) {
153
- if (isNotFound(error)) throw new FileNotFoundError(path);
154
- throw error;
155
- }
156
- const buffer = Buffer.from(await response.arrayBuffer());
157
- return options?.encoding ? buffer.toString(options.encoding) : buffer;
158
- }
159
- async writeFile(path, content, options) {
160
- await this.ensureReady();
161
- if (this.readOnly) throw new WorkspaceReadOnlyError("writeFile");
162
- const headers = {};
163
- if (options?.mimeType) headers["content-type"] = options.mimeType;
164
- if (options?.overwrite === false) headers["if-none-match"] = "*";
165
- try {
166
- await this._client.request(`/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(keyFromPath(path))}`, {
167
- method: "PUT",
168
- headers,
169
- body: contentToBody(content)
170
- });
171
- } catch (error) {
172
- if (typeof error === "object" && error !== null && "status" in error && error.status === 412) {
173
- throw new FileExistsError(path);
174
- }
175
- throw error;
176
- }
177
- }
178
- /**
179
- * Append bytes to a file.
180
- *
181
- * **Not atomic.** Object storage behind the workspace proxy has no native
182
- * append or compare-and-swap primitive, so this implementation is a
183
- * read-modify-write: it reads the current contents, concatenates the new
184
- * bytes, and PUTs the whole object back. Concurrent `appendFile` calls to
185
- * the same path can overwrite each other's writes ("last write wins").
186
- * Use `writeFile` with distinct keys for concurrent writers.
187
- */
188
- async appendFile(path, content) {
189
- const existing = await this.exists(path) ? await this.readFile(path) : Buffer.alloc(0);
190
- await this.writeFile(
191
- path,
192
- Buffer.concat([Buffer.isBuffer(existing) ? existing : Buffer.from(existing), Buffer.from(content)])
193
- );
194
- }
195
- async deleteFile(path, options) {
196
- await this.ensureReady();
197
- if (this.readOnly) throw new WorkspaceReadOnlyError("deleteFile");
198
- try {
199
- await this._client.request(`/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(keyFromPath(path))}`, {
200
- method: "DELETE",
201
- query: { recursive: options?.recursive }
202
- });
203
- } catch (error) {
204
- if (isNotFound(error) && options?.force) return;
205
- if (isNotFound(error)) throw new FileNotFoundError(path);
206
- throw error;
207
- }
208
- }
209
- async copyFile(src, dest, options) {
210
- await this.ensureReady();
211
- if (this.readOnly) throw new WorkspaceReadOnlyError("copyFile");
212
- if (options?.overwrite === false) {
213
- throw new Error("PlatformFilesystem.copyFile does not support overwrite: false \u2014 the proxy always overwrites.");
214
- }
215
- await this._client.request(`/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(keyFromPath(src))}`, {
216
- method: "POST",
217
- query: { op: "copy" },
218
- headers: { "content-type": "application/json" },
219
- body: JSON.stringify({ destination: keyFromPath(dest) })
220
- });
221
- }
222
- async moveFile(src, dest, options) {
223
- await this.ensureReady();
224
- if (this.readOnly) throw new WorkspaceReadOnlyError("moveFile");
225
- if (options?.overwrite === false) {
226
- throw new Error("PlatformFilesystem.moveFile does not support overwrite: false \u2014 the proxy always overwrites.");
227
- }
228
- await this._client.request(`/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(keyFromPath(src))}`, {
229
- method: "POST",
230
- query: { op: "rename" },
231
- headers: { "content-type": "application/json" },
232
- body: JSON.stringify({ destination: keyFromPath(dest) })
233
- });
234
- }
235
- async mkdir(path, _options) {
236
- await this.ensureReady();
237
- if (this.readOnly) throw new WorkspaceReadOnlyError("mkdir");
238
- await this._client.request(`/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(keyFromPath(path))}`, {
239
- method: "POST",
240
- query: { op: "mkdir" }
241
- });
242
- }
243
- async rmdir(path, options) {
244
- await this.deleteFile(path.endsWith("/") ? path : `${path}/`, { recursive: true, force: options?.force });
245
- }
246
- async readdir(path, options) {
247
- await this.ensureReady();
248
- const prefix = keyFromPath(path);
249
- const response = await this._client.request(
250
- `/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(prefix)}`,
251
- {
252
- query: {
253
- delimiter: options?.recursive ? void 0 : "/",
254
- prefix: prefix ? `${prefix.replace(/\/$/, "")}/` : void 0
255
- }
256
- }
257
- );
258
- const json = await response.json();
259
- return [
260
- ...(json.commonPrefixes ?? []).map((prefix2) => ({
261
- name: nameFromPath(prefix2.replace(/\/$/, "")),
262
- type: "directory"
263
- })),
264
- ...(json.contents ?? []).filter((object) => object.key && !object.key.endsWith("/")).map((object) => ({
265
- name: nameFromPath(object.key),
266
- type: "file",
267
- size: object.size
268
- }))
269
- ].filter(
270
- (entry) => !options?.extension || entry.type === "directory" || matchesExtension(entry.name, options.extension)
271
- );
272
- }
273
- async exists(path) {
274
- try {
275
- await this.stat(path);
276
- return true;
277
- } catch (error) {
278
- if (isNotFound(error) || error instanceof FileNotFoundError) return false;
279
- throw error;
280
- }
281
- }
282
- async stat(path) {
283
- await this.ensureReady();
284
- const normalized = normalizePath(path);
285
- if (normalized === "/") {
286
- return { name: "", path: "/", type: "directory", size: 0, createdAt: /* @__PURE__ */ new Date(0), modifiedAt: /* @__PURE__ */ new Date(0) };
287
- }
288
- let response;
289
- try {
290
- response = await this._client.request(
291
- `/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(keyFromPath(path))}`,
292
- {
293
- method: "HEAD"
294
- }
295
- );
296
- } catch (error) {
297
- if (isNotFound(error)) throw new FileNotFoundError(path);
298
- throw error;
299
- }
300
- return {
301
- name: nameFromPath(path),
302
- path: normalized,
303
- type: normalized.endsWith("/") ? "directory" : "file",
304
- size: headerSize(response.headers),
305
- createdAt: headerDate(response.headers, "last-modified"),
306
- modifiedAt: headerDate(response.headers, "last-modified"),
307
- mimeType: response.headers.get("content-type") ?? void 0
308
- };
309
- }
310
- realpath(path) {
311
- return Promise.resolve(normalizePath(path));
312
- }
313
- getInstructions(opts) {
314
- const defaultInstructions = `Platform filesystem backed by Mastra Platform bucket ${this._bucketName}. Use absolute workspace paths.`;
315
- if (typeof this._instructionsOverride === "function") {
316
- return this._instructionsOverride({ defaultInstructions, requestContext: opts?.requestContext });
317
- }
318
- if (typeof this._instructionsOverride === "string") return this._instructionsOverride;
319
- return defaultInstructions;
320
- }
321
- getInfo() {
322
- return {
323
- id: this.id,
324
- name: this.name,
325
- provider: this.provider,
326
- status: this.status,
327
- readOnly: this.readOnly,
328
- icon: this.icon,
329
- metadata: {
330
- bucketName: this._bucketName,
331
- ...this.displayName && { displayName: this.displayName },
332
- ...this.description && { description: this.description }
333
- }
334
- };
335
- }
130
+ id;
131
+ name = "PlatformFilesystem";
132
+ provider = "platform";
133
+ readOnly;
134
+ displayName;
135
+ icon;
136
+ description;
137
+ status = "pending";
138
+ _client;
139
+ _bucketName;
140
+ _instructionsOverride;
141
+ constructor(options = {}) {
142
+ super({
143
+ ...options,
144
+ name: "PlatformFilesystem"
145
+ });
146
+ this.id = options.id ?? this.generateId();
147
+ this._bucketName = options.bucketName ?? process.env.MASTRA_PLATFORM_BUCKET_NAME ?? "";
148
+ if (!this._bucketName) throw new Error("bucketName is required");
149
+ this.readOnly = options.readOnly;
150
+ this.displayName = options.displayName;
151
+ this.icon = options.icon ?? "cloud";
152
+ this.description = options.description;
153
+ this._instructionsOverride = options.instructions;
154
+ this._client = new PlatformClient(options);
155
+ }
156
+ generateId() {
157
+ return `platform-fs-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
158
+ }
159
+ async readFile(path, options) {
160
+ await this.ensureReady();
161
+ let response;
162
+ try {
163
+ response = await this._client.request(`/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(keyFromPath(path))}`);
164
+ } catch (error) {
165
+ if (isNotFound(error)) throw new FileNotFoundError(path);
166
+ throw error;
167
+ }
168
+ const buffer = Buffer.from(await response.arrayBuffer());
169
+ return options?.encoding ? buffer.toString(options.encoding) : buffer;
170
+ }
171
+ async writeFile(path, content, options) {
172
+ await this.ensureReady();
173
+ if (this.readOnly) throw new WorkspaceReadOnlyError("writeFile");
174
+ const headers = {};
175
+ if (options?.mimeType) headers["content-type"] = options.mimeType;
176
+ if (options?.overwrite === false) headers["if-none-match"] = "*";
177
+ try {
178
+ await this._client.request(`/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(keyFromPath(path))}`, {
179
+ method: "PUT",
180
+ headers,
181
+ body: contentToBody(content)
182
+ });
183
+ } catch (error) {
184
+ if (typeof error === "object" && error !== null && "status" in error && error.status === 412) throw new FileExistsError(path);
185
+ throw error;
186
+ }
187
+ }
188
+ /**
189
+ * Append bytes to a file.
190
+ *
191
+ * **Not atomic.** Object storage behind the workspace proxy has no native
192
+ * append or compare-and-swap primitive, so this implementation is a
193
+ * read-modify-write: it reads the current contents, concatenates the new
194
+ * bytes, and PUTs the whole object back. Concurrent `appendFile` calls to
195
+ * the same path can overwrite each other's writes ("last write wins").
196
+ * Use `writeFile` with distinct keys for concurrent writers.
197
+ */
198
+ async appendFile(path, content) {
199
+ const existing = await this.exists(path) ? await this.readFile(path) : Buffer.alloc(0);
200
+ await this.writeFile(path, Buffer.concat([Buffer.isBuffer(existing) ? existing : Buffer.from(existing), Buffer.from(content)]));
201
+ }
202
+ async deleteFile(path, options) {
203
+ await this.ensureReady();
204
+ if (this.readOnly) throw new WorkspaceReadOnlyError("deleteFile");
205
+ try {
206
+ await this._client.request(`/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(keyFromPath(path))}`, {
207
+ method: "DELETE",
208
+ query: { recursive: options?.recursive }
209
+ });
210
+ } catch (error) {
211
+ if (isNotFound(error) && options?.force) return;
212
+ if (isNotFound(error)) throw new FileNotFoundError(path);
213
+ throw error;
214
+ }
215
+ }
216
+ async copyFile(src, dest, options) {
217
+ await this.ensureReady();
218
+ if (this.readOnly) throw new WorkspaceReadOnlyError("copyFile");
219
+ if (options?.overwrite === false) throw new Error("PlatformFilesystem.copyFile does not support overwrite: false — the proxy always overwrites.");
220
+ await this._client.request(`/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(keyFromPath(src))}`, {
221
+ method: "POST",
222
+ query: { op: "copy" },
223
+ headers: { "content-type": "application/json" },
224
+ body: JSON.stringify({ destination: keyFromPath(dest) })
225
+ });
226
+ }
227
+ async moveFile(src, dest, options) {
228
+ await this.ensureReady();
229
+ if (this.readOnly) throw new WorkspaceReadOnlyError("moveFile");
230
+ if (options?.overwrite === false) throw new Error("PlatformFilesystem.moveFile does not support overwrite: false — the proxy always overwrites.");
231
+ await this._client.request(`/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(keyFromPath(src))}`, {
232
+ method: "POST",
233
+ query: { op: "rename" },
234
+ headers: { "content-type": "application/json" },
235
+ body: JSON.stringify({ destination: keyFromPath(dest) })
236
+ });
237
+ }
238
+ async mkdir(path, _options) {
239
+ await this.ensureReady();
240
+ if (this.readOnly) throw new WorkspaceReadOnlyError("mkdir");
241
+ await this._client.request(`/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(keyFromPath(path))}`, {
242
+ method: "POST",
243
+ query: { op: "mkdir" }
244
+ });
245
+ }
246
+ async rmdir(path, options) {
247
+ await this.deleteFile(path.endsWith("/") ? path : `${path}/`, {
248
+ recursive: true,
249
+ force: options?.force
250
+ });
251
+ }
252
+ async readdir(path, options) {
253
+ await this.ensureReady();
254
+ const prefix = keyFromPath(path);
255
+ const json = await (await this._client.request(`/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(prefix)}`, { query: {
256
+ delimiter: options?.recursive ? void 0 : "/",
257
+ prefix: prefix ? `${prefix.replace(/\/$/, "")}/` : void 0
258
+ } })).json();
259
+ return [...(json.commonPrefixes ?? []).map((prefix) => ({
260
+ name: nameFromPath(prefix.replace(/\/$/, "")),
261
+ type: "directory"
262
+ })), ...(json.contents ?? []).filter((object) => object.key && !object.key.endsWith("/")).map((object) => ({
263
+ name: nameFromPath(object.key),
264
+ type: "file",
265
+ size: object.size
266
+ }))].filter((entry) => !options?.extension || entry.type === "directory" || matchesExtension(entry.name, options.extension));
267
+ }
268
+ async exists(path) {
269
+ try {
270
+ await this.stat(path);
271
+ return true;
272
+ } catch (error) {
273
+ if (isNotFound(error) || error instanceof FileNotFoundError) return false;
274
+ throw error;
275
+ }
276
+ }
277
+ async stat(path) {
278
+ await this.ensureReady();
279
+ const normalized = normalizePath(path);
280
+ if (normalized === "/") return {
281
+ name: "",
282
+ path: "/",
283
+ type: "directory",
284
+ size: 0,
285
+ createdAt: /* @__PURE__ */ new Date(0),
286
+ modifiedAt: /* @__PURE__ */ new Date(0)
287
+ };
288
+ let response;
289
+ try {
290
+ response = await this._client.request(`/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(keyFromPath(path))}`, { method: "HEAD" });
291
+ } catch (error) {
292
+ if (isNotFound(error)) throw new FileNotFoundError(path);
293
+ throw error;
294
+ }
295
+ return {
296
+ name: nameFromPath(path),
297
+ path: normalized,
298
+ type: normalized.endsWith("/") ? "directory" : "file",
299
+ size: headerSize(response.headers),
300
+ createdAt: headerDate(response.headers, "last-modified"),
301
+ modifiedAt: headerDate(response.headers, "last-modified"),
302
+ mimeType: response.headers.get("content-type") ?? void 0
303
+ };
304
+ }
305
+ realpath(path) {
306
+ return Promise.resolve(normalizePath(path));
307
+ }
308
+ getInstructions(opts) {
309
+ const defaultInstructions = `Platform filesystem backed by Mastra Platform bucket ${this._bucketName}. Use absolute workspace paths.`;
310
+ if (typeof this._instructionsOverride === "function") return this._instructionsOverride({
311
+ defaultInstructions,
312
+ requestContext: opts?.requestContext
313
+ });
314
+ if (typeof this._instructionsOverride === "string") return this._instructionsOverride;
315
+ return defaultInstructions;
316
+ }
317
+ getInfo() {
318
+ return {
319
+ id: this.id,
320
+ name: this.name,
321
+ provider: this.provider,
322
+ status: this.status,
323
+ readOnly: this.readOnly,
324
+ icon: this.icon,
325
+ metadata: {
326
+ bucketName: this._bucketName,
327
+ ...this.displayName && { displayName: this.displayName },
328
+ ...this.description && { description: this.description }
329
+ }
330
+ };
331
+ }
336
332
  };
337
333
  function matchesExtension(name, extension) {
338
- const extensions = Array.isArray(extension) ? extension : [extension];
339
- return extensions.some((ext) => name.endsWith(ext));
334
+ return (Array.isArray(extension) ? extension : [extension]).some((ext) => name.endsWith(ext));
335
+ }
336
+ //#endregion
337
+ //#region src/direct-exec.ts
338
+ /**
339
+ * Direct exec client — opens Railway's tcp-proxy exec WebSocket directly using
340
+ * a short-lived JWT minted by the workspace proxy's exec-lease endpoint. This
341
+ * removes the platform data plane from the exec stdout/stderr path entirely
342
+ * (see `docs/factory/direct-sandbox-connection.md` in the Platform repo),
343
+ * cutting payload-scaled Cloud Run egress and RTT for commands like
344
+ * `pnpm install` that stream tens of MB of output.
345
+ *
346
+ * The frame protocol below mirrors `connectExecWs()` in `railway@3.5.5`
347
+ * (`workspaces/railway/node_modules/railway/dist/index.js`). The `railway`
348
+ * SDK's version is pinned on both sides (platform + here); a version bump
349
+ * signals the protocol may have drifted and this module must be revisited.
350
+ */
351
+ /** Byte-0 tag on binary WS frames for stdout output. */
352
+ const STDOUT_FRAME = 1;
353
+ /** Byte-0 tag on binary WS frames for stderr output. */
354
+ const STDERR_FRAME = 3;
355
+ /**
356
+ * Upper bound on how long we'll wait for the WebSocket to open when the
357
+ * caller didn't supply a `timeoutMs`. Guards against a stalled TLS/WS
358
+ * handshake leaving the promise unresolved forever. Not applied once the
359
+ * socket has opened — a caller with no timeout has opted in to unbounded
360
+ * command runtime, just not to unbounded connection setup.
361
+ */
362
+ const HANDSHAKE_DEADLINE_MS = 3e4;
363
+ const DEFAULT_WS_FACTORY = (endpoint, subprotocols) => {
364
+ const WS = globalThis.WebSocket;
365
+ if (!WS) throw new Error("Direct exec requires a WebSocket implementation. Node 22+ provides one globally; on older runtimes, pass webSocketFactory explicitly.");
366
+ return new WS(endpoint, subprotocols);
367
+ };
368
+ /**
369
+ * Open the provider exec WebSocket using `lease`, run `command`, and resolve
370
+ * with the accumulated stdout/stderr + exit code. See the module docstring
371
+ * for the wire protocol reference.
372
+ *
373
+ * The client sends `stdin_close` immediately after `init_exec`, matching the
374
+ * SDK's own one-shot exec behavior — we never stream stdin from the caller.
375
+ */
376
+ function execViaLease(lease, options) {
377
+ const factory = options.webSocketFactory ?? DEFAULT_WS_FACTORY;
378
+ const stdoutDecoder = new TextDecoder();
379
+ const stderrDecoder = new TextDecoder();
380
+ return new Promise((resolve) => {
381
+ let stdout = "";
382
+ let stderr = "";
383
+ let exitCode = null;
384
+ let timedOut = false;
385
+ let settled = false;
386
+ let opened = false;
387
+ let timer;
388
+ let handshakeTimer;
389
+ const settle = () => {
390
+ if (settled) return;
391
+ settled = true;
392
+ if (timer) clearTimeout(timer);
393
+ if (handshakeTimer) clearTimeout(handshakeTimer);
394
+ const stdoutTail = stdoutDecoder.decode();
395
+ if (stdoutTail) {
396
+ stdout += stdoutTail;
397
+ options.onStdout?.(stdoutTail);
398
+ }
399
+ const stderrTail = stderrDecoder.decode();
400
+ if (stderrTail) {
401
+ stderr += stderrTail;
402
+ options.onStderr?.(stderrTail);
403
+ }
404
+ try {
405
+ socket.close(1e3, "");
406
+ } catch {}
407
+ resolve({
408
+ exitCode,
409
+ stdout,
410
+ stderr,
411
+ truncated: false,
412
+ timedOut
413
+ });
414
+ };
415
+ if (options.timeoutMs !== void 0 && options.timeoutMs > 0) timer = setTimeout(() => {
416
+ timedOut = true;
417
+ if (exitCode === null) exitCode = 124;
418
+ settle();
419
+ }, options.timeoutMs);
420
+ else handshakeTimer = setTimeout(() => {
421
+ if (!opened) settle();
422
+ }, HANDSHAKE_DEADLINE_MS);
423
+ const socket = factory(lease.wsEndpoint, [lease.subprotocol, lease.jwt]);
424
+ socket.binaryType = "arraybuffer";
425
+ socket.onopen = () => {
426
+ opened = true;
427
+ if (handshakeTimer) {
428
+ clearTimeout(handshakeTimer);
429
+ handshakeTimer = void 0;
430
+ }
431
+ const data = { command: options.command };
432
+ if (options.cwd) data.cwd = options.cwd;
433
+ if (options.env && Object.keys(options.env).length > 0) data.env = options.env;
434
+ socket.send(JSON.stringify({
435
+ type: "init_exec",
436
+ data
437
+ }));
438
+ socket.send(JSON.stringify({ type: "stdin_close" }));
439
+ };
440
+ socket.onmessage = (event) => {
441
+ const { data } = event;
442
+ if (data instanceof ArrayBuffer) handleBinaryFrame(data);
443
+ else if (typeof data === "string") handleTextFrame(data);
444
+ };
445
+ socket.onclose = (event) => {
446
+ if (!opened) {
447
+ settle();
448
+ return;
449
+ }
450
+ settle();
451
+ };
452
+ socket.onerror = () => {
453
+ if (settled) return;
454
+ if (!opened) settle();
455
+ };
456
+ function handleBinaryFrame(buffer) {
457
+ const view = new Uint8Array(buffer);
458
+ if (view.length <= 1) return;
459
+ if (view[0] === STDOUT_FRAME) {
460
+ const chunk = stdoutDecoder.decode(view.subarray(1), { stream: true });
461
+ stdout += chunk;
462
+ options.onStdout?.(chunk);
463
+ } else if (view[0] === STDERR_FRAME) {
464
+ const chunk = stderrDecoder.decode(view.subarray(1), { stream: true });
465
+ stderr += chunk;
466
+ options.onStderr?.(chunk);
467
+ }
468
+ }
469
+ function handleTextFrame(text) {
470
+ let frame;
471
+ try {
472
+ frame = JSON.parse(text);
473
+ } catch {
474
+ return;
475
+ }
476
+ if (frame.type === "exit") {
477
+ exitCode = frame.data?.exit_code ?? 0;
478
+ settle();
479
+ }
480
+ }
481
+ });
340
482
  }
483
+ //#endregion
484
+ //#region src/sandbox.ts
485
+ /**
486
+ * How long before a lease's stated `expiresAt` we should treat it as
487
+ * expired. Avoids a race where the JWT is valid at cache-hit time but the
488
+ * server rejects it by the time the WebSocket handshake completes.
489
+ */
490
+ const LEASE_REFRESH_MARGIN_MS = 6e4;
491
+ /** Max attempts for `POST /sandbox` when the proxy returns transient 5xx errors. */
492
+ const CREATE_MAX_ATTEMPTS = 3;
493
+ /** Base delay between create retries; multiplied by the attempt number. */
494
+ const CREATE_RETRY_BASE_DELAY_MS = 2e3;
495
+ /**
496
+ * Compose a shell command line from a `command` string and optional `args`.
497
+ *
498
+ * IMPORTANT: `command` is treated as a **shell string** and passed to the
499
+ * remote shell verbatim so callers can use pipes, redirects, and chaining
500
+ * (`ls -la | grep foo`). This matches the contract of {@link MastraSandbox}
501
+ * and the local sandbox implementation. `args` are always shell-quoted so
502
+ * they cannot inject syntax.
503
+ *
504
+ * Callers MUST NOT pass untrusted input as `command`. Untrusted values must
505
+ * be passed via `args`, where they are safely quoted. Passing untrusted
506
+ * input as `command` allows arbitrary shell syntax execution on the remote
507
+ * sandbox.
508
+ */
341
509
  function buildCommand(command, args) {
342
- return args?.length ? `${command} ${args.map(shellQuote).join(" ")}` : command;
510
+ return args?.length ? `${command} ${args.map(shellQuote).join(" ")}` : command;
343
511
  }
344
512
  function shellQuote(arg) {
345
- if (/^[a-zA-Z0-9._\-/=:@]+$/.test(arg)) return arg;
346
- return `'${arg.replace(/'/g, `'\\''`)}'`;
513
+ if (/^[a-zA-Z0-9._\-/=:@]+$/.test(arg)) return arg;
514
+ return `'${arg.replace(/'/g, `'\\''`)}'`;
347
515
  }
348
516
  var PlatformProcessHandle = class extends ProcessHandle {
349
- pid;
350
- resultPromise;
351
- exitCodeValue;
352
- constructor(pid, resultPromise, options) {
353
- super(options);
354
- this.pid = pid;
355
- this.resultPromise = resultPromise.then((result) => {
356
- this.exitCodeValue = result.exitCode;
357
- if (result.stdout) this.emitStdout(result.stdout);
358
- if (result.stderr) this.emitStderr(result.stderr);
359
- return result;
360
- });
361
- }
362
- get exitCode() {
363
- return this.exitCodeValue;
364
- }
365
- async wait() {
366
- return this.resultPromise;
367
- }
368
- async kill() {
369
- throw new Error("Platform sandbox command execution does not support killing individual processes");
370
- }
371
- async sendStdin() {
372
- throw new Error("Platform sandbox command execution does not support stdin");
373
- }
517
+ pid;
518
+ resultPromise;
519
+ exitCodeValue;
520
+ constructor(pid, resultPromise, options) {
521
+ super(options);
522
+ this.pid = pid;
523
+ this.resultPromise = resultPromise.then((result) => {
524
+ this.exitCodeValue = result.exitCode;
525
+ if (result.stdout) this.emitStdout(result.stdout);
526
+ if (result.stderr) this.emitStderr(result.stderr);
527
+ return result;
528
+ });
529
+ }
530
+ get exitCode() {
531
+ return this.exitCodeValue;
532
+ }
533
+ async wait() {
534
+ return this.resultPromise;
535
+ }
536
+ async kill() {
537
+ throw new Error("Platform sandbox command execution does not support killing individual processes");
538
+ }
539
+ async sendStdin() {
540
+ throw new Error("Platform sandbox command execution does not support stdin");
541
+ }
374
542
  };
375
543
  var PlatformProcessManager = class extends SandboxProcessManager {
376
- spawnCounter = 0;
377
- /**
378
- * Spawn a process on the remote sandbox.
379
- *
380
- * `command` is interpreted as a shell string by the remote shell, matching
381
- * the {@link MastraSandbox} contract. See {@link PlatformSandbox.executeCommand}
382
- * for the untrusted-input caveat: never pass untrusted values as `command`.
383
- */
384
- async spawn(command, options = {}) {
385
- const pid = `platform-proc-${Date.now().toString(36)}-${(this.spawnCounter++).toString(36)}`;
386
- const resultPromise = this.sandbox.executeCommand(command, void 0, options);
387
- const handle = new PlatformProcessHandle(pid, resultPromise, options);
388
- this._tracked.set(handle.pid, handle);
389
- return handle;
390
- }
391
- async list() {
392
- return Array.from(this._tracked.values()).map((handle) => ({
393
- pid: handle.pid,
394
- command: handle.command,
395
- running: handle.exitCode === void 0,
396
- ...handle.exitCode !== void 0 && { exitCode: handle.exitCode }
397
- }));
398
- }
544
+ spawnCounter = 0;
545
+ /**
546
+ * Spawn a process on the remote sandbox.
547
+ *
548
+ * `command` is interpreted as a shell string by the remote shell, matching
549
+ * the {@link MastraSandbox} contract. See {@link PlatformSandbox.executeCommand}
550
+ * for the untrusted-input caveat: never pass untrusted values as `command`.
551
+ */
552
+ async spawn(command, options = {}) {
553
+ const handle = new PlatformProcessHandle(`platform-proc-${Date.now().toString(36)}-${(this.spawnCounter++).toString(36)}`, this.sandbox.executeCommand(command, void 0, options), options);
554
+ this._tracked.set(handle.pid, handle);
555
+ return handle;
556
+ }
557
+ async list() {
558
+ return Array.from(this._tracked.values()).map((handle) => ({
559
+ pid: handle.pid,
560
+ command: handle.command,
561
+ running: handle.exitCode === void 0,
562
+ ...handle.exitCode !== void 0 && { exitCode: handle.exitCode }
563
+ }));
564
+ }
399
565
  };
400
- var PlatformSandbox = class _PlatformSandbox extends MastraSandbox {
401
- id;
402
- name = "PlatformSandbox";
403
- provider = "platform";
404
- status = "pending";
405
- _client;
406
- _environmentId;
407
- _sandboxId;
408
- _idleTimeoutMinutes;
409
- _networkIsolation;
410
- _env;
411
- _timeout;
412
- _instructionsOverride;
413
- _createdAt = null;
414
- constructor(options = {}) {
415
- super({ ...options, name: "PlatformSandbox", processes: new PlatformProcessManager() });
416
- this.id = options.id ?? this.generateId();
417
- this._client = new PlatformClient(options);
418
- this._environmentId = options.environmentId ?? process.env.MASTRA_ENVIRONMENT_ID ?? "";
419
- if (!this._environmentId && !options.sandboxId) throw new Error("environmentId is required");
420
- this._sandboxId = options.sandboxId;
421
- this._idleTimeoutMinutes = options.idleTimeoutMinutes;
422
- this._networkIsolation = options.networkIsolation;
423
- this._env = options.env ?? {};
424
- this._timeout = options.timeout;
425
- this._instructionsOverride = options.instructions;
426
- }
427
- generateId() {
428
- return `platform-sandbox-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
429
- }
430
- /**
431
- * Construct a sibling {@link PlatformSandbox} that inherits this sandbox's
432
- * credentials and defaults (access token, project, environment, network
433
- * isolation, timeout, instructions, env, idle timeout) with per-instance
434
- * overrides from `options`.
435
- *
436
- * Performs no I/O and does not require this sandbox to be started — the
437
- * returned sandbox is not started and provisions (or reattaches, when
438
- * `sandboxId` is set) on its own `start()`. Use it when one configured
439
- * sandbox acts as the template for a fleet of independent sandboxes
440
- * (e.g. one per project).
441
- */
442
- clone(options = {}) {
443
- return new _PlatformSandbox({
444
- ...options.id !== void 0 && { id: options.id },
445
- accessToken: this._client.accessToken,
446
- projectId: this._client.projectId,
447
- fetch: this._client.fetch,
448
- environmentId: this._environmentId,
449
- ...options.sandboxId !== void 0 && { sandboxId: options.sandboxId },
450
- idleTimeoutMinutes: options.idleTimeoutMinutes ?? this._idleTimeoutMinutes,
451
- ...this._networkIsolation !== void 0 && { networkIsolation: this._networkIsolation },
452
- env: options.env ?? this._env,
453
- ...this._timeout !== void 0 && { timeout: this._timeout },
454
- ...this._instructionsOverride !== void 0 && { instructions: this._instructionsOverride }
455
- });
456
- }
457
- async start() {
458
- if (this._sandboxId) {
459
- try {
460
- const response2 = await this._client.request(`/sandbox/${encodeURIComponent(this._sandboxId)}`);
461
- const json2 = await response2.json();
462
- this._createdAt = json2.createdAt ? new Date(json2.createdAt) : /* @__PURE__ */ new Date();
463
- return;
464
- } catch (error) {
465
- if (!(error instanceof PlatformApiError) || error.status !== 404) throw error;
466
- this._sandboxId = void 0;
467
- }
468
- }
469
- if (!this._environmentId) throw new Error("environmentId is required");
470
- const response = await this._client.request("/sandbox", {
471
- method: "POST",
472
- headers: { "content-type": "application/json" },
473
- body: JSON.stringify({
474
- // Sent so the platform can associate the provisioned resource with a
475
- // caller-stable identifier (used for opt-in checkpoint recovery). The
476
- // platform treats it as an advisory key: unknown values fall through
477
- // to a fresh sandbox, matching pre-existing behavior.
478
- id: this.id,
479
- environmentId: this._environmentId,
480
- idleTimeoutMinutes: this._idleTimeoutMinutes,
481
- networkIsolation: this._networkIsolation,
482
- env: this._env
483
- })
484
- });
485
- const json = await response.json();
486
- this._sandboxId = json.id;
487
- this._createdAt = json.createdAt ? new Date(json.createdAt) : /* @__PURE__ */ new Date();
488
- }
489
- async stop() {
490
- await this.destroy();
491
- }
492
- async destroy() {
493
- if (!this._sandboxId) return;
494
- await this._client.request(`/sandbox/${encodeURIComponent(this._sandboxId)}`, { method: "DELETE" });
495
- this._sandboxId = void 0;
496
- this._createdAt = null;
497
- }
498
- /**
499
- * Execute a command on the remote sandbox.
500
- *
501
- * `command` is a **shell string**: it is concatenated verbatim into the
502
- * command line sent to the remote shell, which lets callers use pipes,
503
- * redirects, and chaining (`ls -la | grep foo`). This matches the contract
504
- * of {@link MastraSandbox} and the local sandbox implementation.
505
- *
506
- * `args`, when provided, are always shell-quoted so they cannot inject
507
- * additional shell syntax.
508
- *
509
- * Security: callers MUST NOT pass untrusted input as `command`. If any part
510
- * of the invocation is derived from an untrusted source, pass it through
511
- * `args` (which is safely quoted) or shell-quote it yourself before
512
- * inclusion. Untrusted `command` values allow arbitrary shell syntax
513
- * execution on the remote sandbox.
514
- */
515
- async executeCommand(command, args, options) {
516
- await this.ensureRunning();
517
- if (!this._sandboxId) throw new SandboxNotReadyError(this.id);
518
- const started = Date.now();
519
- const fullCommand = buildCommand(command, args);
520
- const effectiveTimeout = options?.timeout ?? this._timeout;
521
- const timeoutSec = effectiveTimeout != null ? Math.ceil(effectiveTimeout / 1e3) : void 0;
522
- const clientSignal = effectiveTimeout != null && effectiveTimeout > 0 ? AbortSignal.timeout(effectiveTimeout + 3e4) : void 0;
523
- const response = await this._client.request(`/sandbox/${encodeURIComponent(this._sandboxId)}/exec`, {
524
- method: "POST",
525
- headers: { "content-type": "application/json" },
526
- body: JSON.stringify({
527
- command: fullCommand,
528
- timeoutSec,
529
- cwd: options?.cwd,
530
- env: options?.env
531
- }),
532
- signal: clientSignal
533
- });
534
- const json = await response.json();
535
- const exitCode = json.exitCode ?? (json.timedOut ? 124 : 1);
536
- return {
537
- success: exitCode === 0,
538
- exitCode,
539
- stdout: json.stdout,
540
- stderr: json.stderr,
541
- executionTimeMs: Date.now() - started,
542
- timedOut: json.timedOut,
543
- command: fullCommand
544
- };
545
- }
546
- async getInfo() {
547
- if (!this._sandboxId) {
548
- return {
549
- id: this.id,
550
- name: this.name,
551
- provider: this.provider,
552
- status: this.status,
553
- createdAt: this._createdAt ?? /* @__PURE__ */ new Date()
554
- };
555
- }
556
- const response = await this._client.request(`/sandbox/${encodeURIComponent(this._sandboxId)}`);
557
- const json = await response.json();
558
- return {
559
- id: json.id,
560
- name: this.name,
561
- provider: this.provider,
562
- status: this.status,
563
- createdAt: json.createdAt ? new Date(json.createdAt) : this._createdAt ?? /* @__PURE__ */ new Date(),
564
- metadata: {
565
- providerResourceId: json.providerResourceId ?? void 0,
566
- platformStatus: json.status
567
- }
568
- };
569
- }
570
- getInstructions(opts) {
571
- const defaultInstructions = `Platform sandbox${this._sandboxId ? ` ${this._sandboxId}` : ""}. Execute commands with the sandbox command APIs.`;
572
- if (typeof this._instructionsOverride === "function") {
573
- return this._instructionsOverride({ defaultInstructions, requestContext: opts?.requestContext });
574
- }
575
- if (typeof this._instructionsOverride === "string") return this._instructionsOverride;
576
- return defaultInstructions;
577
- }
566
+ var PlatformSandbox = class PlatformSandbox extends MastraSandbox {
567
+ id;
568
+ name = "PlatformSandbox";
569
+ provider = "platform";
570
+ status = "pending";
571
+ _client;
572
+ _environmentId;
573
+ _sandboxId;
574
+ _idleTimeoutMinutes;
575
+ _networkIsolation;
576
+ _env;
577
+ _timeout;
578
+ _instructionsOverride;
579
+ _createdAt = null;
580
+ _webSocketFactory;
581
+ /**
582
+ * Cached exec lease for this sandbox. `null` before the first exec and
583
+ * after {@link destroy}. Refreshed when `expiresAt - LEASE_REFRESH_MARGIN_MS < now`
584
+ * (see {@link _ensureLease}); a lease without a disclosed `expiresAt`
585
+ * is refreshed on every call.
586
+ */
587
+ _lease = null;
588
+ /**
589
+ * In-flight mint request; concurrent `_ensureLease` callers on a cold or
590
+ * near-expiry cache all await this single promise so we don't burn N
591
+ * `POST /exec-lease` round-trips when the sandbox is doing N parallel execs.
592
+ * Cleared (regardless of success or failure) when the request settles.
593
+ */
594
+ _leaseInFlight = null;
595
+ /**
596
+ * Tri-state feature detection for the platform's exec-lease endpoint:
597
+ * undefined not yet tried (default; try direct on first exec)
598
+ * true — endpoint present, use direct exec
599
+ * false — endpoint returned 404 or 501, fall back permanently to /exec
600
+ * Sticky per instance so we make the fallback decision once per sandbox
601
+ * lifetime instead of paying an extra round-trip on every exec.
602
+ */
603
+ _directExecAvailable = void 0;
604
+ constructor(options = {}) {
605
+ super({
606
+ ...options,
607
+ name: "PlatformSandbox",
608
+ processes: new PlatformProcessManager()
609
+ });
610
+ this.id = options.id ?? this.generateId();
611
+ this._client = new PlatformClient(options);
612
+ this._environmentId = options.environmentId ?? process.env.MASTRA_ENVIRONMENT_ID ?? "";
613
+ if (!this._environmentId && !options.sandboxId) throw new Error("environmentId is required");
614
+ this._sandboxId = options.sandboxId;
615
+ this._idleTimeoutMinutes = options.idleTimeoutMinutes;
616
+ this._networkIsolation = options.networkIsolation;
617
+ this._env = options.env ?? {};
618
+ this._timeout = options.timeout;
619
+ this._instructionsOverride = options.instructions;
620
+ this._webSocketFactory = options.webSocketFactory;
621
+ }
622
+ generateId() {
623
+ return `platform-sandbox-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
624
+ }
625
+ /**
626
+ * Construct a sibling {@link PlatformSandbox} that inherits this sandbox's
627
+ * credentials and defaults (access token, project, environment, network
628
+ * isolation, timeout, instructions, env, idle timeout) with per-instance
629
+ * overrides from `options`.
630
+ *
631
+ * Performs no I/O and does not require this sandbox to be started — the
632
+ * returned sandbox is not started and provisions (or reattaches, when
633
+ * `sandboxId` is set) on its own `start()`. Use it when one configured
634
+ * sandbox acts as the template for a fleet of independent sandboxes
635
+ * (e.g. one per project).
636
+ */
637
+ clone(options = {}) {
638
+ return new PlatformSandbox({
639
+ ...options.id !== void 0 && { id: options.id },
640
+ accessToken: this._client.accessToken,
641
+ projectId: this._client.projectId,
642
+ fetch: this._client.fetch,
643
+ environmentId: this._environmentId,
644
+ ...options.sandboxId !== void 0 && { sandboxId: options.sandboxId },
645
+ idleTimeoutMinutes: options.idleTimeoutMinutes ?? this._idleTimeoutMinutes,
646
+ ...this._networkIsolation !== void 0 && { networkIsolation: this._networkIsolation },
647
+ env: options.env ?? this._env,
648
+ ...this._timeout !== void 0 && { timeout: this._timeout },
649
+ ...this._instructionsOverride !== void 0 && { instructions: this._instructionsOverride },
650
+ ...this._webSocketFactory !== void 0 && { webSocketFactory: this._webSocketFactory }
651
+ });
652
+ }
653
+ async start() {
654
+ if (this._sandboxId) try {
655
+ const json = await (await this._client.request(`/sandbox/${encodeURIComponent(this._sandboxId)}`)).json();
656
+ if (!json.destroyedAt) {
657
+ this._createdAt = json.createdAt ? new Date(json.createdAt) : /* @__PURE__ */ new Date();
658
+ return;
659
+ }
660
+ this._sandboxId = void 0;
661
+ } catch (error) {
662
+ if (!(error instanceof PlatformApiError) || error.status !== 404) throw error;
663
+ this._sandboxId = void 0;
664
+ }
665
+ if (!this._environmentId) throw new Error("environmentId is required");
666
+ const body = JSON.stringify({
667
+ id: this.id,
668
+ environmentId: this._environmentId,
669
+ idleTimeoutMinutes: this._idleTimeoutMinutes,
670
+ networkIsolation: this._networkIsolation,
671
+ env: this._env
672
+ });
673
+ let response;
674
+ for (let attempt = 1;; attempt++) try {
675
+ response = await this._client.request("/sandbox", {
676
+ method: "POST",
677
+ headers: { "content-type": "application/json" },
678
+ body
679
+ });
680
+ break;
681
+ } catch (error) {
682
+ if (!(error instanceof PlatformApiError && error.status >= 500) || attempt >= CREATE_MAX_ATTEMPTS) throw error;
683
+ await new Promise((resolve) => setTimeout(resolve, CREATE_RETRY_BASE_DELAY_MS * attempt));
684
+ }
685
+ const json = await response.json();
686
+ this._sandboxId = json.id;
687
+ this._createdAt = json.createdAt ? new Date(json.createdAt) : /* @__PURE__ */ new Date();
688
+ }
689
+ async stop() {
690
+ await this.destroy();
691
+ }
692
+ async destroy() {
693
+ if (!this._sandboxId) return;
694
+ await this._client.request(`/sandbox/${encodeURIComponent(this._sandboxId)}`, { method: "DELETE" });
695
+ this._sandboxId = void 0;
696
+ this._createdAt = null;
697
+ this._lease = null;
698
+ }
699
+ /**
700
+ * Execute a command on the remote sandbox.
701
+ *
702
+ * `command` is a **shell string**: it is concatenated verbatim into the
703
+ * command line sent to the remote shell, which lets callers use pipes,
704
+ * redirects, and chaining (`ls -la | grep foo`). This matches the contract
705
+ * of {@link MastraSandbox} and the local sandbox implementation.
706
+ *
707
+ * `args`, when provided, are always shell-quoted so they cannot inject
708
+ * additional shell syntax.
709
+ *
710
+ * Security: callers MUST NOT pass untrusted input as `command`. If any part
711
+ * of the invocation is derived from an untrusted source, pass it through
712
+ * `args` (which is safely quoted) or shell-quote it yourself before
713
+ * inclusion. Untrusted `command` values allow arbitrary shell syntax
714
+ * execution on the remote sandbox.
715
+ */
716
+ async executeCommand(command, args, options) {
717
+ await this.ensureRunning();
718
+ if (!this._sandboxId) throw new SandboxNotReadyError(this.id);
719
+ const started = Date.now();
720
+ const fullCommand = buildCommand(command, args);
721
+ const effectiveTimeout = options?.timeout ?? this._timeout;
722
+ if (this._directExecAvailable !== false) {
723
+ const leaseResult = await this._tryDirectExec(fullCommand, effectiveTimeout, options);
724
+ if (leaseResult) return {
725
+ ...leaseResult,
726
+ executionTimeMs: Date.now() - started
727
+ };
728
+ }
729
+ return this._execViaProxy(fullCommand, effectiveTimeout, options, started);
730
+ }
731
+ async _tryDirectExec(fullCommand, effectiveTimeout, options) {
732
+ let lease;
733
+ try {
734
+ lease = await this._ensureLease();
735
+ } catch (error) {
736
+ if (error instanceof PlatformApiError && (error.status === 404 || error.status === 501)) {
737
+ this._directExecAvailable = false;
738
+ return null;
739
+ }
740
+ throw error;
741
+ }
742
+ this._directExecAvailable = true;
743
+ const filteredEnv = options?.env ? Object.fromEntries(Object.entries(options.env).filter((entry) => entry[1] !== void 0)) : void 0;
744
+ const result = await execViaLease(lease, {
745
+ command: fullCommand,
746
+ ...options?.cwd !== void 0 && { cwd: options.cwd },
747
+ ...filteredEnv !== void 0 && { env: filteredEnv },
748
+ ...effectiveTimeout != null && effectiveTimeout > 0 && { timeoutMs: effectiveTimeout },
749
+ ...this._webSocketFactory && { webSocketFactory: this._webSocketFactory }
750
+ });
751
+ if (result.exitCode === null && !result.timedOut) {
752
+ this._lease = null;
753
+ return null;
754
+ }
755
+ const exitCode = result.exitCode ?? 124;
756
+ return {
757
+ success: exitCode === 0,
758
+ exitCode,
759
+ stdout: result.stdout,
760
+ stderr: result.stderr,
761
+ timedOut: result.timedOut,
762
+ command: fullCommand
763
+ };
764
+ }
765
+ async _execViaProxy(fullCommand, effectiveTimeout, options, started) {
766
+ if (!this._sandboxId) throw new SandboxNotReadyError(this.id);
767
+ const timeoutSec = effectiveTimeout != null ? Math.ceil(effectiveTimeout / 1e3) : void 0;
768
+ const clientSignal = effectiveTimeout != null && effectiveTimeout > 0 ? AbortSignal.timeout(effectiveTimeout + 3e4) : void 0;
769
+ const json = await (await this._client.request(`/sandbox/${encodeURIComponent(this._sandboxId)}/exec`, {
770
+ method: "POST",
771
+ headers: { "content-type": "application/json" },
772
+ body: JSON.stringify({
773
+ command: fullCommand,
774
+ timeoutSec,
775
+ cwd: options?.cwd,
776
+ env: options?.env
777
+ }),
778
+ signal: clientSignal
779
+ })).json();
780
+ const exitCode = json.exitCode ?? (json.timedOut ? 124 : 1);
781
+ return {
782
+ success: exitCode === 0,
783
+ exitCode,
784
+ stdout: json.stdout,
785
+ stderr: json.stderr,
786
+ executionTimeMs: Date.now() - started,
787
+ timedOut: json.timedOut,
788
+ command: fullCommand
789
+ };
790
+ }
791
+ /**
792
+ * Return a cached exec lease, minting a fresh one when the cache is empty
793
+ * or the JWT is within {@link LEASE_REFRESH_MARGIN_MS} of `expiresAt`.
794
+ *
795
+ * Callers are expected to be on the "sandbox is running" path; we don't
796
+ * re-check `_sandboxId` here because `executeCommand` already gated on it.
797
+ */
798
+ async _ensureLease() {
799
+ const now = Date.now();
800
+ if (this._lease && this._lease.expiresAtMs !== null && this._lease.expiresAtMs - LEASE_REFRESH_MARGIN_MS > now) return this._lease;
801
+ if (this._leaseInFlight) return this._leaseInFlight;
802
+ if (!this._sandboxId) throw new SandboxNotReadyError(this.id);
803
+ const sandboxId = this._sandboxId;
804
+ const inFlight = (async () => {
805
+ const json = await (await this._client.request(`/sandbox/${encodeURIComponent(sandboxId)}/exec-lease`, { method: "POST" })).json();
806
+ const expiresAtMs = json.expiresAt ? Date.parse(json.expiresAt) : null;
807
+ const lease = {
808
+ jwt: json.jwt,
809
+ wsEndpoint: json.wsEndpoint,
810
+ subprotocol: json.subprotocol,
811
+ expiresAt: json.expiresAt,
812
+ expiresAtMs: expiresAtMs !== null && !Number.isNaN(expiresAtMs) ? expiresAtMs : null
813
+ };
814
+ this._lease = lease;
815
+ return lease;
816
+ })();
817
+ this._leaseInFlight = inFlight;
818
+ try {
819
+ return await inFlight;
820
+ } finally {
821
+ if (this._leaseInFlight === inFlight) this._leaseInFlight = null;
822
+ }
823
+ }
824
+ async getInfo() {
825
+ if (!this._sandboxId) return {
826
+ id: this.id,
827
+ name: this.name,
828
+ provider: this.provider,
829
+ status: this.status,
830
+ createdAt: this._createdAt ?? /* @__PURE__ */ new Date()
831
+ };
832
+ const json = await (await this._client.request(`/sandbox/${encodeURIComponent(this._sandboxId)}`)).json();
833
+ return {
834
+ id: json.id,
835
+ name: this.name,
836
+ provider: this.provider,
837
+ status: this.status,
838
+ createdAt: json.createdAt ? new Date(json.createdAt) : this._createdAt ?? /* @__PURE__ */ new Date(),
839
+ metadata: {
840
+ sandboxId: json.id,
841
+ providerResourceId: json.providerResourceId ?? void 0,
842
+ platformStatus: json.status
843
+ }
844
+ };
845
+ }
846
+ getInstructions(opts) {
847
+ const defaultInstructions = `Platform sandbox${this._sandboxId ? ` ${this._sandboxId}` : ""}. Execute commands with the sandbox command APIs.`;
848
+ if (typeof this._instructionsOverride === "function") return this._instructionsOverride({
849
+ defaultInstructions,
850
+ requestContext: opts?.requestContext
851
+ });
852
+ if (typeof this._instructionsOverride === "string") return this._instructionsOverride;
853
+ return defaultInstructions;
854
+ }
578
855
  };
579
-
580
- // src/provider.ts
581
- var platformSandboxProvider = {
582
- id: "platform",
583
- name: "Mastra Platform Sandbox",
584
- description: "Environment-scoped sandbox execution through Mastra Platform workspace proxy",
585
- configSchema: {
586
- type: "object",
587
- properties: {
588
- accessToken: {
589
- type: "string",
590
- description: "Mastra Platform secret key (falls back to MASTRA_PLATFORM_SECRET_KEY)"
591
- },
592
- projectId: { type: "string", description: "Platform project ID (falls back to MASTRA_PROJECT_ID)" },
593
- environmentId: { type: "string", description: "Platform environment ID (falls back to MASTRA_ENVIRONMENT_ID)" },
594
- sandboxId: { type: "string", description: "Reattach to an existing Platform sandbox by ID" },
595
- idleTimeoutMinutes: { type: "number", description: "Minutes before the sandbox can be destroyed while idle" },
596
- networkIsolation: {
597
- type: "string",
598
- description: "Network isolation mode",
599
- enum: ["ISOLATED", "PRIVATE"],
600
- default: "ISOLATED"
601
- },
602
- env: { type: "object", description: "Environment variables", additionalProperties: { type: "string" } },
603
- timeout: { type: "number", description: "Default command timeout in ms" }
604
- }
605
- },
606
- createSandbox: (config) => new PlatformSandbox(config)
856
+ //#endregion
857
+ //#region src/provider.ts
858
+ const platformSandboxProvider = {
859
+ id: "platform",
860
+ name: "Mastra Platform Sandbox",
861
+ description: "Environment-scoped sandbox execution through Mastra Platform workspace proxy",
862
+ configSchema: {
863
+ type: "object",
864
+ properties: {
865
+ accessToken: {
866
+ type: "string",
867
+ description: "Mastra Platform secret key (falls back to MASTRA_PLATFORM_SECRET_KEY)"
868
+ },
869
+ projectId: {
870
+ type: "string",
871
+ description: "Platform project ID (falls back to MASTRA_PROJECT_ID)"
872
+ },
873
+ environmentId: {
874
+ type: "string",
875
+ description: "Platform environment ID (falls back to MASTRA_ENVIRONMENT_ID)"
876
+ },
877
+ sandboxId: {
878
+ type: "string",
879
+ description: "Reattach to an existing Platform sandbox by ID"
880
+ },
881
+ idleTimeoutMinutes: {
882
+ type: "number",
883
+ description: "Minutes before the sandbox can be destroyed while idle"
884
+ },
885
+ networkIsolation: {
886
+ type: "string",
887
+ description: "Network isolation mode",
888
+ enum: ["ISOLATED", "PRIVATE"],
889
+ default: "ISOLATED"
890
+ },
891
+ env: {
892
+ type: "object",
893
+ description: "Environment variables",
894
+ additionalProperties: { type: "string" }
895
+ },
896
+ timeout: {
897
+ type: "number",
898
+ description: "Default command timeout in ms"
899
+ }
900
+ }
901
+ },
902
+ createSandbox: (config) => new PlatformSandbox(config)
607
903
  };
608
- var platformFilesystemProvider = {
609
- id: "platform",
610
- name: "Mastra Platform Filesystem",
611
- description: "Bucket-backed filesystem access through Mastra Platform workspace proxy",
612
- configSchema: {
613
- type: "object",
614
- properties: {
615
- accessToken: {
616
- type: "string",
617
- description: "Mastra Platform secret key (falls back to MASTRA_PLATFORM_SECRET_KEY)"
618
- },
619
- projectId: { type: "string", description: "Platform project ID (falls back to MASTRA_PROJECT_ID)" },
620
- bucketName: {
621
- type: "string",
622
- description: "Platform workspace bucket name (falls back to MASTRA_PLATFORM_BUCKET_NAME)"
623
- },
624
- readOnly: { type: "boolean", description: "Mount as read-only", default: false }
625
- }
626
- },
627
- createFilesystem: (config) => new PlatformFilesystem(config)
904
+ const platformFilesystemProvider = {
905
+ id: "platform",
906
+ name: "Mastra Platform Filesystem",
907
+ description: "Bucket-backed filesystem access through Mastra Platform workspace proxy",
908
+ configSchema: {
909
+ type: "object",
910
+ properties: {
911
+ accessToken: {
912
+ type: "string",
913
+ description: "Mastra Platform secret key (falls back to MASTRA_PLATFORM_SECRET_KEY)"
914
+ },
915
+ projectId: {
916
+ type: "string",
917
+ description: "Platform project ID (falls back to MASTRA_PROJECT_ID)"
918
+ },
919
+ bucketName: {
920
+ type: "string",
921
+ description: "Platform workspace bucket name (falls back to MASTRA_PLATFORM_BUCKET_NAME)"
922
+ },
923
+ readOnly: {
924
+ type: "boolean",
925
+ description: "Mount as read-only",
926
+ default: false
927
+ }
928
+ }
929
+ },
930
+ createFilesystem: (config) => new PlatformFilesystem(config)
628
931
  };
629
-
932
+ //#endregion
630
933
  export { PlatformApiError, PlatformClient, PlatformFilesystem, PlatformSandbox, platformFilesystemProvider, platformSandboxProvider };
631
- //# sourceMappingURL=index.js.map
934
+
632
935
  //# sourceMappingURL=index.js.map