@mastra/platform-workspace 0.0.0 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +72 -0
- package/LICENSE.md +30 -0
- package/dist/client.d.ts +44 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/filesystem.d.ts +62 -0
- package/dist/filesystem.d.ts.map +1 -0
- package/dist/index.cjs +599 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +588 -0
- package/dist/index.js.map +1 -0
- package/dist/provider.d.ts +6 -0
- package/dist/provider.d.ts.map +1 -0
- package/dist/sandbox.d.ts +72 -0
- package/dist/sandbox.d.ts.map +1 -0
- package/package.json +20 -20
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,599 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var buffer = require('buffer');
|
|
4
|
+
var nodePath = require('path');
|
|
5
|
+
var workspace = require('@mastra/core/workspace');
|
|
6
|
+
|
|
7
|
+
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
8
|
+
|
|
9
|
+
var nodePath__default = /*#__PURE__*/_interopDefault(nodePath);
|
|
10
|
+
|
|
11
|
+
// src/client.ts
|
|
12
|
+
var DEFAULT_PROXY_URL = "https://workspaces.mastra.ai";
|
|
13
|
+
var DEFAULT_REQUEST_TIMEOUT_MS = 6e4;
|
|
14
|
+
function requireOption(value, name) {
|
|
15
|
+
if (!value) throw new Error(`${name} is required`);
|
|
16
|
+
return value;
|
|
17
|
+
}
|
|
18
|
+
function resolvePlatformOptions(options) {
|
|
19
|
+
return {
|
|
20
|
+
accessToken: requireOption(options.accessToken ?? process.env.MASTRA_PLATFORM_ACCESS_TOKEN, "accessToken"),
|
|
21
|
+
projectId: requireOption(options.projectId ?? process.env.MASTRA_PROJECT_ID, "projectId"),
|
|
22
|
+
proxyUrl: (process.env.MASTRA_WORKSPACE_PROXY_URL ?? DEFAULT_PROXY_URL).replace(/\/$/, ""),
|
|
23
|
+
fetch: options.fetch ?? fetch
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
function parseProxyError(body) {
|
|
27
|
+
if (!body) return void 0;
|
|
28
|
+
let parsed;
|
|
29
|
+
try {
|
|
30
|
+
parsed = JSON.parse(body);
|
|
31
|
+
} catch {
|
|
32
|
+
return void 0;
|
|
33
|
+
}
|
|
34
|
+
if (typeof parsed !== "object" || parsed === null) return void 0;
|
|
35
|
+
const err = parsed.error;
|
|
36
|
+
if (typeof err !== "object" || err === null) return void 0;
|
|
37
|
+
const { message, type } = err;
|
|
38
|
+
if (typeof message !== "string" || typeof type !== "string") return void 0;
|
|
39
|
+
return { message, type };
|
|
40
|
+
}
|
|
41
|
+
var PlatformApiError = class extends Error {
|
|
42
|
+
status;
|
|
43
|
+
body;
|
|
44
|
+
/** Machine-readable proxy error kind (e.g. `not_found`), when the response body matches `{ error: { message, type } }`. */
|
|
45
|
+
code;
|
|
46
|
+
/** Human-readable proxy error message, when the response body matches `{ error: { message, type } }`. */
|
|
47
|
+
proxyMessage;
|
|
48
|
+
constructor(status, body) {
|
|
49
|
+
const parsed = parseProxyError(body);
|
|
50
|
+
const summary = parsed ? `${parsed.type}: ${parsed.message}` : body;
|
|
51
|
+
super(`Platform proxy request failed with ${status}${summary ? `: ${summary}` : ""}`);
|
|
52
|
+
this.name = "PlatformApiError";
|
|
53
|
+
this.status = status;
|
|
54
|
+
this.body = body;
|
|
55
|
+
this.code = parsed?.type;
|
|
56
|
+
this.proxyMessage = parsed?.message;
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
var PlatformClient = class {
|
|
60
|
+
accessToken;
|
|
61
|
+
projectId;
|
|
62
|
+
proxyUrl;
|
|
63
|
+
fetch;
|
|
64
|
+
constructor(options) {
|
|
65
|
+
const resolved = resolvePlatformOptions(options);
|
|
66
|
+
this.accessToken = resolved.accessToken;
|
|
67
|
+
this.projectId = resolved.projectId;
|
|
68
|
+
this.proxyUrl = resolved.proxyUrl;
|
|
69
|
+
this.fetch = resolved.fetch;
|
|
70
|
+
}
|
|
71
|
+
async request(path, options = {}) {
|
|
72
|
+
const url = new URL(`${this.proxyUrl}/v1/projects/${encodeURIComponent(this.projectId)}${path}`);
|
|
73
|
+
for (const [key, value] of Object.entries(options.query ?? {})) {
|
|
74
|
+
if (value !== void 0) url.searchParams.set(key, String(value));
|
|
75
|
+
}
|
|
76
|
+
const headers = new Headers(options.headers);
|
|
77
|
+
headers.set("authorization", `Bearer ${this.accessToken}`);
|
|
78
|
+
const { query: _query, ...fetchOptions } = options;
|
|
79
|
+
const signal = fetchOptions.signal ?? AbortSignal.timeout(DEFAULT_REQUEST_TIMEOUT_MS);
|
|
80
|
+
const response = await this.fetch(url, { ...fetchOptions, headers, signal });
|
|
81
|
+
if (!response.ok) {
|
|
82
|
+
throw new PlatformApiError(response.status, await response.text());
|
|
83
|
+
}
|
|
84
|
+
return response;
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
function normalizePath(input) {
|
|
88
|
+
if (!input || input === ".") return "/";
|
|
89
|
+
let normalized = input.startsWith("/") ? input : `/${input}`;
|
|
90
|
+
normalized = nodePath__default.default.posix.normalize(normalized);
|
|
91
|
+
return normalized === "." ? "/" : normalized;
|
|
92
|
+
}
|
|
93
|
+
function keyFromPath(path) {
|
|
94
|
+
const normalized = normalizePath(path);
|
|
95
|
+
return normalized === "/" ? "" : normalized.slice(1);
|
|
96
|
+
}
|
|
97
|
+
function encodeKeyPath(key) {
|
|
98
|
+
return key.split("/").map(encodeURIComponent).join("/");
|
|
99
|
+
}
|
|
100
|
+
function nameFromPath(path) {
|
|
101
|
+
const normalized = normalizePath(path);
|
|
102
|
+
if (normalized === "/") return "";
|
|
103
|
+
return normalized.slice(normalized.lastIndexOf("/") + 1);
|
|
104
|
+
}
|
|
105
|
+
function contentToBody(content) {
|
|
106
|
+
if (typeof content === "string") return content;
|
|
107
|
+
return buffer.Buffer.from(content);
|
|
108
|
+
}
|
|
109
|
+
function headerDate(headers, name) {
|
|
110
|
+
const value = headers.get(name);
|
|
111
|
+
return value ? new Date(value) : /* @__PURE__ */ new Date(0);
|
|
112
|
+
}
|
|
113
|
+
function headerSize(headers) {
|
|
114
|
+
const value = headers.get("content-length");
|
|
115
|
+
return value ? Number(value) : 0;
|
|
116
|
+
}
|
|
117
|
+
function isNotFound(error) {
|
|
118
|
+
return typeof error === "object" && error !== null && "status" in error && error.status === 404;
|
|
119
|
+
}
|
|
120
|
+
var PlatformFilesystem = class extends workspace.MastraFilesystem {
|
|
121
|
+
id;
|
|
122
|
+
name = "PlatformFilesystem";
|
|
123
|
+
provider = "platform";
|
|
124
|
+
readOnly;
|
|
125
|
+
displayName;
|
|
126
|
+
icon;
|
|
127
|
+
description;
|
|
128
|
+
status = "pending";
|
|
129
|
+
_client;
|
|
130
|
+
_bucketName;
|
|
131
|
+
_instructionsOverride;
|
|
132
|
+
constructor(options = {}) {
|
|
133
|
+
super({ ...options, name: "PlatformFilesystem" });
|
|
134
|
+
this.id = options.id ?? this.generateId();
|
|
135
|
+
this._bucketName = options.bucketName ?? process.env.MASTRA_PLATFORM_BUCKET_NAME ?? "";
|
|
136
|
+
if (!this._bucketName) throw new Error("bucketName is required");
|
|
137
|
+
this.readOnly = options.readOnly;
|
|
138
|
+
this.displayName = options.displayName;
|
|
139
|
+
this.icon = options.icon ?? "cloud";
|
|
140
|
+
this.description = options.description;
|
|
141
|
+
this._instructionsOverride = options.instructions;
|
|
142
|
+
this._client = new PlatformClient(options);
|
|
143
|
+
}
|
|
144
|
+
generateId() {
|
|
145
|
+
return `platform-fs-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
|
146
|
+
}
|
|
147
|
+
async readFile(path, options) {
|
|
148
|
+
await this.ensureReady();
|
|
149
|
+
let response;
|
|
150
|
+
try {
|
|
151
|
+
response = await this._client.request(
|
|
152
|
+
`/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(keyFromPath(path))}`
|
|
153
|
+
);
|
|
154
|
+
} catch (error) {
|
|
155
|
+
if (isNotFound(error)) throw new workspace.FileNotFoundError(path);
|
|
156
|
+
throw error;
|
|
157
|
+
}
|
|
158
|
+
const buffer$1 = buffer.Buffer.from(await response.arrayBuffer());
|
|
159
|
+
return options?.encoding ? buffer$1.toString(options.encoding) : buffer$1;
|
|
160
|
+
}
|
|
161
|
+
async writeFile(path, content, options) {
|
|
162
|
+
await this.ensureReady();
|
|
163
|
+
if (this.readOnly) throw new workspace.WorkspaceReadOnlyError("writeFile");
|
|
164
|
+
const headers = {};
|
|
165
|
+
if (options?.mimeType) headers["content-type"] = options.mimeType;
|
|
166
|
+
if (options?.overwrite === false) headers["if-none-match"] = "*";
|
|
167
|
+
try {
|
|
168
|
+
await this._client.request(`/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(keyFromPath(path))}`, {
|
|
169
|
+
method: "PUT",
|
|
170
|
+
headers,
|
|
171
|
+
body: contentToBody(content)
|
|
172
|
+
});
|
|
173
|
+
} catch (error) {
|
|
174
|
+
if (typeof error === "object" && error !== null && "status" in error && error.status === 412) {
|
|
175
|
+
throw new workspace.FileExistsError(path);
|
|
176
|
+
}
|
|
177
|
+
throw error;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Append bytes to a file.
|
|
182
|
+
*
|
|
183
|
+
* **Not atomic.** Object storage behind the workspace proxy has no native
|
|
184
|
+
* append or compare-and-swap primitive, so this implementation is a
|
|
185
|
+
* read-modify-write: it reads the current contents, concatenates the new
|
|
186
|
+
* bytes, and PUTs the whole object back. Concurrent `appendFile` calls to
|
|
187
|
+
* the same path can overwrite each other's writes ("last write wins").
|
|
188
|
+
* Use `writeFile` with distinct keys for concurrent writers.
|
|
189
|
+
*/
|
|
190
|
+
async appendFile(path, content) {
|
|
191
|
+
const existing = await this.exists(path) ? await this.readFile(path) : buffer.Buffer.alloc(0);
|
|
192
|
+
await this.writeFile(
|
|
193
|
+
path,
|
|
194
|
+
buffer.Buffer.concat([buffer.Buffer.isBuffer(existing) ? existing : buffer.Buffer.from(existing), buffer.Buffer.from(content)])
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
async deleteFile(path, options) {
|
|
198
|
+
await this.ensureReady();
|
|
199
|
+
if (this.readOnly) throw new workspace.WorkspaceReadOnlyError("deleteFile");
|
|
200
|
+
try {
|
|
201
|
+
await this._client.request(`/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(keyFromPath(path))}`, {
|
|
202
|
+
method: "DELETE",
|
|
203
|
+
query: { recursive: options?.recursive }
|
|
204
|
+
});
|
|
205
|
+
} catch (error) {
|
|
206
|
+
if (isNotFound(error) && options?.force) return;
|
|
207
|
+
if (isNotFound(error)) throw new workspace.FileNotFoundError(path);
|
|
208
|
+
throw error;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
async copyFile(src, dest, options) {
|
|
212
|
+
await this.ensureReady();
|
|
213
|
+
if (this.readOnly) throw new workspace.WorkspaceReadOnlyError("copyFile");
|
|
214
|
+
if (options?.overwrite === false) {
|
|
215
|
+
throw new Error("PlatformFilesystem.copyFile does not support overwrite: false \u2014 the proxy always overwrites.");
|
|
216
|
+
}
|
|
217
|
+
await this._client.request(`/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(keyFromPath(src))}`, {
|
|
218
|
+
method: "POST",
|
|
219
|
+
query: { op: "copy" },
|
|
220
|
+
headers: { "content-type": "application/json" },
|
|
221
|
+
body: JSON.stringify({ destination: keyFromPath(dest) })
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
async moveFile(src, dest, options) {
|
|
225
|
+
await this.ensureReady();
|
|
226
|
+
if (this.readOnly) throw new workspace.WorkspaceReadOnlyError("moveFile");
|
|
227
|
+
if (options?.overwrite === false) {
|
|
228
|
+
throw new Error("PlatformFilesystem.moveFile does not support overwrite: false \u2014 the proxy always overwrites.");
|
|
229
|
+
}
|
|
230
|
+
await this._client.request(`/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(keyFromPath(src))}`, {
|
|
231
|
+
method: "POST",
|
|
232
|
+
query: { op: "rename" },
|
|
233
|
+
headers: { "content-type": "application/json" },
|
|
234
|
+
body: JSON.stringify({ destination: keyFromPath(dest) })
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
async mkdir(path, _options) {
|
|
238
|
+
await this.ensureReady();
|
|
239
|
+
if (this.readOnly) throw new workspace.WorkspaceReadOnlyError("mkdir");
|
|
240
|
+
await this._client.request(`/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(keyFromPath(path))}`, {
|
|
241
|
+
method: "POST",
|
|
242
|
+
query: { op: "mkdir" }
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
async rmdir(path, options) {
|
|
246
|
+
await this.deleteFile(path.endsWith("/") ? path : `${path}/`, { recursive: true, force: options?.force });
|
|
247
|
+
}
|
|
248
|
+
async readdir(path, options) {
|
|
249
|
+
await this.ensureReady();
|
|
250
|
+
const prefix = keyFromPath(path);
|
|
251
|
+
const response = await this._client.request(
|
|
252
|
+
`/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(prefix)}`,
|
|
253
|
+
{
|
|
254
|
+
query: {
|
|
255
|
+
delimiter: options?.recursive ? void 0 : "/",
|
|
256
|
+
prefix: prefix ? `${prefix.replace(/\/$/, "")}/` : void 0
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
);
|
|
260
|
+
const json = await response.json();
|
|
261
|
+
return [
|
|
262
|
+
...(json.commonPrefixes ?? []).map((prefix2) => ({
|
|
263
|
+
name: nameFromPath(prefix2.replace(/\/$/, "")),
|
|
264
|
+
type: "directory"
|
|
265
|
+
})),
|
|
266
|
+
...(json.contents ?? []).filter((object) => object.key && !object.key.endsWith("/")).map((object) => ({
|
|
267
|
+
name: nameFromPath(object.key),
|
|
268
|
+
type: "file",
|
|
269
|
+
size: object.size
|
|
270
|
+
}))
|
|
271
|
+
].filter(
|
|
272
|
+
(entry) => !options?.extension || entry.type === "directory" || matchesExtension(entry.name, options.extension)
|
|
273
|
+
);
|
|
274
|
+
}
|
|
275
|
+
async exists(path) {
|
|
276
|
+
try {
|
|
277
|
+
await this.stat(path);
|
|
278
|
+
return true;
|
|
279
|
+
} catch (error) {
|
|
280
|
+
if (isNotFound(error) || error instanceof workspace.FileNotFoundError) return false;
|
|
281
|
+
throw error;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
async stat(path) {
|
|
285
|
+
await this.ensureReady();
|
|
286
|
+
const normalized = normalizePath(path);
|
|
287
|
+
if (normalized === "/") {
|
|
288
|
+
return { name: "", path: "/", type: "directory", size: 0, createdAt: /* @__PURE__ */ new Date(0), modifiedAt: /* @__PURE__ */ new Date(0) };
|
|
289
|
+
}
|
|
290
|
+
let response;
|
|
291
|
+
try {
|
|
292
|
+
response = await this._client.request(
|
|
293
|
+
`/fs/${encodeURIComponent(this._bucketName)}/${encodeKeyPath(keyFromPath(path))}`,
|
|
294
|
+
{
|
|
295
|
+
method: "HEAD"
|
|
296
|
+
}
|
|
297
|
+
);
|
|
298
|
+
} catch (error) {
|
|
299
|
+
if (isNotFound(error)) throw new workspace.FileNotFoundError(path);
|
|
300
|
+
throw error;
|
|
301
|
+
}
|
|
302
|
+
return {
|
|
303
|
+
name: nameFromPath(path),
|
|
304
|
+
path: normalized,
|
|
305
|
+
type: normalized.endsWith("/") ? "directory" : "file",
|
|
306
|
+
size: headerSize(response.headers),
|
|
307
|
+
createdAt: headerDate(response.headers, "last-modified"),
|
|
308
|
+
modifiedAt: headerDate(response.headers, "last-modified"),
|
|
309
|
+
mimeType: response.headers.get("content-type") ?? void 0
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
realpath(path) {
|
|
313
|
+
return Promise.resolve(normalizePath(path));
|
|
314
|
+
}
|
|
315
|
+
getInstructions(opts) {
|
|
316
|
+
const defaultInstructions = `Platform filesystem backed by Mastra Platform bucket ${this._bucketName}. Use absolute workspace paths.`;
|
|
317
|
+
if (typeof this._instructionsOverride === "function") {
|
|
318
|
+
return this._instructionsOverride({ defaultInstructions, requestContext: opts?.requestContext });
|
|
319
|
+
}
|
|
320
|
+
if (typeof this._instructionsOverride === "string") return this._instructionsOverride;
|
|
321
|
+
return defaultInstructions;
|
|
322
|
+
}
|
|
323
|
+
getInfo() {
|
|
324
|
+
return {
|
|
325
|
+
id: this.id,
|
|
326
|
+
name: this.name,
|
|
327
|
+
provider: this.provider,
|
|
328
|
+
status: this.status,
|
|
329
|
+
readOnly: this.readOnly,
|
|
330
|
+
icon: this.icon,
|
|
331
|
+
metadata: {
|
|
332
|
+
bucketName: this._bucketName,
|
|
333
|
+
...this.displayName && { displayName: this.displayName },
|
|
334
|
+
...this.description && { description: this.description }
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
};
|
|
339
|
+
function matchesExtension(name, extension) {
|
|
340
|
+
const extensions = Array.isArray(extension) ? extension : [extension];
|
|
341
|
+
return extensions.some((ext) => name.endsWith(ext));
|
|
342
|
+
}
|
|
343
|
+
function buildCommand(command, args) {
|
|
344
|
+
return args?.length ? `${command} ${args.map(shellQuote).join(" ")}` : command;
|
|
345
|
+
}
|
|
346
|
+
function shellQuote(arg) {
|
|
347
|
+
if (/^[a-zA-Z0-9._\-/=:@]+$/.test(arg)) return arg;
|
|
348
|
+
return `'${arg.replace(/'/g, `'\\''`)}'`;
|
|
349
|
+
}
|
|
350
|
+
var PlatformProcessHandle = class extends workspace.ProcessHandle {
|
|
351
|
+
pid;
|
|
352
|
+
resultPromise;
|
|
353
|
+
exitCodeValue;
|
|
354
|
+
constructor(pid, resultPromise, options) {
|
|
355
|
+
super(options);
|
|
356
|
+
this.pid = pid;
|
|
357
|
+
this.resultPromise = resultPromise.then((result) => {
|
|
358
|
+
this.exitCodeValue = result.exitCode;
|
|
359
|
+
if (result.stdout) this.emitStdout(result.stdout);
|
|
360
|
+
if (result.stderr) this.emitStderr(result.stderr);
|
|
361
|
+
return result;
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
get exitCode() {
|
|
365
|
+
return this.exitCodeValue;
|
|
366
|
+
}
|
|
367
|
+
async wait() {
|
|
368
|
+
return this.resultPromise;
|
|
369
|
+
}
|
|
370
|
+
async kill() {
|
|
371
|
+
throw new Error("Platform sandbox command execution does not support killing individual processes");
|
|
372
|
+
}
|
|
373
|
+
async sendStdin() {
|
|
374
|
+
throw new Error("Platform sandbox command execution does not support stdin");
|
|
375
|
+
}
|
|
376
|
+
};
|
|
377
|
+
var PlatformProcessManager = class extends workspace.SandboxProcessManager {
|
|
378
|
+
spawnCounter = 0;
|
|
379
|
+
/**
|
|
380
|
+
* Spawn a process on the remote sandbox.
|
|
381
|
+
*
|
|
382
|
+
* `command` is interpreted as a shell string by the remote shell, matching
|
|
383
|
+
* the {@link MastraSandbox} contract. See {@link PlatformSandbox.executeCommand}
|
|
384
|
+
* for the untrusted-input caveat: never pass untrusted values as `command`.
|
|
385
|
+
*/
|
|
386
|
+
async spawn(command, options = {}) {
|
|
387
|
+
const pid = `platform-proc-${Date.now().toString(36)}-${(this.spawnCounter++).toString(36)}`;
|
|
388
|
+
const resultPromise = this.sandbox.executeCommand(command, void 0, options);
|
|
389
|
+
const handle = new PlatformProcessHandle(pid, resultPromise, options);
|
|
390
|
+
this._tracked.set(handle.pid, handle);
|
|
391
|
+
return handle;
|
|
392
|
+
}
|
|
393
|
+
async list() {
|
|
394
|
+
return Array.from(this._tracked.values()).map((handle) => ({
|
|
395
|
+
pid: handle.pid,
|
|
396
|
+
command: handle.command,
|
|
397
|
+
running: handle.exitCode === void 0,
|
|
398
|
+
...handle.exitCode !== void 0 && { exitCode: handle.exitCode }
|
|
399
|
+
}));
|
|
400
|
+
}
|
|
401
|
+
};
|
|
402
|
+
var PlatformSandbox = class extends workspace.MastraSandbox {
|
|
403
|
+
id;
|
|
404
|
+
name = "PlatformSandbox";
|
|
405
|
+
provider = "platform";
|
|
406
|
+
status = "pending";
|
|
407
|
+
_client;
|
|
408
|
+
_environmentId;
|
|
409
|
+
_sandboxId;
|
|
410
|
+
_idleTimeoutMinutes;
|
|
411
|
+
_networkIsolation;
|
|
412
|
+
_env;
|
|
413
|
+
_timeout;
|
|
414
|
+
_instructionsOverride;
|
|
415
|
+
_createdAt = null;
|
|
416
|
+
constructor(options = {}) {
|
|
417
|
+
super({ ...options, name: "PlatformSandbox", processes: new PlatformProcessManager() });
|
|
418
|
+
this.id = options.id ?? this.generateId();
|
|
419
|
+
this._client = new PlatformClient(options);
|
|
420
|
+
this._environmentId = options.environmentId ?? process.env.MASTRA_ENVIRONMENT_ID ?? "";
|
|
421
|
+
if (!this._environmentId && !options.sandboxId) throw new Error("environmentId is required");
|
|
422
|
+
this._sandboxId = options.sandboxId;
|
|
423
|
+
this._idleTimeoutMinutes = options.idleTimeoutMinutes;
|
|
424
|
+
this._networkIsolation = options.networkIsolation;
|
|
425
|
+
this._env = options.env ?? {};
|
|
426
|
+
this._timeout = options.timeout;
|
|
427
|
+
this._instructionsOverride = options.instructions;
|
|
428
|
+
}
|
|
429
|
+
generateId() {
|
|
430
|
+
return `platform-sandbox-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
|
431
|
+
}
|
|
432
|
+
async start() {
|
|
433
|
+
if (this._sandboxId) {
|
|
434
|
+
this._createdAt = /* @__PURE__ */ new Date();
|
|
435
|
+
return;
|
|
436
|
+
}
|
|
437
|
+
const response = await this._client.request("/sandbox", {
|
|
438
|
+
method: "POST",
|
|
439
|
+
headers: { "content-type": "application/json" },
|
|
440
|
+
body: JSON.stringify({
|
|
441
|
+
environmentId: this._environmentId,
|
|
442
|
+
idleTimeoutMinutes: this._idleTimeoutMinutes,
|
|
443
|
+
networkIsolation: this._networkIsolation,
|
|
444
|
+
env: this._env
|
|
445
|
+
})
|
|
446
|
+
});
|
|
447
|
+
const json = await response.json();
|
|
448
|
+
this._sandboxId = json.id;
|
|
449
|
+
this._createdAt = json.createdAt ? new Date(json.createdAt) : /* @__PURE__ */ new Date();
|
|
450
|
+
}
|
|
451
|
+
async stop() {
|
|
452
|
+
await this.destroy();
|
|
453
|
+
}
|
|
454
|
+
async destroy() {
|
|
455
|
+
if (!this._sandboxId) return;
|
|
456
|
+
await this._client.request(`/sandbox/${encodeURIComponent(this._sandboxId)}`, { method: "DELETE" });
|
|
457
|
+
this._sandboxId = void 0;
|
|
458
|
+
this._createdAt = null;
|
|
459
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* Execute a command on the remote sandbox.
|
|
462
|
+
*
|
|
463
|
+
* `command` is a **shell string**: it is concatenated verbatim into the
|
|
464
|
+
* command line sent to the remote shell, which lets callers use pipes,
|
|
465
|
+
* redirects, and chaining (`ls -la | grep foo`). This matches the contract
|
|
466
|
+
* of {@link MastraSandbox} and the local sandbox implementation.
|
|
467
|
+
*
|
|
468
|
+
* `args`, when provided, are always shell-quoted so they cannot inject
|
|
469
|
+
* additional shell syntax.
|
|
470
|
+
*
|
|
471
|
+
* Security: callers MUST NOT pass untrusted input as `command`. If any part
|
|
472
|
+
* of the invocation is derived from an untrusted source, pass it through
|
|
473
|
+
* `args` (which is safely quoted) or shell-quote it yourself before
|
|
474
|
+
* inclusion. Untrusted `command` values allow arbitrary shell syntax
|
|
475
|
+
* execution on the remote sandbox.
|
|
476
|
+
*/
|
|
477
|
+
async executeCommand(command, args, options) {
|
|
478
|
+
await this.ensureRunning();
|
|
479
|
+
if (!this._sandboxId) throw new workspace.SandboxNotReadyError(this.id);
|
|
480
|
+
const started = Date.now();
|
|
481
|
+
const fullCommand = buildCommand(command, args);
|
|
482
|
+
const effectiveTimeout = options?.timeout ?? this._timeout;
|
|
483
|
+
const timeoutSec = effectiveTimeout != null ? Math.ceil(effectiveTimeout / 1e3) : void 0;
|
|
484
|
+
const clientSignal = effectiveTimeout != null && effectiveTimeout > 0 ? AbortSignal.timeout(effectiveTimeout + 3e4) : void 0;
|
|
485
|
+
const response = await this._client.request(`/sandbox/${encodeURIComponent(this._sandboxId)}/exec`, {
|
|
486
|
+
method: "POST",
|
|
487
|
+
headers: { "content-type": "application/json" },
|
|
488
|
+
body: JSON.stringify({
|
|
489
|
+
command: fullCommand,
|
|
490
|
+
timeoutSec,
|
|
491
|
+
cwd: options?.cwd,
|
|
492
|
+
env: options?.env
|
|
493
|
+
}),
|
|
494
|
+
signal: clientSignal
|
|
495
|
+
});
|
|
496
|
+
const json = await response.json();
|
|
497
|
+
const exitCode = json.exitCode ?? (json.timedOut ? 124 : 1);
|
|
498
|
+
return {
|
|
499
|
+
success: exitCode === 0,
|
|
500
|
+
exitCode,
|
|
501
|
+
stdout: json.stdout,
|
|
502
|
+
stderr: json.stderr,
|
|
503
|
+
executionTimeMs: Date.now() - started,
|
|
504
|
+
timedOut: json.timedOut,
|
|
505
|
+
command: fullCommand
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
async getInfo() {
|
|
509
|
+
if (!this._sandboxId) {
|
|
510
|
+
return {
|
|
511
|
+
id: this.id,
|
|
512
|
+
name: this.name,
|
|
513
|
+
provider: this.provider,
|
|
514
|
+
status: this.status,
|
|
515
|
+
createdAt: this._createdAt ?? /* @__PURE__ */ new Date()
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
const response = await this._client.request(`/sandbox/${encodeURIComponent(this._sandboxId)}`);
|
|
519
|
+
const json = await response.json();
|
|
520
|
+
return {
|
|
521
|
+
id: json.id,
|
|
522
|
+
name: this.name,
|
|
523
|
+
provider: this.provider,
|
|
524
|
+
status: this.status,
|
|
525
|
+
createdAt: json.createdAt ? new Date(json.createdAt) : this._createdAt ?? /* @__PURE__ */ new Date(),
|
|
526
|
+
metadata: {
|
|
527
|
+
providerResourceId: json.providerResourceId ?? void 0,
|
|
528
|
+
platformStatus: json.status
|
|
529
|
+
}
|
|
530
|
+
};
|
|
531
|
+
}
|
|
532
|
+
getInstructions(opts) {
|
|
533
|
+
const defaultInstructions = `Platform sandbox${this._sandboxId ? ` ${this._sandboxId}` : ""}. Execute commands with the sandbox command APIs.`;
|
|
534
|
+
if (typeof this._instructionsOverride === "function") {
|
|
535
|
+
return this._instructionsOverride({ defaultInstructions, requestContext: opts?.requestContext });
|
|
536
|
+
}
|
|
537
|
+
if (typeof this._instructionsOverride === "string") return this._instructionsOverride;
|
|
538
|
+
return defaultInstructions;
|
|
539
|
+
}
|
|
540
|
+
};
|
|
541
|
+
|
|
542
|
+
// src/provider.ts
|
|
543
|
+
var platformSandboxProvider = {
|
|
544
|
+
id: "platform",
|
|
545
|
+
name: "Mastra Platform Sandbox",
|
|
546
|
+
description: "Environment-scoped sandbox execution through Mastra Platform workspace proxy",
|
|
547
|
+
configSchema: {
|
|
548
|
+
type: "object",
|
|
549
|
+
properties: {
|
|
550
|
+
accessToken: {
|
|
551
|
+
type: "string",
|
|
552
|
+
description: "Mastra Platform access token (falls back to MASTRA_PLATFORM_ACCESS_TOKEN)"
|
|
553
|
+
},
|
|
554
|
+
projectId: { type: "string", description: "Platform project ID (falls back to MASTRA_PROJECT_ID)" },
|
|
555
|
+
environmentId: { type: "string", description: "Platform environment ID (falls back to MASTRA_ENVIRONMENT_ID)" },
|
|
556
|
+
sandboxId: { type: "string", description: "Reattach to an existing Platform sandbox by ID" },
|
|
557
|
+
idleTimeoutMinutes: { type: "number", description: "Minutes before the sandbox can be destroyed while idle" },
|
|
558
|
+
networkIsolation: {
|
|
559
|
+
type: "string",
|
|
560
|
+
description: "Network isolation mode",
|
|
561
|
+
enum: ["ISOLATED", "PRIVATE"],
|
|
562
|
+
default: "ISOLATED"
|
|
563
|
+
},
|
|
564
|
+
env: { type: "object", description: "Environment variables", additionalProperties: { type: "string" } },
|
|
565
|
+
timeout: { type: "number", description: "Default command timeout in ms" }
|
|
566
|
+
}
|
|
567
|
+
},
|
|
568
|
+
createSandbox: (config) => new PlatformSandbox(config)
|
|
569
|
+
};
|
|
570
|
+
var platformFilesystemProvider = {
|
|
571
|
+
id: "platform",
|
|
572
|
+
name: "Mastra Platform Filesystem",
|
|
573
|
+
description: "Bucket-backed filesystem access through Mastra Platform workspace proxy",
|
|
574
|
+
configSchema: {
|
|
575
|
+
type: "object",
|
|
576
|
+
properties: {
|
|
577
|
+
accessToken: {
|
|
578
|
+
type: "string",
|
|
579
|
+
description: "Mastra Platform access token (falls back to MASTRA_PLATFORM_ACCESS_TOKEN)"
|
|
580
|
+
},
|
|
581
|
+
projectId: { type: "string", description: "Platform project ID (falls back to MASTRA_PROJECT_ID)" },
|
|
582
|
+
bucketName: {
|
|
583
|
+
type: "string",
|
|
584
|
+
description: "Platform workspace bucket name (falls back to MASTRA_PLATFORM_BUCKET_NAME)"
|
|
585
|
+
},
|
|
586
|
+
readOnly: { type: "boolean", description: "Mount as read-only", default: false }
|
|
587
|
+
}
|
|
588
|
+
},
|
|
589
|
+
createFilesystem: (config) => new PlatformFilesystem(config)
|
|
590
|
+
};
|
|
591
|
+
|
|
592
|
+
exports.PlatformApiError = PlatformApiError;
|
|
593
|
+
exports.PlatformClient = PlatformClient;
|
|
594
|
+
exports.PlatformFilesystem = PlatformFilesystem;
|
|
595
|
+
exports.PlatformSandbox = PlatformSandbox;
|
|
596
|
+
exports.platformFilesystemProvider = platformFilesystemProvider;
|
|
597
|
+
exports.platformSandboxProvider = platformSandboxProvider;
|
|
598
|
+
//# sourceMappingURL=index.cjs.map
|
|
599
|
+
//# sourceMappingURL=index.cjs.map
|