@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/CHANGELOG.md +30 -0
- package/dist/direct-exec.d.ts +89 -0
- package/dist/direct-exec.d.ts.map +1 -0
- package/dist/index.cjs +921 -600
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +892 -589
- package/dist/index.js.map +1 -1
- package/dist/sandbox.d.ts +42 -0
- package/dist/sandbox.d.ts.map +1 -1
- package/package.json +6 -6
package/dist/index.js
CHANGED
|
@@ -1,632 +1,935 @@
|
|
|
1
|
-
import { Buffer } from
|
|
2
|
-
import nodePath from
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
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
|
-
|
|
10
|
-
|
|
13
|
+
if (!value) throw new Error(`${name} is required`);
|
|
14
|
+
return value;
|
|
11
15
|
}
|
|
12
16
|
function resolvePlatformOptions(options) {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
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
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
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
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
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
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
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
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
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
|
-
|
|
93
|
-
|
|
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
|
-
|
|
107
|
+
return key.split("/").map(encodeURIComponent).join("/");
|
|
97
108
|
}
|
|
98
109
|
function nameFromPath(path) {
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
110
|
+
const normalized = normalizePath(path);
|
|
111
|
+
if (normalized === "/") return "";
|
|
112
|
+
return normalized.slice(normalized.lastIndexOf("/") + 1);
|
|
102
113
|
}
|
|
103
114
|
function contentToBody(content) {
|
|
104
|
-
|
|
105
|
-
|
|
115
|
+
if (typeof content === "string") return content;
|
|
116
|
+
return Buffer.from(content);
|
|
106
117
|
}
|
|
107
118
|
function headerDate(headers, name) {
|
|
108
|
-
|
|
109
|
-
|
|
119
|
+
const value = headers.get(name);
|
|
120
|
+
return value ? new Date(value) : /* @__PURE__ */ new Date(0);
|
|
110
121
|
}
|
|
111
122
|
function headerSize(headers) {
|
|
112
|
-
|
|
113
|
-
|
|
123
|
+
const value = headers.get("content-length");
|
|
124
|
+
return value ? Number(value) : 0;
|
|
114
125
|
}
|
|
115
126
|
function isNotFound(error) {
|
|
116
|
-
|
|
127
|
+
return typeof error === "object" && error !== null && "status" in error && error.status === 404;
|
|
117
128
|
}
|
|
118
129
|
var PlatformFilesystem = class extends MastraFilesystem {
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
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
|
-
|
|
339
|
-
|
|
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
|
-
|
|
510
|
+
return args?.length ? `${command} ${args.map(shellQuote).join(" ")}` : command;
|
|
343
511
|
}
|
|
344
512
|
function shellQuote(arg) {
|
|
345
|
-
|
|
346
|
-
|
|
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
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
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
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
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
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
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
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
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
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
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
|
-
|
|
934
|
+
|
|
632
935
|
//# sourceMappingURL=index.js.map
|