@groundbox/mastra 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1237 @@
1
+ // src/sandbox.ts
2
+ import { randomUUID } from "crypto";
3
+ import { Groundbox } from "@groundbox/sdk";
4
+ import {
5
+ MastraSandbox,
6
+ SandboxAbortError,
7
+ SandboxNotReadyError,
8
+ validateSandboxFileMode
9
+ } from "@mastra/core/workspace";
10
+
11
+ // src/computer.ts
12
+ var KEY_NAMES = {
13
+ enter: "Return",
14
+ return: "Return",
15
+ escape: "Escape",
16
+ esc: "Escape",
17
+ backspace: "BackSpace",
18
+ tab: "Tab",
19
+ space: "space",
20
+ " ": "space",
21
+ delete: "Delete",
22
+ del: "Delete",
23
+ insert: "Insert",
24
+ home: "Home",
25
+ end: "End",
26
+ pageup: "Page_Up",
27
+ pagedown: "Page_Down",
28
+ arrowup: "Up",
29
+ arrowdown: "Down",
30
+ arrowleft: "Left",
31
+ arrowright: "Right",
32
+ up: "Up",
33
+ down: "Down",
34
+ left: "Left",
35
+ right: "Right",
36
+ control: "ctrl",
37
+ ctrl: "ctrl",
38
+ shift: "shift",
39
+ alt: "alt",
40
+ option: "alt",
41
+ meta: "super",
42
+ cmd: "super",
43
+ command: "super",
44
+ super: "super",
45
+ win: "super",
46
+ capslock: "Caps_Lock"
47
+ };
48
+ function toKeysym(key) {
49
+ const mapped = KEY_NAMES[key.toLowerCase()];
50
+ if (mapped) return mapped;
51
+ if (/^f\d{1,2}$/i.test(key)) return key.toUpperCase();
52
+ return key;
53
+ }
54
+ function toKeyCombo(key) {
55
+ const keys = Array.isArray(key) ? key : [key];
56
+ return keys.map(toKeysym).join("+");
57
+ }
58
+ function createGroundboxComputer(sandbox) {
59
+ const act = async (action) => sandbox.retryOnDead(async () => {
60
+ await sandbox.ensureRunning();
61
+ return sandbox.groundbox.computer(sandbox.requireSandboxId(), action);
62
+ });
63
+ return {
64
+ async screenshot() {
65
+ const shot = await sandbox.retryOnDead(async () => {
66
+ await sandbox.ensureRunning();
67
+ return sandbox.groundbox.computer_screenshot(sandbox.requireSandboxId(), { format: "png" });
68
+ });
69
+ return { data: new Uint8Array(Buffer.from(shot.data, "base64")), mediaType: "image/png" };
70
+ },
71
+ async leftClick(x, y) {
72
+ await act({ action: "left_click", coordinate: [x, y] });
73
+ },
74
+ async rightClick(x, y) {
75
+ await act({ action: "right_click", coordinate: [x, y] });
76
+ },
77
+ async doubleClick(x, y) {
78
+ await act({ action: "double_click", coordinate: [x, y] });
79
+ },
80
+ async moveMouse(x, y) {
81
+ await act({ action: "mouse_move", coordinate: [x, y] });
82
+ },
83
+ async drag(from, to) {
84
+ await act({ action: "left_click_drag", start_coordinate: [from.x, from.y], coordinate: [to.x, to.y] });
85
+ },
86
+ async scroll(direction, amount) {
87
+ await act({ action: "scroll", scroll_direction: direction, scroll_amount: Math.max(1, Math.round(amount)) });
88
+ },
89
+ async type(text) {
90
+ await act({ action: "type", text });
91
+ },
92
+ async press(key) {
93
+ await act({ action: "key", text: toKeyCombo(key) });
94
+ },
95
+ async getScreenSize() {
96
+ const info = await sandbox.refresh();
97
+ if (info?.desktop) return { width: info.desktop.width, height: info.desktop.height };
98
+ const shot = await sandbox.groundbox.computer_screenshot(sandbox.requireSandboxId(), { format: "jpeg", max_width: 64 });
99
+ return { width: shot.screen.width, height: shot.screen.height };
100
+ },
101
+ async getCursorPosition() {
102
+ const response = await act({ action: "cursor_position" });
103
+ if (!response.cursor) throw new Error("Groundbox did not return a cursor position");
104
+ return { x: response.cursor.x, y: response.cursor.y };
105
+ },
106
+ async streamUrl() {
107
+ try {
108
+ const link = await sandbox.retryOnDead(async () => {
109
+ await sandbox.ensureRunning();
110
+ return sandbox.groundbox.create_desktop_link(sandbox.requireSandboxId(), { control: false });
111
+ });
112
+ return link.url;
113
+ } catch {
114
+ return null;
115
+ }
116
+ }
117
+ };
118
+ }
119
+
120
+ // src/filesystem.ts
121
+ import {
122
+ DirectoryNotEmptyError,
123
+ DirectoryNotFoundError,
124
+ FileExistsError,
125
+ FileNotFoundError,
126
+ IsDirectoryError,
127
+ MastraFilesystem,
128
+ NotDirectoryError,
129
+ StaleFileError
130
+ } from "@mastra/core/workspace";
131
+ import { posix as posix2 } from "path";
132
+
133
+ // src/utils.ts
134
+ import { posix } from "path";
135
+ import { GroundboxError } from "@groundbox/sdk";
136
+ function shellQuote(value) {
137
+ if (value !== "" && /^[A-Za-z0-9_\-./=:@%+,]+$/.test(value)) return value;
138
+ return `'${value.replace(/'/g, `'\\''`)}'`;
139
+ }
140
+ function definedEnv(env) {
141
+ const out = {};
142
+ if (!env) return out;
143
+ for (const [key, value] of Object.entries(env)) {
144
+ if (value !== void 0) out[key] = value;
145
+ }
146
+ return out;
147
+ }
148
+ function toSeconds(ms) {
149
+ return Math.max(1, Math.ceil(ms / 1e3));
150
+ }
151
+ function toAbsolute(path, base = "/") {
152
+ return posix.resolve(base, path);
153
+ }
154
+ function errorCode(error) {
155
+ if (error instanceof GroundboxError) return error.code;
156
+ if (error && typeof error === "object" && "code" in error && typeof error.code === "string") {
157
+ return error.code;
158
+ }
159
+ return void 0;
160
+ }
161
+ function errorMessage(error) {
162
+ if (error instanceof Error) return error.message;
163
+ return String(error);
164
+ }
165
+ function sleep(ms) {
166
+ return new Promise((resolve) => setTimeout(resolve, ms));
167
+ }
168
+ function retainNewest(text, maxBytes) {
169
+ if (!Number.isFinite(maxBytes)) return { text, dropped: 0 };
170
+ const bytes = Buffer.from(text, "utf8");
171
+ if (bytes.length <= maxBytes) return { text, dropped: 0 };
172
+ const dropped = bytes.length - maxBytes;
173
+ let start = dropped;
174
+ while (start < bytes.length && (bytes[start] & 192) === 128) start++;
175
+ return { text: bytes.subarray(start).toString("utf8"), dropped: start };
176
+ }
177
+ function toBytes(content) {
178
+ if (typeof content === "string") return Buffer.from(content, "utf8");
179
+ return content;
180
+ }
181
+
182
+ // src/filesystem.ts
183
+ var EXIT = { notFound: 20, isDirectory: 21, exists: 22, notDirectory: 23, destIsDirectory: 24 };
184
+ var DEFAULT_MAX_DEPTH = 100;
185
+ var LIST_CONCURRENCY = 8;
186
+ var COPY_SCRIPT = `src=$1 dest=$2 recursive=$3 overwrite=$4
187
+ [ -e "$src" ] || exit ${EXIT.notFound}
188
+ if [ -d "$src" ]; then
189
+ [ "$recursive" = 1 ] || exit ${EXIT.isDirectory}
190
+ if [ "$overwrite" = 0 ] && { [ -e "$dest" ] || [ -L "$dest" ]; }; then exit ${EXIT.exists}; fi
191
+ mkdir -p "$dest" && cp -R -P "$src"/. "$dest"/
192
+ exit $?
193
+ fi
194
+ if [ -e "$dest" ] || [ -L "$dest" ]; then
195
+ [ "$overwrite" = 0 ] && exit ${EXIT.exists}
196
+ [ -d "$dest" ] && exit ${EXIT.destIsDirectory}
197
+ fi
198
+ mkdir -p "$(dirname "$dest")" && cp "$src" "$dest"`;
199
+ var MOVE_SCRIPT = `src=$1 dest=$2 overwrite=$3
200
+ { [ -e "$src" ] || [ -L "$src" ]; } || exit ${EXIT.notFound}
201
+ if [ -e "$dest" ] || [ -L "$dest" ]; then
202
+ [ "$overwrite" = 0 ] && exit ${EXIT.exists}
203
+ if [ -d "$dest" ] && [ ! -L "$dest" ]; then exit ${EXIT.destIsDirectory}; fi
204
+ fi
205
+ mkdir -p "$(dirname "$dest")" && mv -f "$src" "$dest"`;
206
+ var APPEND_SCRIPT = `[ -d "$1" ] && exit ${EXIT.isDirectory}
207
+ mkdir -p "$(dirname "$1")" && cat >> "$1"`;
208
+ var RESOLVE_LINKS_SCRIPT = `for p do
209
+ if [ -d "$p" ]; then t=d; elif [ -e "$p" ]; then t=f; else t=x; fi
210
+ printf '%s\\t%s\\n' "$t" "$(readlink "$p")"
211
+ done`;
212
+ var REALPATH_SCRIPT = `readlink -f -- "$1"`;
213
+ var GroundboxSandboxFilesystem = class extends MastraFilesystem {
214
+ constructor(sandbox) {
215
+ super({ name: "GroundboxSandboxFilesystem" });
216
+ this.sandbox = sandbox;
217
+ this.id = `${sandbox.id}-fs`;
218
+ }
219
+ sandbox;
220
+ id;
221
+ name = "GroundboxSandboxFilesystem";
222
+ provider = "groundbox";
223
+ status = "pending";
224
+ get basePath() {
225
+ return this.sandbox.workingDirectory;
226
+ }
227
+ getInstructions() {
228
+ return `The disk of a Groundbox sandbox. Paths are absolute inside the sandbox; a relative path is resolved against ${this.sandbox.workingDirectory ?? "the home folder"}.`;
229
+ }
230
+ async getCommandCwd() {
231
+ return this.sandbox.workingDirectory;
232
+ }
233
+ resolveAbsolutePath(path) {
234
+ return this.abs(path);
235
+ }
236
+ abs(path) {
237
+ return toAbsolute(path, this.sandbox.workingDirectory ?? "/");
238
+ }
239
+ /** Run `fn` with the sandbox started, retrying once when it died under us. */
240
+ run(fn) {
241
+ return this.sandbox.retryOnDead(async () => {
242
+ await this.sandbox.ensureRunning();
243
+ return fn(this.sandbox.requireSandboxId());
244
+ });
245
+ }
246
+ async script(script, args, stdin) {
247
+ const result = await this.run(
248
+ (id) => this.sandbox.groundbox.run_command(id, ["sh", "-c", script, "sh", ...args], stdin ? { stdin } : {})
249
+ );
250
+ return { exitCode: result.exit_code, stdout: result.stdout, stderr: result.stderr };
251
+ }
252
+ /** The entry itself (a symlink is described, not followed), or undefined when nothing is there. */
253
+ async lstat(abs) {
254
+ try {
255
+ return await this.run((id) => this.sandbox.groundbox.stat_file(id, abs));
256
+ } catch (error) {
257
+ if (errorCode(error) === "not_found") return void 0;
258
+ throw error;
259
+ }
260
+ }
261
+ async readFile(path, options) {
262
+ const abs = this.abs(path);
263
+ let bytes;
264
+ try {
265
+ bytes = await this.run((id) => this.sandbox.groundbox.read_file(id, abs));
266
+ } catch (error) {
267
+ throw this.fileError(error, path);
268
+ }
269
+ const buffer = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
270
+ return options?.encoding ? buffer.toString(options.encoding) : buffer;
271
+ }
272
+ async writeFile(path, content, options) {
273
+ const abs = this.abs(path);
274
+ if (options?.overwrite === false || options?.expectedMtime) {
275
+ const current = await this.lstat(abs);
276
+ if (current && options?.overwrite === false) throw new FileExistsError(path);
277
+ if (options?.expectedMtime && current) {
278
+ const actual = new Date(current.modified_at);
279
+ if (actual.getTime() !== options.expectedMtime.getTime()) throw new StaleFileError(path, options.expectedMtime, actual);
280
+ }
281
+ }
282
+ if (options?.recursive === false) await this.assertParentDirectory(abs, path);
283
+ try {
284
+ await this.run((id) => this.sandbox.groundbox.write_file(id, abs, toBytes(content)));
285
+ } catch (error) {
286
+ throw this.fileError(error, path);
287
+ }
288
+ }
289
+ async appendFile(path, content) {
290
+ const abs = this.abs(path);
291
+ const result = await this.script(APPEND_SCRIPT, [abs], toBytes(content));
292
+ this.check(result, "appendFile", path, { isDirectory: () => new IsDirectoryError(path) });
293
+ }
294
+ async deleteFile(path, options) {
295
+ const abs = this.abs(path);
296
+ const entry = await this.lstat(abs);
297
+ if (!entry) {
298
+ if (options?.force) return;
299
+ throw new FileNotFoundError(path);
300
+ }
301
+ if (entry.type === "dir") throw new IsDirectoryError(path);
302
+ await this.run((id) => this.sandbox.groundbox.delete_file(id, abs));
303
+ }
304
+ async copyFile(src, dest, options) {
305
+ const result = await this.script(COPY_SCRIPT, [
306
+ this.abs(src),
307
+ this.abs(dest),
308
+ options?.recursive ? "1" : "0",
309
+ options?.overwrite === false ? "0" : "1"
310
+ ]);
311
+ this.check(result, "copyFile", `${src} -> ${dest}`, {
312
+ notFound: () => new FileNotFoundError(src),
313
+ isDirectory: () => new IsDirectoryError(src),
314
+ exists: () => new FileExistsError(dest),
315
+ destIsDirectory: () => new IsDirectoryError(dest)
316
+ });
317
+ }
318
+ async moveFile(src, dest, options) {
319
+ const result = await this.script(MOVE_SCRIPT, [this.abs(src), this.abs(dest), options?.overwrite === false ? "0" : "1"]);
320
+ this.check(result, "moveFile", `${src} -> ${dest}`, {
321
+ notFound: () => new FileNotFoundError(src),
322
+ exists: () => new FileExistsError(dest),
323
+ destIsDirectory: () => new IsDirectoryError(dest)
324
+ });
325
+ }
326
+ async mkdir(path, options) {
327
+ const abs = this.abs(path);
328
+ if (options?.recursive === false) {
329
+ await this.assertParentDirectory(abs, path);
330
+ if (await this.lstat(abs)) throw new FileExistsError(path);
331
+ }
332
+ try {
333
+ await this.run((id) => this.sandbox.groundbox.make_dir(id, abs));
334
+ } catch (error) {
335
+ if (errorCode(error) === "bad_request") {
336
+ const entry = await this.lstat(abs);
337
+ if (entry && entry.type !== "dir") throw new FileExistsError(path);
338
+ throw new NotDirectoryError(posix2.dirname(path));
339
+ }
340
+ throw error;
341
+ }
342
+ }
343
+ async rmdir(path, options) {
344
+ const abs = this.abs(path);
345
+ const entry = await this.lstat(abs);
346
+ if (!entry) {
347
+ if (options?.force) return;
348
+ throw new DirectoryNotFoundError(path);
349
+ }
350
+ if (entry.type !== "dir") throw new NotDirectoryError(path);
351
+ try {
352
+ await this.run((id) => this.sandbox.groundbox.delete_file(id, abs, { recursive: options?.recursive ?? false }));
353
+ } catch (error) {
354
+ if (errorCode(error) === "conflict") throw new DirectoryNotEmptyError(path);
355
+ throw error;
356
+ }
357
+ }
358
+ async readdir(path, options) {
359
+ const root = this.abs(path);
360
+ const maxDepth = options?.recursive ? options.maxDepth ?? DEFAULT_MAX_DEPTH : 1;
361
+ const result = [];
362
+ let level = [root];
363
+ for (let depth = 1; depth <= maxDepth && level.length > 0; depth++) {
364
+ const next = [];
365
+ for (let i = 0; i < level.length; i += LIST_CONCURRENCY) {
366
+ const batch = level.slice(i, i + LIST_CONCURRENCY);
367
+ const listed = await Promise.all(batch.map((dir) => this.listOne(dir, dir === root ? path : posix2.relative(root, dir))));
368
+ for (const entries of listed) {
369
+ const links = entries.filter((entry) => entry.type === "symlink");
370
+ const resolved = links.length > 0 ? await this.resolveLinks(links.map((entry) => entry.path)) : [];
371
+ const linkInfo = new Map(links.map((entry, index) => [entry.path, resolved[index]]));
372
+ for (const entry of entries) {
373
+ if (entry.type === "other") continue;
374
+ const name = posix2.relative(root, entry.path);
375
+ if (entry.type === "symlink") {
376
+ const info = linkInfo.get(entry.path);
377
+ if (!info || info.type === "x") continue;
378
+ const type = info.type === "d" ? "directory" : "file";
379
+ if (type === "file" && !matchesExtension(name, options?.extension)) continue;
380
+ result.push({ name, type, isSymlink: true, ...info.target && { symlinkTarget: info.target } });
381
+ continue;
382
+ }
383
+ if (entry.type === "dir") {
384
+ result.push({ name, type: "directory" });
385
+ next.push(entry.path);
386
+ continue;
387
+ }
388
+ if (!matchesExtension(name, options?.extension)) continue;
389
+ result.push({ name, type: "file", size: entry.size_bytes });
390
+ }
391
+ }
392
+ }
393
+ level = next;
394
+ }
395
+ return result;
396
+ }
397
+ async listOne(abs, shown) {
398
+ try {
399
+ const listing = await this.run((id) => this.sandbox.groundbox.list_files(id, abs));
400
+ return listing.entries;
401
+ } catch (error) {
402
+ const code = errorCode(error);
403
+ if (code === "not_found") throw new DirectoryNotFoundError(shown);
404
+ if (code === "bad_request") throw new NotDirectoryError(shown);
405
+ throw error;
406
+ }
407
+ }
408
+ async resolveLinks(paths) {
409
+ const result = await this.script(RESOLVE_LINKS_SCRIPT, paths);
410
+ const lines = result.stdout.split("\n");
411
+ return paths.map((_, index) => {
412
+ const [type, ...rest] = (lines[index] ?? "x ").split(" ");
413
+ return { type: type === "d" || type === "f" ? type : "x", target: rest.join(" ") };
414
+ });
415
+ }
416
+ async exists(path) {
417
+ const abs = this.abs(path);
418
+ return this.run((id) => this.sandbox.groundbox.file_exists(id, abs));
419
+ }
420
+ async stat(path) {
421
+ const abs = this.abs(path);
422
+ let entry = await this.lstat(abs);
423
+ if (entry?.type === "symlink") {
424
+ const target = (await this.script(REALPATH_SCRIPT, [abs])).stdout.trim();
425
+ entry = target ? await this.lstat(target) : void 0;
426
+ }
427
+ if (!entry || entry.type === "symlink") throw new FileNotFoundError(path);
428
+ const modifiedAt = new Date(entry.modified_at);
429
+ const isDir = entry.type === "dir";
430
+ return {
431
+ name: posix2.basename(abs),
432
+ path: abs,
433
+ type: isDir ? "directory" : "file",
434
+ size: isDir ? 0 : entry.size_bytes,
435
+ createdAt: modifiedAt,
436
+ modifiedAt
437
+ };
438
+ }
439
+ async assertParentDirectory(abs, path) {
440
+ const parent = await this.lstat(posix2.dirname(abs));
441
+ if (!parent) throw new DirectoryNotFoundError(posix2.dirname(path));
442
+ if (parent.type !== "dir") throw new NotDirectoryError(posix2.dirname(path));
443
+ }
444
+ /** A files API error about one path, as the Mastra error it means. */
445
+ fileError(error, path) {
446
+ const code = errorCode(error);
447
+ if (code === "not_found") return new FileNotFoundError(path);
448
+ if (code === "bad_request") {
449
+ const message = errorMessage(error);
450
+ if (/is a folder|is a directory/i.test(message)) return new IsDirectoryError(path);
451
+ if (/not a (folder|directory)/i.test(message)) return new NotDirectoryError(posix2.dirname(path));
452
+ }
453
+ return error;
454
+ }
455
+ check(result, operation, subject, errors) {
456
+ if (result.exitCode === 0) return;
457
+ for (const [outcome, code] of Object.entries(EXIT)) {
458
+ const make = errors[outcome];
459
+ if (code === result.exitCode && make) throw make();
460
+ }
461
+ throw new Error(`${operation} ${subject} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);
462
+ }
463
+ };
464
+ function matchesExtension(name, extension) {
465
+ if (!extension) return true;
466
+ const ext = posix2.extname(name);
467
+ return (Array.isArray(extension) ? extension : [extension]).some((e) => e === ext || e === ext.slice(1) || `.${e}` === ext);
468
+ }
469
+
470
+ // src/process-manager.ts
471
+ import { ProcessHandle, SandboxProcessManager } from "@mastra/core/workspace";
472
+ var KILLED_EXIT_CODE = 137;
473
+ var NO_TIMEOUT_S = 2592e3;
474
+ var POLL_MS = 1e3;
475
+ var GroundboxProcessHandle = class extends ProcessHandle {
476
+ constructor(pid, client, sandboxId, stream, startTime, stdinOpen, options, ended) {
477
+ super(options);
478
+ this.client = client;
479
+ this.sandboxId = sandboxId;
480
+ this.stream = stream;
481
+ this.startTime = startTime;
482
+ this.stdinOpen = stdinOpen;
483
+ this.pid = pid;
484
+ if (ended) {
485
+ this._ended = Promise.resolve(ended);
486
+ this.settle(ended);
487
+ } else if (stream) {
488
+ this._ended = stream.done.then(
489
+ (result) => {
490
+ this.settle(result);
491
+ return result;
492
+ },
493
+ (error) => {
494
+ if (this._detached) throw error;
495
+ return this.pollUntilEnded();
496
+ }
497
+ );
498
+ } else {
499
+ this._ended = this.pollUntilEnded();
500
+ }
501
+ this._ended.catch(() => void 0);
502
+ }
503
+ client;
504
+ sandboxId;
505
+ stream;
506
+ startTime;
507
+ stdinOpen;
508
+ pid;
509
+ _exitCode;
510
+ _timedOut = false;
511
+ _killed = false;
512
+ _detached = false;
513
+ _waitPromise;
514
+ _ended;
515
+ get exitCode() {
516
+ return this._exitCode;
517
+ }
518
+ settle(result) {
519
+ if (this._exitCode !== void 0) return;
520
+ this._exitCode = result.exit_code;
521
+ this._timedOut = result.timed_out;
522
+ }
523
+ /** The output stream failed for good: read the command's state until it ends. */
524
+ async pollUntilEnded() {
525
+ for (; ; ) {
526
+ let command;
527
+ try {
528
+ command = await this.client.get_command(this.sandboxId, this.pid);
529
+ } catch (error) {
530
+ const code = errorCode(error);
531
+ if (code === "not_found" || code === "conflict") {
532
+ const ended = { exit_code: this._killed ? KILLED_EXIT_CODE : 1, duration_ms: Date.now() - this.startTime, timed_out: false };
533
+ this.settle(ended);
534
+ return ended;
535
+ }
536
+ throw error;
537
+ }
538
+ if (command.state !== "running") {
539
+ const ended = {
540
+ exit_code: command.exit_code ?? (command.state === "lost" ? KILLED_EXIT_CODE : 1),
541
+ duration_ms: command.duration_ms ?? Date.now() - this.startTime,
542
+ timed_out: command.timed_out
543
+ };
544
+ this.settle(ended);
545
+ return ended;
546
+ }
547
+ await sleep(POLL_MS);
548
+ }
549
+ }
550
+ async wait() {
551
+ if (!this._waitPromise) this._waitPromise = this.doWait();
552
+ return this._waitPromise;
553
+ }
554
+ async doWait() {
555
+ const ended = await this._ended;
556
+ const exitCode = this._exitCode ?? ended.exit_code;
557
+ const timedOut = this._timedOut;
558
+ const result = {
559
+ success: exitCode === 0 && !timedOut,
560
+ exitCode,
561
+ stdout: this.stdout,
562
+ stderr: this.stderr,
563
+ executionTimeMs: Date.now() - this.startTime,
564
+ ...timedOut && { timedOut: true },
565
+ ...(this._killed || timedOut) && { killed: true },
566
+ ...this.stdoutTruncated && { stdoutTruncated: true, stdoutDroppedBytes: this.stdoutDroppedBytes },
567
+ ...this.stderrTruncated && { stderrTruncated: true, stderrDroppedBytes: this.stderrDroppedBytes }
568
+ };
569
+ return result;
570
+ }
571
+ async kill() {
572
+ if (this._exitCode !== void 0) return false;
573
+ this._killed = true;
574
+ try {
575
+ const command = await this.client.kill_command(this.sandboxId, this.pid);
576
+ if (command.state !== "running" && command.exit_code !== null) {
577
+ this.settle({ exit_code: command.exit_code, duration_ms: command.duration_ms ?? 0, timed_out: command.timed_out });
578
+ }
579
+ } catch (error) {
580
+ const code = errorCode(error);
581
+ if (code === "not_found" || code === "conflict") return false;
582
+ throw error;
583
+ }
584
+ return true;
585
+ }
586
+ async sendStdin(data) {
587
+ if (this._exitCode !== void 0) throw new Error(`Process ${this.pid} has already exited with code ${this._exitCode}`);
588
+ if (!this.stdinOpen || !this.stream) throw new Error(`Process ${this.pid} was started without stdin (stdinMode: 'ignore')`);
589
+ this.stream.write(data);
590
+ }
591
+ async closeStdin() {
592
+ if (this._exitCode !== void 0) return;
593
+ if (!this.stdinOpen || !this.stream) throw new Error(`Process ${this.pid} was started without stdin (stdinMode: 'ignore')`);
594
+ this.stream.end();
595
+ }
596
+ /** Stop following the output; the command runs on in the sandbox. */
597
+ detach() {
598
+ if (this._exitCode !== void 0 || this._detached) return;
599
+ this._detached = true;
600
+ this.stream?.detach();
601
+ }
602
+ };
603
+ var GroundboxProcessManager = class extends SandboxProcessManager {
604
+ defaultTimeout;
605
+ constructor(options = {}) {
606
+ super();
607
+ this.defaultTimeout = options.defaultTimeout;
608
+ }
609
+ async spawn(command, options = {}) {
610
+ const timeout = options.timeout ?? this.defaultTimeout;
611
+ const cwd = options.cwd ?? this.sandbox.workingDirectory;
612
+ const env = definedEnv(options.env);
613
+ const stdinOpen = options.stdinMode !== "ignore";
614
+ return this.sandbox.retryOnDead(async () => {
615
+ const client = this.sandbox.groundbox;
616
+ const sandboxId = this.sandbox.requireSandboxId();
617
+ const startTime = Date.now();
618
+ const started = await client.start_command(sandboxId, command, {
619
+ ...cwd !== void 0 && { cwd },
620
+ ...Object.keys(env).length > 0 && { env },
621
+ timeout_s: timeout !== void 0 ? Math.min(toSeconds(timeout), NO_TIMEOUT_S) : NO_TIMEOUT_S,
622
+ stdin: stdinOpen
623
+ });
624
+ let handle;
625
+ const early = [];
626
+ const stream = client.attach_command(sandboxId, started.id, { seq: 0 }, {
627
+ onStdout: (text) => handle ? handle.emitStdout(text) : early.push(["stdout", text]),
628
+ onStderr: (text) => handle ? handle.emitStderr(text) : early.push(["stderr", text])
629
+ });
630
+ handle = new GroundboxProcessHandle(started.id, client, sandboxId, stream, startTime, stdinOpen, options);
631
+ for (const [kind, text] of early.splice(0)) {
632
+ if (kind === "stdout") handle.emitStdout(text);
633
+ else handle.emitStderr(text);
634
+ }
635
+ this._tracked.set(handle.pid, handle);
636
+ return handle;
637
+ });
638
+ }
639
+ async list() {
640
+ const result = [];
641
+ for (const [pid, handle] of this._tracked) {
642
+ result.push({
643
+ pid,
644
+ ...handle.command !== void 0 && { command: handle.command },
645
+ running: handle.exitCode === void 0,
646
+ ...handle.exitCode !== void 0 && { exitCode: handle.exitCode }
647
+ });
648
+ }
649
+ return result;
650
+ }
651
+ /**
652
+ * A tracked process, or a Groundbox command this manager did not start (by its `ex_...` id),
653
+ * attached from the start of its kept output.
654
+ */
655
+ async get(pid, options) {
656
+ const tracked = this._tracked.get(pid);
657
+ if (tracked) return tracked;
658
+ if (!pid.startsWith("ex_")) return void 0;
659
+ const client = this.sandbox.groundbox;
660
+ const sandboxId = this.sandbox.sandboxId;
661
+ if (!sandboxId) return void 0;
662
+ let command;
663
+ try {
664
+ command = await client.get_command(sandboxId, pid);
665
+ } catch (error) {
666
+ if (errorCode(error) === "not_found") return void 0;
667
+ throw error;
668
+ }
669
+ const startTime = command.started_at ? Date.parse(command.started_at) : Date.now();
670
+ let handle;
671
+ const early = [];
672
+ const stream = command.output_kept || command.state === "running" ? client.attach_command(sandboxId, pid, { seq: 0 }, {
673
+ onStdout: (text) => handle ? handle.emitStdout(text) : early.push(["stdout", text]),
674
+ onStderr: (text) => handle ? handle.emitStderr(text) : early.push(["stderr", text])
675
+ }) : void 0;
676
+ handle = new GroundboxProcessHandle(pid, client, sandboxId, stream, startTime, command.stdin);
677
+ for (const [kind, text] of early.splice(0)) {
678
+ if (kind === "stdout") handle.emitStdout(text);
679
+ else handle.emitStderr(text);
680
+ }
681
+ const commandLine = command.cmd ?? command.args?.join(" ");
682
+ if (commandLine) handle.command = commandLine;
683
+ void options;
684
+ this._tracked.set(pid, handle);
685
+ return handle;
686
+ }
687
+ /** Stop following every tracked process's output and forget them (the sandbox is going away). */
688
+ detachAll() {
689
+ for (const pid of [...this._tracked.keys()]) this.release(pid);
690
+ }
691
+ /** Release a process and stop following its output. */
692
+ release(pid) {
693
+ const handle = this._tracked.get(pid);
694
+ if (handle instanceof GroundboxProcessHandle) handle.detach();
695
+ super.release(pid);
696
+ }
697
+ };
698
+
699
+ // src/sandbox.ts
700
+ var LOG_PREFIX = "[@groundbox/mastra]";
701
+ var MASTRA_ID_METADATA_KEY = "mastra-sandbox-id";
702
+ var CHECKPOINT_LABEL_PREFIX = "mastra:";
703
+ var DEFAULT_COMMAND_TIMEOUT_MS = 3e5;
704
+ var MAX_RUN_COMMAND_MS = 36e5;
705
+ var DEFAULT_MAX_RETAINED_BYTES = 1048576;
706
+ var TRANSITIONAL = /* @__PURE__ */ new Set(["queued", "starting", "resuming", "pausing", "shutting_down"]);
707
+ var ENDED = /* @__PURE__ */ new Set(["stopping", "stopped", "failed"]);
708
+ var SETTLE_TIMEOUT_MS = 3e5;
709
+ var SETTLE_POLL_MS = 1e3;
710
+ var GroundboxSandbox = class _GroundboxSandbox extends MastraSandbox {
711
+ id;
712
+ name = "GroundboxSandbox";
713
+ provider = "groundbox";
714
+ status = "pending";
715
+ supportsCheckpoints = true;
716
+ /**
717
+ * Public HTTPS URLs for ports in the sandbox, through Groundbox previews
718
+ * (`https://<slug>-<port>.groundbox.page`). The app must listen on 0.0.0.0. Private unless
719
+ * `publicPreviews` is set. Previews are on the paid plan.
720
+ */
721
+ networking = {
722
+ getPortUrl: async (port) => {
723
+ try {
724
+ const id = this._sandboxId ?? (await this.lookup())?.id;
725
+ if (!id) return null;
726
+ const preview = await this.client.expose_port(id, port, this.publicPreviews ? { public: true } : {});
727
+ return preview.url;
728
+ } catch (error) {
729
+ this.logger.debug(`${LOG_PREFIX} No preview for port ${port}`, { error });
730
+ return null;
731
+ }
732
+ }
733
+ };
734
+ client;
735
+ commandTimeout;
736
+ options;
737
+ publicPreviews;
738
+ checkpointName;
739
+ _sandbox = null;
740
+ _sandboxId;
741
+ _preferredSandboxId;
742
+ _createdAt = null;
743
+ _isRetrying = false;
744
+ _filesystem;
745
+ /** The `workingDirectory` option as given, apart from the detected home folder. */
746
+ explicitWorkingDirectory;
747
+ constructor(options = {}) {
748
+ const commandTimeout = options.timeout ?? DEFAULT_COMMAND_TIMEOUT_MS;
749
+ super({
750
+ ...options,
751
+ name: "GroundboxSandbox",
752
+ processes: new GroundboxProcessManager()
753
+ });
754
+ this.options = { ...options };
755
+ this.id = options.id ?? `groundbox-sandbox-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
756
+ this.client = options.client ?? new Groundbox({
757
+ ...options.apiKey !== void 0 && { apiKey: options.apiKey },
758
+ ...options.baseUrl !== void 0 && { baseUrl: options.baseUrl },
759
+ userAgent: "groundbox-mastra"
760
+ });
761
+ this.commandTimeout = commandTimeout;
762
+ this.defaultCommandTimeout = commandTimeout;
763
+ this.publicPreviews = options.publicPreviews ?? false;
764
+ this.checkpointName = options.checkpointName ?? this.id;
765
+ this._preferredSandboxId = options.sandboxId;
766
+ this.explicitWorkingDirectory = options.workingDirectory;
767
+ if (options.desktop) this.computer = createGroundboxComputer(this);
768
+ }
769
+ /** The Groundbox client this sandbox uses, for any API call this class does not wrap. */
770
+ get groundbox() {
771
+ return this.client;
772
+ }
773
+ /** The Groundbox sandbox id (`sbx_...`), once started. Persist it to reattach with `sandboxId`. */
774
+ get sandboxId() {
775
+ return this._sandboxId;
776
+ }
777
+ /** The Groundbox sandbox as last read. */
778
+ get instance() {
779
+ if (!this._sandbox) throw new SandboxNotReadyError(this.id);
780
+ return this._sandbox;
781
+ }
782
+ /** The sandbox's disk through Groundbox's files API. Pass it as the workspace `filesystem` to give the agent file tools on it. */
783
+ get filesystem() {
784
+ if (!this._filesystem) this._filesystem = new GroundboxSandboxFilesystem(this);
785
+ return this._filesystem;
786
+ }
787
+ /** @internal The Groundbox sandbox id; throws when the sandbox has not been started. */
788
+ requireSandboxId() {
789
+ if (!this._sandboxId || !this._sandbox) throw new SandboxNotReadyError(this.id);
790
+ return this._sandboxId;
791
+ }
792
+ /**
793
+ * A sibling sandbox with this one's settings and per-instance overrides. No I/O: it creates
794
+ * (or reconnects to the sandbox for its `id`, or reattaches to `sandboxId`) on its own start.
795
+ * `idleTimeoutMinutes` becomes Groundbox's idle pause.
796
+ */
797
+ clone(options = {}) {
798
+ const { id: _id, sandboxId: _sandboxId, checkpointName: _cp, seedCheckpointName: _seed, ...base } = this.options;
799
+ return new _GroundboxSandbox({
800
+ ...base,
801
+ client: this.client,
802
+ ...options.id !== void 0 && { id: options.id },
803
+ ...options.sandboxId !== void 0 && { sandboxId: options.sandboxId },
804
+ ...options.env !== void 0 && { env: options.env },
805
+ ...options.workingDirectory !== void 0 && { workingDirectory: options.workingDirectory },
806
+ ...options.idleTimeoutMinutes !== void 0 && { idleTimeoutSeconds: Math.max(30, Math.round(options.idleTimeoutMinutes * 60)) },
807
+ ...options.checkpointName !== void 0 && { checkpointName: options.checkpointName },
808
+ ...options.seedCheckpointName !== void 0 && { seedCheckpointName: options.seedCheckpointName }
809
+ });
810
+ }
811
+ // ---------------------------------------------------------------------------
812
+ // Start: find / connect / create (the base class orchestrates them)
813
+ // ---------------------------------------------------------------------------
814
+ /**
815
+ * The Groundbox sandbox for this logical id: the one named by `sandboxId` (or the last one
816
+ * this instance had) when it is still there, else the newest live sandbox whose metadata
817
+ * carries this id. Errors other than not-found propagate: making a duplicate on an auth or
818
+ * network error would be worse than failing.
819
+ */
820
+ async find() {
821
+ if (this._sandbox) return this._sandbox;
822
+ if (this._preferredSandboxId) {
823
+ try {
824
+ const sandbox = await this.client.get_sandbox(this._preferredSandboxId);
825
+ if (!ENDED.has(sandbox.status)) return sandbox;
826
+ } catch (error) {
827
+ if (errorCode(error) !== "not_found") throw error;
828
+ }
829
+ this._preferredSandboxId = void 0;
830
+ }
831
+ return this.lookup();
832
+ }
833
+ /** The newest live sandbox for this logical id, without starting or resuming it. */
834
+ async lookup() {
835
+ const list = await this.client.list_sandboxes({ live: true, metadata: { [MASTRA_ID_METADATA_KEY]: this.id }, limit: 10 });
836
+ return list.data.find((sandbox) => !ENDED.has(sandbox.status));
837
+ }
838
+ /** Bring an existing sandbox to `running`: wait out a transition, resume a paused one, start a shut-down one. */
839
+ async connect(existing) {
840
+ if (existing === this._sandbox && existing.status === "running") return;
841
+ let sandbox = await this.settle(existing);
842
+ if (sandbox.status === "paused") {
843
+ this.logger.debug(`${LOG_PREFIX} Resuming ${sandbox.id} for ${this.id}`);
844
+ sandbox = await this.client.resume_sandbox(sandbox.id);
845
+ } else if (sandbox.status === "shut_down") {
846
+ this.logger.debug(`${LOG_PREFIX} Starting ${sandbox.id} for ${this.id}`);
847
+ sandbox = await this.client.start_sandbox(sandbox.id);
848
+ }
849
+ if (sandbox.status !== "running") sandbox = await this.client.wait_for_sandbox(sandbox.id);
850
+ if (sandbox.status !== "running") {
851
+ throw new Error(`${LOG_PREFIX} Groundbox sandbox ${sandbox.id} is ${sandbox.status}${sandbox.error ? `: ${sandbox.error}` : ""}`);
852
+ }
853
+ await this.adopt(sandbox);
854
+ this.logger.debug(`${LOG_PREFIX} Reconnected to ${sandbox.id} for ${this.id}`);
855
+ }
856
+ async create() {
857
+ const spec = await this.createSpec();
858
+ this.logger.debug(`${LOG_PREFIX} Creating a sandbox for ${this.id}`);
859
+ let sandbox = await this.client.create_sandbox(spec, { idempotencyKey: randomUUID() });
860
+ if (sandbox.status !== "running") sandbox = await this.client.wait_for_sandbox(sandbox.id);
861
+ if (sandbox.status !== "running") {
862
+ await this.client.delete_sandbox(sandbox.id).catch(() => void 0);
863
+ throw new Error(`${LOG_PREFIX} Groundbox sandbox ${sandbox.id} did not start (${sandbox.status})${sandbox.error ? `: ${sandbox.error}` : ""}`);
864
+ }
865
+ await this.adopt(sandbox);
866
+ this.logger.debug(`${LOG_PREFIX} Created ${sandbox.id} for ${this.id}`);
867
+ }
868
+ /** The create request: this sandbox's settings, booted from a checkpoint when one is kept. */
869
+ async createSpec() {
870
+ const o = this.options;
871
+ const env = definedEnv(o.env);
872
+ const common = {
873
+ metadata: { ...o.metadata, [MASTRA_ID_METADATA_KEY]: this.id },
874
+ ...Object.keys(env).length > 0 && { env },
875
+ ...o.secrets && { secrets: o.secrets },
876
+ ...o.envFromSecrets && { env_from_secrets: o.envFromSecrets },
877
+ ...o.allowHosts && { allow_hosts: o.allowHosts },
878
+ ...o.denyHosts && { deny_hosts: o.denyHosts },
879
+ ...o.timeoutMinutes !== void 0 && { timeout_minutes: o.timeoutMinutes },
880
+ ...o.onTimeout && { on_timeout: o.onTimeout },
881
+ ...o.idleTimeoutSeconds !== void 0 && { idle_timeout_seconds: o.idleTimeoutSeconds },
882
+ ...o.flex && { flex: true }
883
+ };
884
+ const checkpoint = o.snapshotId === void 0 ? await this.findCheckpoint(this.checkpointName) ?? (o.seedCheckpointName ? await this.findCheckpoint(o.seedCheckpointName) : void 0) : void 0;
885
+ const snapshotId = o.snapshotId ?? checkpoint?.id;
886
+ if (snapshotId) {
887
+ return { ...common, snapshot_id: snapshotId };
888
+ }
889
+ const desktop = o.desktop === void 0 || o.desktop === false ? void 0 : o.desktop === true ? true : {
890
+ ...o.desktop.width !== void 0 && { width: o.desktop.width },
891
+ ...o.desktop.height !== void 0 && { height: o.desktop.height },
892
+ ...o.desktop.startUrl !== void 0 && { start_url: o.desktop.startUrl },
893
+ ...o.desktop.recording !== void 0 && { recording: o.desktop.recording }
894
+ };
895
+ return {
896
+ ...common,
897
+ ...o.cpus !== void 0 && { cpus: o.cpus },
898
+ ...o.memoryGb !== void 0 && { memory_gb: o.memoryGb },
899
+ ...o.diskGb !== void 0 && { disk_gb: o.diskGb },
900
+ ...o.image !== void 0 && { image: o.image },
901
+ ...o.template !== void 0 && { template: o.template },
902
+ ...o.volumes && { volumes: o.volumes.map((v) => ({ volume: v.volume, path: v.path, read_only: v.readOnly ?? false })) },
903
+ ...desktop !== void 0 && { desktop }
904
+ };
905
+ }
906
+ /** Wait while the sandbox is between states (queued, pausing, shutting down, ...). */
907
+ async settle(sandbox) {
908
+ const deadline = Date.now() + SETTLE_TIMEOUT_MS;
909
+ let current = sandbox;
910
+ while (TRANSITIONAL.has(current.status) && Date.now() < deadline) {
911
+ if (current.status === "queued" || current.status === "starting" || current.status === "resuming") {
912
+ current = await this.client.wait_for_sandbox(current.id);
913
+ continue;
914
+ }
915
+ await sleep(SETTLE_POLL_MS);
916
+ current = await this.client.get_sandbox(current.id);
917
+ }
918
+ return current;
919
+ }
920
+ async adopt(sandbox) {
921
+ this._sandbox = sandbox;
922
+ this._sandboxId = sandbox.id;
923
+ this._preferredSandboxId = sandbox.id;
924
+ this._createdAt = new Date(sandbox.created_at);
925
+ await this.detectWorkingDirectory();
926
+ }
927
+ /**
928
+ * Groundbox's own image starts commands in /home/runner. On a Docker image, a template or a
929
+ * snapshot the home folder can differ, so it is read from the sandbox once.
930
+ */
931
+ async detectWorkingDirectory() {
932
+ if (this.explicitWorkingDirectory !== void 0 || !this._sandboxId) return;
933
+ const o = this.options;
934
+ if (!o.image && !o.template && !o.snapshotId && !this._sandbox?.snapshot_id && !this._sandbox?.template) {
935
+ this.setWorkingDirectory("/home/runner");
936
+ return;
937
+ }
938
+ try {
939
+ const result = await this.client.run_command(this._sandboxId, "pwd", { timeout_s: 30 });
940
+ const dir = result.stdout.trim();
941
+ if (result.exit_code === 0 && dir.startsWith("/")) this.setWorkingDirectory(dir);
942
+ } catch (error) {
943
+ this.logger.debug(`${LOG_PREFIX} Could not read the working directory`, { error });
944
+ }
945
+ }
946
+ /** Read the Groundbox sandbox again and keep it. */
947
+ async refresh() {
948
+ if (!this._sandboxId) return void 0;
949
+ const sandbox = await this.client.get_sandbox(this._sandboxId);
950
+ if (this._sandbox) this._sandbox = sandbox;
951
+ return sandbox;
952
+ }
953
+ // ---------------------------------------------------------------------------
954
+ // Stop / destroy
955
+ // ---------------------------------------------------------------------------
956
+ /**
957
+ * Pause the Groundbox sandbox: memory, processes and disk are kept and only storage is
958
+ * billed. The next start resumes it. A sandbox with volumes cannot be paused, so it is shut
959
+ * down instead (disk kept, a cold boot on the next start).
960
+ */
961
+ async stop() {
962
+ const sandbox = this._sandbox ?? await this.lookup().catch(() => void 0) ?? null;
963
+ this.processes.detachAll();
964
+ if (sandbox) {
965
+ const current = await this.settle(await this.client.get_sandbox(sandbox.id).catch(() => sandbox));
966
+ if (current.status === "running") {
967
+ if (this.options.volumes?.length) await this.client.stop_sandbox(current.id);
968
+ else await this.client.pause_sandbox(current.id);
969
+ this.logger.debug(`${LOG_PREFIX} ${this.options.volumes?.length ? "Shut down" : "Paused"} ${current.id} for ${this.id}`);
970
+ }
971
+ this._preferredSandboxId = current.id;
972
+ }
973
+ this._sandbox = null;
974
+ }
975
+ /** Delete the Groundbox sandbox for good. Billing stops. */
976
+ async destroy() {
977
+ const id = this._sandboxId ?? this._preferredSandboxId ?? (await this.lookup().catch(() => void 0))?.id;
978
+ this.processes.detachAll();
979
+ if (id) {
980
+ try {
981
+ await this.client.delete_sandbox(id);
982
+ this.logger.debug(`${LOG_PREFIX} Deleted ${id} for ${this.id}`);
983
+ } catch (error) {
984
+ if (errorCode(error) !== "not_found") throw error;
985
+ }
986
+ }
987
+ this._sandbox = null;
988
+ this._sandboxId = void 0;
989
+ this._preferredSandboxId = void 0;
990
+ }
991
+ async isReady() {
992
+ return this.status === "running" && this._sandbox !== null;
993
+ }
994
+ async getInfo() {
995
+ const s = this._sandbox;
996
+ return {
997
+ id: this.id,
998
+ name: this.name,
999
+ provider: this.provider,
1000
+ status: this.status,
1001
+ createdAt: this._createdAt ?? /* @__PURE__ */ new Date(),
1002
+ ...s?.expires_at && { timeoutAt: new Date(s.expires_at) },
1003
+ mounts: [],
1004
+ ...s && { resources: { cpuCores: s.cpus, memoryMB: s.memory_gb * 1024, diskMB: s.disk_gb * 1024 } },
1005
+ metadata: {
1006
+ ...this._sandboxId && { sandboxId: this._sandboxId },
1007
+ ...s && { groundboxStatus: s.status },
1008
+ ...this.options.image && { image: this.options.image },
1009
+ ...this.options.template && { template: this.options.template },
1010
+ ...s?.snapshot_id && { snapshotId: s.snapshot_id },
1011
+ ...s?.desktop && { desktop: { width: s.desktop.width, height: s.desktop.height } }
1012
+ }
1013
+ };
1014
+ }
1015
+ getInstructions(opts) {
1016
+ const defaultInstructions = this.defaultInstructions();
1017
+ const custom = this.options.instructions;
1018
+ if (custom === void 0) return defaultInstructions;
1019
+ if (typeof custom === "string") return custom;
1020
+ return custom({ defaultInstructions, ...opts?.requestContext && { requestContext: opts.requestContext } });
1021
+ }
1022
+ defaultInstructions() {
1023
+ const o = this.options;
1024
+ const parts = [];
1025
+ if (o.image) {
1026
+ parts.push(`Groundbox sandbox: an isolated Linux microVM started from the Docker image ${o.image}. Commands run as root.`);
1027
+ } else {
1028
+ parts.push(
1029
+ "Groundbox sandbox: an isolated Linux (Ubuntu) microVM. Commands run as user `runner`, who has passwordless sudo, so `sudo apt-get install` works."
1030
+ );
1031
+ }
1032
+ if (this.workingDirectory) parts.push(`Default working directory: ${this.workingDirectory}.`);
1033
+ parts.push(`Command timeout: ${Math.ceil(this.commandTimeout / 1e3)}s; use background processes for servers and long jobs.`);
1034
+ if (o.allowHosts) parts.push(`Network: only these hosts are reachable: ${o.allowHosts.join(", ")}.`);
1035
+ else if (o.denyHosts) parts.push(`Network: these hosts are blocked: ${o.denyHosts.join(", ")}.`);
1036
+ if (o.desktop) parts.push("A Linux desktop with Chrome is running for computer use.");
1037
+ if (o.volumes?.length) parts.push(`Volumes: ${o.volumes.map((v) => `${v.path}${v.readOnly ? " (read-only)" : ""}`).join(", ")}.`);
1038
+ return parts.join(" ");
1039
+ }
1040
+ // ---------------------------------------------------------------------------
1041
+ // Commands and files
1042
+ // ---------------------------------------------------------------------------
1043
+ /**
1044
+ * Run a command and wait for it. Without streaming callbacks or an abort signal this is one
1045
+ * `POST /exec` call; otherwise it is a background command followed over the exec stream.
1046
+ */
1047
+ async executeCommand(command, args, options = {}) {
1048
+ const fullCommand = args?.length ? `${command} ${args.map(shellQuote).join(" ")}` : command;
1049
+ const timeout = options.timeout ?? this.defaultCommandTimeout ?? this.commandTimeout;
1050
+ const maxRetainedBytes = options.maxRetainedBytes ?? DEFAULT_MAX_RETAINED_BYTES;
1051
+ const streamed = options.onStdout || options.onStderr || options.abortSignal || timeout > MAX_RUN_COMMAND_MS;
1052
+ if (streamed) {
1053
+ const handle = await this.processes.spawn(fullCommand, {
1054
+ ...options,
1055
+ timeout,
1056
+ maxRetainedBytes,
1057
+ stdinMode: "ignore",
1058
+ ...args?.length && { originalInvocation: { command, args: [...args] } }
1059
+ });
1060
+ try {
1061
+ const result2 = await handle.wait();
1062
+ if (handle.exitCode === void 0) await handle.kill();
1063
+ return { ...result2, command: fullCommand, ...args && { args } };
1064
+ } finally {
1065
+ this.processes.release(handle.pid);
1066
+ }
1067
+ }
1068
+ await this.ensureRunning();
1069
+ const env = definedEnv({ ...this.getEnv(), ...options.env });
1070
+ const cwd = options.cwd ?? this.workingDirectory;
1071
+ const start = Date.now();
1072
+ const result = await this.retryOnDead(
1073
+ async () => this.client.run_command(this.requireSandboxId(), fullCommand, {
1074
+ ...cwd !== void 0 && { cwd },
1075
+ ...Object.keys(env).length > 0 && { env },
1076
+ timeout_s: toSeconds(timeout)
1077
+ })
1078
+ );
1079
+ const stdout = retainNewest(result.stdout, maxRetainedBytes);
1080
+ const stderr = retainNewest(result.stderr, maxRetainedBytes);
1081
+ return {
1082
+ success: result.exit_code === 0 && !result.timed_out,
1083
+ exitCode: result.exit_code,
1084
+ stdout: stdout.text,
1085
+ stderr: stderr.text,
1086
+ executionTimeMs: Date.now() - start,
1087
+ ...result.timed_out && { timedOut: true, killed: true },
1088
+ ...stdout.dropped > 0 && { stdoutTruncated: true, stdoutDroppedBytes: stdout.dropped },
1089
+ ...stderr.dropped > 0 && { stderrTruncated: true, stderrDroppedBytes: stderr.dropped },
1090
+ command: fullCommand,
1091
+ ...args && { args }
1092
+ };
1093
+ }
1094
+ /**
1095
+ * Write many files at once: they go up as one tar.gz and are unpacked in the sandbox. Modes are
1096
+ * kept. A relative path is resolved against the working directory. Files are written as the
1097
+ * sandbox user (`runner` on Groundbox's image), so a path it cannot write to fails.
1098
+ */
1099
+ async writeFiles(files, options) {
1100
+ for (const file of files) if (file.mode !== void 0) validateSandboxFileMode(file.mode);
1101
+ if (options?.abortSignal?.aborted) throw new SandboxAbortError("writeFiles", options.abortSignal.reason);
1102
+ if (files.length === 0) return;
1103
+ await this.ensureRunning();
1104
+ const base = this.workingDirectory ?? "/";
1105
+ const entries = files.map((file) => {
1106
+ const abs = toAbsolute(file.path, base);
1107
+ if (abs === "/") throw new Error(`${LOG_PREFIX} Cannot write a file at /`);
1108
+ return {
1109
+ path: abs.slice(1),
1110
+ content: typeof file.content === "string" ? file.content : new Uint8Array(file.content),
1111
+ ...file.mode !== void 0 && { mode: file.mode }
1112
+ };
1113
+ });
1114
+ try {
1115
+ await this.retryOnDead(
1116
+ () => this.client.upload_files(this.requireSandboxId(), "/", entries, options?.abortSignal ? { signal: options.abortSignal } : {})
1117
+ );
1118
+ } catch (error) {
1119
+ if (options?.abortSignal?.aborted) throw new SandboxAbortError("writeFiles", options.abortSignal.reason);
1120
+ throw error;
1121
+ }
1122
+ }
1123
+ // ---------------------------------------------------------------------------
1124
+ // Checkpoints (Groundbox kept snapshots)
1125
+ // ---------------------------------------------------------------------------
1126
+ /**
1127
+ * Keep the sandbox as it is now (memory, disk and processes) as a Groundbox snapshot named
1128
+ * `checkpointName`, replacing the previous one of that name. The next sandbox started for this
1129
+ * checkpoint boots from it. Kept snapshots are on the paid plan.
1130
+ */
1131
+ async snapshot() {
1132
+ if (!this._sandbox || !this._sandboxId) return;
1133
+ const label = CHECKPOINT_LABEL_PREFIX + this.checkpointName;
1134
+ const kept = await this.client.keep_snapshot({ sandbox_id: this._sandboxId, label });
1135
+ if (kept.status !== "ready") throw new Error(`${LOG_PREFIX} Snapshot ${kept.id} is ${kept.status}${kept.error ? `: ${kept.error}` : ""}`);
1136
+ for (const old of await this.listCheckpoints(label)) {
1137
+ if (old.id !== kept.id) await this.client.delete_snapshot(old.id).catch(() => void 0);
1138
+ }
1139
+ }
1140
+ async listCheckpoints(label) {
1141
+ const list = await this.client.list_snapshots({ limit: 100 });
1142
+ return list.data.filter((snapshot) => snapshot.label === label);
1143
+ }
1144
+ async findCheckpoint(name) {
1145
+ try {
1146
+ const snapshots = await this.listCheckpoints(CHECKPOINT_LABEL_PREFIX + name);
1147
+ return snapshots.filter((snapshot) => snapshot.status === "ready").sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at))[0];
1148
+ } catch (error) {
1149
+ this.logger.debug(`${LOG_PREFIX} Could not list snapshots`, { error });
1150
+ return void 0;
1151
+ }
1152
+ }
1153
+ // ---------------------------------------------------------------------------
1154
+ // A sandbox that went away under us
1155
+ // ---------------------------------------------------------------------------
1156
+ /** Whether `error` came from the sandbox not running, as opposed to the call itself. */
1157
+ async isSandboxGone(error) {
1158
+ const code = errorCode(error);
1159
+ if (code !== "conflict" && code !== "not_found") return false;
1160
+ if (!this._sandboxId) return false;
1161
+ try {
1162
+ const sandbox = await this.client.get_sandbox(this._sandboxId);
1163
+ if (sandbox.status === "running") return false;
1164
+ if (ENDED.has(sandbox.status)) this._preferredSandboxId = void 0;
1165
+ return true;
1166
+ } catch (lookupError) {
1167
+ if (errorCode(lookupError) === "not_found") {
1168
+ this._preferredSandboxId = void 0;
1169
+ return true;
1170
+ }
1171
+ return false;
1172
+ }
1173
+ }
1174
+ /**
1175
+ * Run `fn`; when it fails because the sandbox stopped, was paused or timed out, start it again
1176
+ * (resuming it, or making a new one when it ended) and run `fn` once more.
1177
+ */
1178
+ async retryOnDead(fn) {
1179
+ try {
1180
+ return await fn();
1181
+ } catch (error) {
1182
+ if (this._isRetrying || !await this.isSandboxGone(error)) throw error;
1183
+ this.logger.debug(`${LOG_PREFIX} Sandbox ${this._sandboxId} is not running; starting it again`);
1184
+ this._isRetrying = true;
1185
+ try {
1186
+ this._sandbox = null;
1187
+ this._sandboxId = void 0;
1188
+ this.status = "stopped";
1189
+ await this.ensureRunning();
1190
+ return await fn();
1191
+ } finally {
1192
+ this._isRetrying = false;
1193
+ }
1194
+ }
1195
+ }
1196
+ };
1197
+
1198
+ // src/provider.ts
1199
+ var groundboxSandboxProvider = {
1200
+ id: "groundbox",
1201
+ name: "Groundbox Sandbox",
1202
+ description: "Firecracker microVM Linux sandbox from Groundbox",
1203
+ configSchema: {
1204
+ type: "object",
1205
+ properties: {
1206
+ cpus: { type: "number", description: "vCPUs, 1 to 16", default: 2 },
1207
+ memoryGb: { type: "number", description: "Memory in GB, up to 4 per vCPU" },
1208
+ diskGb: { type: "number", description: "Disk in GB", default: 20 },
1209
+ image: { type: "string", description: "Docker image to start from (commands then run as root)" },
1210
+ template: { type: "string", description: "Groundbox template id or name" },
1211
+ timeout: { type: "number", description: "Command timeout in milliseconds", default: 3e5 },
1212
+ timeoutMinutes: { type: "number", description: "Sandbox lifetime in minutes", default: 60 },
1213
+ idleTimeoutSeconds: { type: "number", description: "Pause after this many idle seconds (at least 30)" },
1214
+ env: { type: "object", description: "Environment variables", additionalProperties: { type: "string" } },
1215
+ metadata: { type: "object", description: "Metadata pairs", additionalProperties: { type: "string" } },
1216
+ allowHosts: { type: "array", items: { type: "string" }, description: "Hosts the sandbox may reach" },
1217
+ denyHosts: { type: "array", items: { type: "string" }, description: "Hosts the sandbox may not reach" },
1218
+ desktop: { type: "boolean", description: "Start a Linux desktop with Chrome for computer use", default: false },
1219
+ publicPreviews: { type: "boolean", description: "Make port previews public", default: false },
1220
+ apiKey: { type: "string", description: "Groundbox API key (defaults to GROUNDBOX_API_KEY)" },
1221
+ baseUrl: { type: "string", description: "Groundbox API URL" }
1222
+ }
1223
+ },
1224
+ createSandbox: (config) => new GroundboxSandbox(config)
1225
+ };
1226
+ export {
1227
+ GroundboxProcessHandle,
1228
+ GroundboxProcessManager,
1229
+ GroundboxSandbox,
1230
+ GroundboxSandboxFilesystem,
1231
+ MASTRA_ID_METADATA_KEY,
1232
+ createGroundboxComputer,
1233
+ groundboxSandboxProvider,
1234
+ toKeyCombo,
1235
+ toKeysym
1236
+ };
1237
+ //# sourceMappingURL=index.js.map