@mastra/sprites 0.0.0-agent-tags-alpha-20261125185303

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/LICENSE.md ADDED
@@ -0,0 +1,32 @@
1
+ Portions of this software are licensed as follows:
2
+
3
+ - All content that resides under any directory named `ee/` within this
4
+ repository, including but not limited to:
5
+ - `@mastra/core/auth/ee`
6
+ - `@mastra/core/agent-builder/ee`
7
+ - `@mastra/editor/ee`
8
+
9
+ is licensed under the license defined in [`ee/LICENSE`](https://github.com/mastra-ai/mastra/blob/main/ee/LICENSE).
10
+
11
+ - All third-party components incorporated into the Mastra Software are
12
+ licensed under the original license provided by the owner of the
13
+ applicable component.
14
+
15
+ - Content outside of the above-mentioned directories or restrictions is
16
+ available under the "Apache License 2.0" as defined below.
17
+
18
+ # Apache License 2.0
19
+
20
+ Copyright (c) 2025 Kepler Software, Inc.
21
+
22
+ Licensed under the Apache License, Version 2.0 (the "License");
23
+ you may not use this file except in compliance with the License.
24
+ You may obtain a copy of the License at
25
+
26
+ http://www.apache.org/licenses/LICENSE-2.0
27
+
28
+ Unless required by applicable law or agreed to in writing, software
29
+ distributed under the License is distributed on an "AS IS" BASIS,
30
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31
+ See the License for the specific language governing permissions and
32
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,47 @@
1
+ # @mastra/sprites
2
+
3
+ Fly.io Sprites sandbox provider for [Mastra](https://mastra.ai) workspaces.
4
+
5
+ Implements the `WorkspaceSandbox` interface using [Fly.io Sprites](https://sprites.dev) — persistent Linux VMs that keep their filesystem between runs and hibernate when idle — through the official `@fly/sprites` SDK. Supports get-or-create by Sprite name, command execution with streaming output, timeouts and cancellation, background processes with stdin, and checkpoint capture.
6
+
7
+ Requires Node.js 24 or later.
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ npm install @mastra/sprites
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ```typescript
18
+ import { Workspace } from '@mastra/core/workspace';
19
+ import { SpritesSandbox } from '@mastra/sprites';
20
+
21
+ const sandbox = new SpritesSandbox({
22
+ id: 'mastra-project',
23
+ // token read from SPRITES_TOKEN
24
+ });
25
+
26
+ const workspace = new Workspace({ sandbox });
27
+ await workspace.init();
28
+
29
+ const result = await workspace.sandbox.executeCommand('echo', ['Hello!']);
30
+ console.log(result.stdout); // "Hello!"
31
+
32
+ // stop() keeps the Sprite and its files; destroy() deletes it.
33
+ await sandbox.destroy();
34
+ ```
35
+
36
+ ## Documentation
37
+
38
+ - [Fly.io Sprites integration guide](https://mastra.ai/integrations/sandboxes/sprites)
39
+ - [Workspace documentation](https://mastra.ai/docs/mastra-platform/workspaces)
40
+
41
+ ## Changelog
42
+
43
+ See the [package changelog](https://github.com/mastra-ai/mastra/blob/main/workspaces/sprites/CHANGELOG.md) for version history and release notes.
44
+
45
+ ## Support
46
+
47
+ We have an [open community Discord](https://discord.gg/mastra-ai). Come and say hello and let us know if you have any questions or need any help getting things running.
package/dist/index.cjs ADDED
@@ -0,0 +1,336 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _fly_sprites = require("@fly/sprites");
3
+ let _mastra_core_workspace = require("@mastra/core/workspace");
4
+ // src/sandbox/process-manager.ts
5
+ const LOG_PREFIX = "[SpritesSandbox]";
6
+ /** Exit code reported for processes terminated by `kill()` or a timeout. */
7
+ const KILLED_EXIT_CODE = 137;
8
+ var SpritesProcessHandle = class extends _mastra_core_workspace.ProcessHandle {
9
+ pid;
10
+ _cmd;
11
+ _startTime = Date.now();
12
+ _done;
13
+ _exitCode;
14
+ _killed = false;
15
+ _timedOut = false;
16
+ _timeoutId;
17
+ _error;
18
+ constructor(pid, cmd, options, timeout) {
19
+ super(options);
20
+ this.pid = pid;
21
+ this._cmd = cmd;
22
+ cmd.stdout.setEncoding("utf8");
23
+ cmd.stderr.setEncoding("utf8");
24
+ cmd.stdout.on("data", (chunk) => this.emitStdout(chunk));
25
+ cmd.stderr.on("data", (chunk) => this.emitStderr(chunk));
26
+ cmd.on("error", (error) => {
27
+ this._error ??= error;
28
+ });
29
+ this._done = Promise.all([
30
+ cmd.wait(),
31
+ streamEnded(cmd.stdout),
32
+ streamEnded(cmd.stderr)
33
+ ]).then(([code]) => {
34
+ clearTimeout(this._timeoutId);
35
+ this._exitCode = this._killed ? KILLED_EXIT_CODE : code < 0 ? 1 : code;
36
+ });
37
+ if (timeout !== void 0 && timeout > 0) this._timeoutId = setTimeout(() => {
38
+ this._timedOut = true;
39
+ this.kill();
40
+ }, timeout);
41
+ }
42
+ get exitCode() {
43
+ return this._exitCode;
44
+ }
45
+ async wait() {
46
+ await this._done;
47
+ const exitCode = this._exitCode;
48
+ let stderr = this.stderr;
49
+ if (exitCode !== 0 && !stderr && this._error && !this._killed) stderr = this._error.message;
50
+ return {
51
+ success: exitCode === 0,
52
+ exitCode,
53
+ stdout: this.stdout,
54
+ stderr,
55
+ executionTimeMs: Date.now() - this._startTime,
56
+ ...this._killed && { killed: true },
57
+ ...this._timedOut && { timedOut: true }
58
+ };
59
+ }
60
+ async kill() {
61
+ if (this._exitCode !== void 0 || this._killed) return false;
62
+ this._killed = true;
63
+ clearTimeout(this._timeoutId);
64
+ this._cmd.kill("SIGKILL");
65
+ this._cmd.close();
66
+ return true;
67
+ }
68
+ async sendStdin(data) {
69
+ if (this._exitCode !== void 0) throw new Error(`${LOG_PREFIX} Cannot write to stdin: process ${this.pid} has exited`);
70
+ await new Promise((resolve, reject) => {
71
+ this._cmd.stdin.write(data, (error) => error ? reject(error) : resolve());
72
+ });
73
+ }
74
+ async closeStdin() {
75
+ this._cmd.stdin.end();
76
+ }
77
+ };
78
+ var SpritesProcessManager = class extends _mastra_core_workspace.SandboxProcessManager {
79
+ _spawnCounter = 0;
80
+ async spawn(command, options = {}) {
81
+ const env = Object.fromEntries(Object.entries(options.env ?? {}).filter((entry) => entry[1] !== void 0));
82
+ const cwd = options.cwd ?? this.sandbox.workingDirectory;
83
+ const cmd = this.sandbox.sprite.spawn("sh", ["-c", command], {
84
+ ...cwd && { cwd },
85
+ ...Object.keys(env).length > 0 && { env }
86
+ });
87
+ try {
88
+ await waitForSpawn(cmd);
89
+ } catch (error) {
90
+ cmd.close();
91
+ throw error;
92
+ }
93
+ if (options.stdinMode === "ignore") cmd.stdin.end();
94
+ const pid = `sprites-proc-${Date.now().toString(36)}-${(++this._spawnCounter).toString(36)}`;
95
+ const handle = new SpritesProcessHandle(pid, cmd, options, options.timeout ?? this.sandbox.defaultTimeout);
96
+ this._tracked.set(pid, handle);
97
+ return handle;
98
+ }
99
+ /**
100
+ * Lists processes spawned by this instance. The Sprites exec API has no
101
+ * listing for non-detachable commands, so processes started elsewhere are
102
+ * not included.
103
+ */
104
+ async list() {
105
+ return [...this._tracked.values()].map((handle) => ({
106
+ pid: handle.pid,
107
+ command: handle.command,
108
+ running: handle.exitCode === void 0,
109
+ ...handle.exitCode !== void 0 && { exitCode: handle.exitCode }
110
+ }));
111
+ }
112
+ /** Kill every running process spawned by this instance. Does not start the sandbox. */
113
+ async killAll() {
114
+ const running = [...this._tracked.values()].filter((handle) => handle.exitCode === void 0);
115
+ await Promise.all(running.map((handle) => this.kill(handle.pid)));
116
+ }
117
+ };
118
+ function waitForSpawn(cmd) {
119
+ return new Promise((resolve, reject) => {
120
+ const onSpawn = () => {
121
+ cmd.off("error", onError);
122
+ resolve();
123
+ };
124
+ const onError = (error) => {
125
+ cmd.off("spawn", onSpawn);
126
+ reject(error);
127
+ };
128
+ cmd.once("spawn", onSpawn);
129
+ cmd.once("error", onError);
130
+ });
131
+ }
132
+ function streamEnded(stream) {
133
+ return new Promise((resolve) => {
134
+ stream.once("end", () => resolve());
135
+ stream.once("close", () => resolve());
136
+ });
137
+ }
138
+ // src/sandbox/index.ts
139
+ /**
140
+ * Fly.io Sprites Sandbox Provider
141
+ *
142
+ * A Sprites sandbox implementation for Mastra workspaces. Gets or creates a
143
+ * persistent Fly.io Sprite by name and runs commands in it through the
144
+ * official `@fly/sprites` SDK. Sprites keep their filesystem between runs and
145
+ * hibernate on their own when idle.
146
+ *
147
+ * @see https://sprites.dev
148
+ */
149
+ var SpritesSandbox = class extends _mastra_core_workspace.MastraSandbox {
150
+ id;
151
+ name = "SpritesSandbox";
152
+ provider = "sprites";
153
+ status = "pending";
154
+ _client = null;
155
+ _sprite = null;
156
+ _createdAt = null;
157
+ _token;
158
+ _baseURL;
159
+ _spriteConfig;
160
+ _timeout;
161
+ _instructionsOverride;
162
+ constructor(options = {}) {
163
+ super({
164
+ ...options,
165
+ name: "SpritesSandbox",
166
+ processes: new SpritesProcessManager()
167
+ });
168
+ this.id = options.id ?? `mastra-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
169
+ this._token = options.token ?? process.env.SPRITES_TOKEN;
170
+ this._baseURL = options.baseURL;
171
+ this._spriteConfig = options.spriteConfig;
172
+ this._timeout = options.timeout;
173
+ this._instructionsOverride = options.instructions;
174
+ }
175
+ /** The underlying SDK `Sprite`. Throws if the sandbox has not been started. */
176
+ get sprite() {
177
+ if (!this._sprite) throw new _mastra_core_workspace.SandboxNotReadyError(this.id);
178
+ return this._sprite;
179
+ }
180
+ /** Default command timeout in milliseconds, if configured. */
181
+ get defaultTimeout() {
182
+ return this._timeout;
183
+ }
184
+ get client() {
185
+ if (!this._client) {
186
+ if (!this._token) throw new Error(`${LOG_PREFIX} Missing Sprites API token. Pass \`token\` or set the SPRITES_TOKEN environment variable.`);
187
+ this._client = new _fly_sprites.SpritesClient(this._token, this._baseURL ? { baseURL: this._baseURL } : void 0);
188
+ }
189
+ return this._client;
190
+ }
191
+ /**
192
+ * Get the Sprite named `id`, creating it when it does not exist.
193
+ * Reports `outcome: 'created'` only when a new Sprite was provisioned.
194
+ */
195
+ async start() {
196
+ if (this._sprite) return { outcome: "connected" };
197
+ const client = this.client;
198
+ let outcome = "connected";
199
+ let sprite;
200
+ try {
201
+ sprite = await client.getSprite(this.id);
202
+ } catch (error) {
203
+ if (!isStatus(error, 404)) throw error;
204
+ try {
205
+ sprite = await client.createSprite(this.id, this._spriteConfig);
206
+ outcome = "created";
207
+ } catch (createError) {
208
+ if (!isStatus(createError, 409)) throw createError;
209
+ sprite = await client.getSprite(this.id);
210
+ }
211
+ }
212
+ this._sprite = sprite;
213
+ this._createdAt = sprite.createdAt ?? /* @__PURE__ */ new Date();
214
+ this.logger.debug(`${LOG_PREFIX} Sprite ready`, {
215
+ id: this.id,
216
+ outcome
217
+ });
218
+ return { outcome };
219
+ }
220
+ /**
221
+ * Release local resources: kill background processes started by this
222
+ * instance and close the SDK control connection.
223
+ *
224
+ * The Sprite itself is NOT deleted or suspended. Sprites hibernate on their
225
+ * own when idle, and `start()` reconnects to the same filesystem.
226
+ */
227
+ async stop() {
228
+ await this._killTrackedProcesses();
229
+ this._sprite?.closeControlConnection();
230
+ this._sprite = null;
231
+ }
232
+ /**
233
+ * Permanently delete the Sprite and its filesystem. A Sprite that no longer
234
+ * exists is treated as already destroyed.
235
+ */
236
+ async destroy() {
237
+ await this._killTrackedProcesses();
238
+ const sprite = this._sprite ?? this.client.sprite(this.id);
239
+ sprite.closeControlConnection();
240
+ this._sprite = null;
241
+ try {
242
+ await sprite.delete();
243
+ } catch (error) {
244
+ if (!isStatus(error, 404)) throw error;
245
+ }
246
+ }
247
+ /**
248
+ * Capture a checkpoint of the Sprite's current state.
249
+ *
250
+ * Checkpoints live inside this Sprite only and cannot seed other sandboxes,
251
+ * so `supportsCheckpoints` stays `false`.
252
+ */
253
+ async snapshot() {
254
+ await this.ensureRunning();
255
+ await (await this.sprite.createCheckpoint("mastra snapshot")).processAll((message) => {
256
+ if (message.type === "error") throw new Error(`${LOG_PREFIX} Checkpoint failed: ${message.error ?? message.data ?? "unknown error"}`);
257
+ });
258
+ }
259
+ async _killTrackedProcesses() {
260
+ await this.processes.killAll().catch((error) => {
261
+ this.logger.warn(`${LOG_PREFIX} Failed to kill background processes`, { error });
262
+ });
263
+ }
264
+ async getInfo() {
265
+ const sprite = this._sprite;
266
+ return {
267
+ id: this.id,
268
+ name: this.name,
269
+ provider: this.provider,
270
+ status: this.status,
271
+ createdAt: this._createdAt ?? /* @__PURE__ */ new Date(),
272
+ metadata: { ...sprite && {
273
+ ...sprite.id && { spriteId: sprite.id },
274
+ ...sprite.status && { spriteStatus: sprite.status },
275
+ ...sprite.url && { url: sprite.url },
276
+ ...sprite.primaryRegion && { region: sprite.primaryRegion }
277
+ } }
278
+ };
279
+ }
280
+ getInstructions() {
281
+ const defaultInstructions = this._buildDefaultInstructions();
282
+ if (typeof this._instructionsOverride === "string") return this._instructionsOverride;
283
+ if (typeof this._instructionsOverride === "function") return this._instructionsOverride({ defaultInstructions });
284
+ return defaultInstructions;
285
+ }
286
+ _buildDefaultInstructions() {
287
+ const parts = ["Fly.io Sprite: a persistent Linux VM. Files written to disk survive between sessions.", this.workingDirectory ? `Commands run in ${this.workingDirectory} by default.` : "Commands run in the Sprite user home directory by default."];
288
+ if (this._timeout !== void 0) parts.push(`Default command timeout: ${Math.ceil(this._timeout / 1e3)}s.`);
289
+ return parts.join(" ");
290
+ }
291
+ };
292
+ function isStatus(error, statusCode) {
293
+ return error instanceof _fly_sprites.APIError && error.statusCode === statusCode;
294
+ }
295
+ // src/provider.ts
296
+ const spritesSandboxProvider = {
297
+ id: "sprites",
298
+ name: "Fly.io Sprites",
299
+ description: "Persistent Linux VM powered by Fly.io Sprites",
300
+ configSchema: {
301
+ type: "object",
302
+ properties: {
303
+ id: {
304
+ type: "string",
305
+ description: "Sprite name. An existing Sprite with this name is reused."
306
+ },
307
+ token: {
308
+ type: "string",
309
+ description: "Sprites API token (falls back to SPRITES_TOKEN)"
310
+ },
311
+ env: {
312
+ type: "object",
313
+ description: "Environment variables",
314
+ additionalProperties: { type: "string" }
315
+ },
316
+ timeout: {
317
+ type: "number",
318
+ description: "Default command timeout in ms"
319
+ },
320
+ workingDirectory: {
321
+ type: "string",
322
+ description: "Default working directory for commands"
323
+ }
324
+ }
325
+ },
326
+ createSandbox: ({ id, token, env, timeout, workingDirectory }) => new SpritesSandbox({
327
+ id,
328
+ token,
329
+ env,
330
+ timeout,
331
+ workingDirectory
332
+ })
333
+ };
334
+ exports.SpritesProcessManager = SpritesProcessManager;
335
+ exports.SpritesSandbox = SpritesSandbox;
336
+ exports.spritesSandboxProvider = spritesSandboxProvider;
@@ -0,0 +1,4 @@
1
+ export { SpritesSandbox, type SpritesSandboxOptions } from './sandbox/index.js';
2
+ export { SpritesProcessManager } from './sandbox/process-manager.js';
3
+ export { spritesSandboxProvider } from './provider.js';
4
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,333 @@
1
+ import { APIError, SpritesClient } from "@fly/sprites";
2
+ import { MastraSandbox, ProcessHandle, SandboxNotReadyError, SandboxProcessManager } from "@mastra/core/workspace";
3
+ // src/sandbox/process-manager.ts
4
+ const LOG_PREFIX = "[SpritesSandbox]";
5
+ /** Exit code reported for processes terminated by `kill()` or a timeout. */
6
+ const KILLED_EXIT_CODE = 137;
7
+ var SpritesProcessHandle = class extends ProcessHandle {
8
+ pid;
9
+ _cmd;
10
+ _startTime = Date.now();
11
+ _done;
12
+ _exitCode;
13
+ _killed = false;
14
+ _timedOut = false;
15
+ _timeoutId;
16
+ _error;
17
+ constructor(pid, cmd, options, timeout) {
18
+ super(options);
19
+ this.pid = pid;
20
+ this._cmd = cmd;
21
+ cmd.stdout.setEncoding("utf8");
22
+ cmd.stderr.setEncoding("utf8");
23
+ cmd.stdout.on("data", (chunk) => this.emitStdout(chunk));
24
+ cmd.stderr.on("data", (chunk) => this.emitStderr(chunk));
25
+ cmd.on("error", (error) => {
26
+ this._error ??= error;
27
+ });
28
+ this._done = Promise.all([
29
+ cmd.wait(),
30
+ streamEnded(cmd.stdout),
31
+ streamEnded(cmd.stderr)
32
+ ]).then(([code]) => {
33
+ clearTimeout(this._timeoutId);
34
+ this._exitCode = this._killed ? KILLED_EXIT_CODE : code < 0 ? 1 : code;
35
+ });
36
+ if (timeout !== void 0 && timeout > 0) this._timeoutId = setTimeout(() => {
37
+ this._timedOut = true;
38
+ this.kill();
39
+ }, timeout);
40
+ }
41
+ get exitCode() {
42
+ return this._exitCode;
43
+ }
44
+ async wait() {
45
+ await this._done;
46
+ const exitCode = this._exitCode;
47
+ let stderr = this.stderr;
48
+ if (exitCode !== 0 && !stderr && this._error && !this._killed) stderr = this._error.message;
49
+ return {
50
+ success: exitCode === 0,
51
+ exitCode,
52
+ stdout: this.stdout,
53
+ stderr,
54
+ executionTimeMs: Date.now() - this._startTime,
55
+ ...this._killed && { killed: true },
56
+ ...this._timedOut && { timedOut: true }
57
+ };
58
+ }
59
+ async kill() {
60
+ if (this._exitCode !== void 0 || this._killed) return false;
61
+ this._killed = true;
62
+ clearTimeout(this._timeoutId);
63
+ this._cmd.kill("SIGKILL");
64
+ this._cmd.close();
65
+ return true;
66
+ }
67
+ async sendStdin(data) {
68
+ if (this._exitCode !== void 0) throw new Error(`${LOG_PREFIX} Cannot write to stdin: process ${this.pid} has exited`);
69
+ await new Promise((resolve, reject) => {
70
+ this._cmd.stdin.write(data, (error) => error ? reject(error) : resolve());
71
+ });
72
+ }
73
+ async closeStdin() {
74
+ this._cmd.stdin.end();
75
+ }
76
+ };
77
+ var SpritesProcessManager = class extends SandboxProcessManager {
78
+ _spawnCounter = 0;
79
+ async spawn(command, options = {}) {
80
+ const env = Object.fromEntries(Object.entries(options.env ?? {}).filter((entry) => entry[1] !== void 0));
81
+ const cwd = options.cwd ?? this.sandbox.workingDirectory;
82
+ const cmd = this.sandbox.sprite.spawn("sh", ["-c", command], {
83
+ ...cwd && { cwd },
84
+ ...Object.keys(env).length > 0 && { env }
85
+ });
86
+ try {
87
+ await waitForSpawn(cmd);
88
+ } catch (error) {
89
+ cmd.close();
90
+ throw error;
91
+ }
92
+ if (options.stdinMode === "ignore") cmd.stdin.end();
93
+ const pid = `sprites-proc-${Date.now().toString(36)}-${(++this._spawnCounter).toString(36)}`;
94
+ const handle = new SpritesProcessHandle(pid, cmd, options, options.timeout ?? this.sandbox.defaultTimeout);
95
+ this._tracked.set(pid, handle);
96
+ return handle;
97
+ }
98
+ /**
99
+ * Lists processes spawned by this instance. The Sprites exec API has no
100
+ * listing for non-detachable commands, so processes started elsewhere are
101
+ * not included.
102
+ */
103
+ async list() {
104
+ return [...this._tracked.values()].map((handle) => ({
105
+ pid: handle.pid,
106
+ command: handle.command,
107
+ running: handle.exitCode === void 0,
108
+ ...handle.exitCode !== void 0 && { exitCode: handle.exitCode }
109
+ }));
110
+ }
111
+ /** Kill every running process spawned by this instance. Does not start the sandbox. */
112
+ async killAll() {
113
+ const running = [...this._tracked.values()].filter((handle) => handle.exitCode === void 0);
114
+ await Promise.all(running.map((handle) => this.kill(handle.pid)));
115
+ }
116
+ };
117
+ function waitForSpawn(cmd) {
118
+ return new Promise((resolve, reject) => {
119
+ const onSpawn = () => {
120
+ cmd.off("error", onError);
121
+ resolve();
122
+ };
123
+ const onError = (error) => {
124
+ cmd.off("spawn", onSpawn);
125
+ reject(error);
126
+ };
127
+ cmd.once("spawn", onSpawn);
128
+ cmd.once("error", onError);
129
+ });
130
+ }
131
+ function streamEnded(stream) {
132
+ return new Promise((resolve) => {
133
+ stream.once("end", () => resolve());
134
+ stream.once("close", () => resolve());
135
+ });
136
+ }
137
+ // src/sandbox/index.ts
138
+ /**
139
+ * Fly.io Sprites Sandbox Provider
140
+ *
141
+ * A Sprites sandbox implementation for Mastra workspaces. Gets or creates a
142
+ * persistent Fly.io Sprite by name and runs commands in it through the
143
+ * official `@fly/sprites` SDK. Sprites keep their filesystem between runs and
144
+ * hibernate on their own when idle.
145
+ *
146
+ * @see https://sprites.dev
147
+ */
148
+ var SpritesSandbox = class extends MastraSandbox {
149
+ id;
150
+ name = "SpritesSandbox";
151
+ provider = "sprites";
152
+ status = "pending";
153
+ _client = null;
154
+ _sprite = null;
155
+ _createdAt = null;
156
+ _token;
157
+ _baseURL;
158
+ _spriteConfig;
159
+ _timeout;
160
+ _instructionsOverride;
161
+ constructor(options = {}) {
162
+ super({
163
+ ...options,
164
+ name: "SpritesSandbox",
165
+ processes: new SpritesProcessManager()
166
+ });
167
+ this.id = options.id ?? `mastra-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
168
+ this._token = options.token ?? process.env.SPRITES_TOKEN;
169
+ this._baseURL = options.baseURL;
170
+ this._spriteConfig = options.spriteConfig;
171
+ this._timeout = options.timeout;
172
+ this._instructionsOverride = options.instructions;
173
+ }
174
+ /** The underlying SDK `Sprite`. Throws if the sandbox has not been started. */
175
+ get sprite() {
176
+ if (!this._sprite) throw new SandboxNotReadyError(this.id);
177
+ return this._sprite;
178
+ }
179
+ /** Default command timeout in milliseconds, if configured. */
180
+ get defaultTimeout() {
181
+ return this._timeout;
182
+ }
183
+ get client() {
184
+ if (!this._client) {
185
+ if (!this._token) throw new Error(`${LOG_PREFIX} Missing Sprites API token. Pass \`token\` or set the SPRITES_TOKEN environment variable.`);
186
+ this._client = new SpritesClient(this._token, this._baseURL ? { baseURL: this._baseURL } : void 0);
187
+ }
188
+ return this._client;
189
+ }
190
+ /**
191
+ * Get the Sprite named `id`, creating it when it does not exist.
192
+ * Reports `outcome: 'created'` only when a new Sprite was provisioned.
193
+ */
194
+ async start() {
195
+ if (this._sprite) return { outcome: "connected" };
196
+ const client = this.client;
197
+ let outcome = "connected";
198
+ let sprite;
199
+ try {
200
+ sprite = await client.getSprite(this.id);
201
+ } catch (error) {
202
+ if (!isStatus(error, 404)) throw error;
203
+ try {
204
+ sprite = await client.createSprite(this.id, this._spriteConfig);
205
+ outcome = "created";
206
+ } catch (createError) {
207
+ if (!isStatus(createError, 409)) throw createError;
208
+ sprite = await client.getSprite(this.id);
209
+ }
210
+ }
211
+ this._sprite = sprite;
212
+ this._createdAt = sprite.createdAt ?? /* @__PURE__ */ new Date();
213
+ this.logger.debug(`${LOG_PREFIX} Sprite ready`, {
214
+ id: this.id,
215
+ outcome
216
+ });
217
+ return { outcome };
218
+ }
219
+ /**
220
+ * Release local resources: kill background processes started by this
221
+ * instance and close the SDK control connection.
222
+ *
223
+ * The Sprite itself is NOT deleted or suspended. Sprites hibernate on their
224
+ * own when idle, and `start()` reconnects to the same filesystem.
225
+ */
226
+ async stop() {
227
+ await this._killTrackedProcesses();
228
+ this._sprite?.closeControlConnection();
229
+ this._sprite = null;
230
+ }
231
+ /**
232
+ * Permanently delete the Sprite and its filesystem. A Sprite that no longer
233
+ * exists is treated as already destroyed.
234
+ */
235
+ async destroy() {
236
+ await this._killTrackedProcesses();
237
+ const sprite = this._sprite ?? this.client.sprite(this.id);
238
+ sprite.closeControlConnection();
239
+ this._sprite = null;
240
+ try {
241
+ await sprite.delete();
242
+ } catch (error) {
243
+ if (!isStatus(error, 404)) throw error;
244
+ }
245
+ }
246
+ /**
247
+ * Capture a checkpoint of the Sprite's current state.
248
+ *
249
+ * Checkpoints live inside this Sprite only and cannot seed other sandboxes,
250
+ * so `supportsCheckpoints` stays `false`.
251
+ */
252
+ async snapshot() {
253
+ await this.ensureRunning();
254
+ await (await this.sprite.createCheckpoint("mastra snapshot")).processAll((message) => {
255
+ if (message.type === "error") throw new Error(`${LOG_PREFIX} Checkpoint failed: ${message.error ?? message.data ?? "unknown error"}`);
256
+ });
257
+ }
258
+ async _killTrackedProcesses() {
259
+ await this.processes.killAll().catch((error) => {
260
+ this.logger.warn(`${LOG_PREFIX} Failed to kill background processes`, { error });
261
+ });
262
+ }
263
+ async getInfo() {
264
+ const sprite = this._sprite;
265
+ return {
266
+ id: this.id,
267
+ name: this.name,
268
+ provider: this.provider,
269
+ status: this.status,
270
+ createdAt: this._createdAt ?? /* @__PURE__ */ new Date(),
271
+ metadata: { ...sprite && {
272
+ ...sprite.id && { spriteId: sprite.id },
273
+ ...sprite.status && { spriteStatus: sprite.status },
274
+ ...sprite.url && { url: sprite.url },
275
+ ...sprite.primaryRegion && { region: sprite.primaryRegion }
276
+ } }
277
+ };
278
+ }
279
+ getInstructions() {
280
+ const defaultInstructions = this._buildDefaultInstructions();
281
+ if (typeof this._instructionsOverride === "string") return this._instructionsOverride;
282
+ if (typeof this._instructionsOverride === "function") return this._instructionsOverride({ defaultInstructions });
283
+ return defaultInstructions;
284
+ }
285
+ _buildDefaultInstructions() {
286
+ const parts = ["Fly.io Sprite: a persistent Linux VM. Files written to disk survive between sessions.", this.workingDirectory ? `Commands run in ${this.workingDirectory} by default.` : "Commands run in the Sprite user home directory by default."];
287
+ if (this._timeout !== void 0) parts.push(`Default command timeout: ${Math.ceil(this._timeout / 1e3)}s.`);
288
+ return parts.join(" ");
289
+ }
290
+ };
291
+ function isStatus(error, statusCode) {
292
+ return error instanceof APIError && error.statusCode === statusCode;
293
+ }
294
+ // src/provider.ts
295
+ const spritesSandboxProvider = {
296
+ id: "sprites",
297
+ name: "Fly.io Sprites",
298
+ description: "Persistent Linux VM powered by Fly.io Sprites",
299
+ configSchema: {
300
+ type: "object",
301
+ properties: {
302
+ id: {
303
+ type: "string",
304
+ description: "Sprite name. An existing Sprite with this name is reused."
305
+ },
306
+ token: {
307
+ type: "string",
308
+ description: "Sprites API token (falls back to SPRITES_TOKEN)"
309
+ },
310
+ env: {
311
+ type: "object",
312
+ description: "Environment variables",
313
+ additionalProperties: { type: "string" }
314
+ },
315
+ timeout: {
316
+ type: "number",
317
+ description: "Default command timeout in ms"
318
+ },
319
+ workingDirectory: {
320
+ type: "string",
321
+ description: "Default working directory for commands"
322
+ }
323
+ }
324
+ },
325
+ createSandbox: ({ id, token, env, timeout, workingDirectory }) => new SpritesSandbox({
326
+ id,
327
+ token,
328
+ env,
329
+ timeout,
330
+ workingDirectory
331
+ })
332
+ };
333
+ export { SpritesProcessManager, SpritesSandbox, spritesSandboxProvider };
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Fly.io Sprites sandbox provider descriptor for MastraEditor.
3
+ *
4
+ * @example
5
+ * ```typescript
6
+ * import { spritesSandboxProvider } from '@mastra/sprites';
7
+ *
8
+ * const editor = new MastraEditor({
9
+ * sandboxes: { [spritesSandboxProvider.id]: spritesSandboxProvider },
10
+ * });
11
+ * ```
12
+ */
13
+ import type { SandboxProvider } from '@mastra/core/editor';
14
+ /**
15
+ * Serializable subset of SpritesSandboxOptions for editor storage.
16
+ *
17
+ * `baseURL` is deliberately excluded: the sandbox falls back to the server's
18
+ * SPRITES_TOKEN, so a stored API host could redirect that token elsewhere.
19
+ */
20
+ interface SpritesProviderConfig {
21
+ id?: string;
22
+ token?: string;
23
+ env?: Record<string, string>;
24
+ timeout?: number;
25
+ workingDirectory?: string;
26
+ }
27
+ export declare const spritesSandboxProvider: SandboxProvider<SpritesProviderConfig>;
28
+ export {};
29
+ //# sourceMappingURL=provider.d.ts.map
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Fly.io Sprites Sandbox Provider
3
+ *
4
+ * A Sprites sandbox implementation for Mastra workspaces. Gets or creates a
5
+ * persistent Fly.io Sprite by name and runs commands in it through the
6
+ * official `@fly/sprites` SDK. Sprites keep their filesystem between runs and
7
+ * hibernate on their own when idle.
8
+ *
9
+ * @see https://sprites.dev
10
+ */
11
+ import type { Sprite, SpriteConfig } from '@fly/sprites';
12
+ import type { InstructionsOption, MastraSandboxOptions, ProviderStatus, SandboxInfo, SandboxStartResult } from '@mastra/core/workspace';
13
+ import { MastraSandbox } from '@mastra/core/workspace';
14
+ import { SpritesProcessManager } from './process-manager.js';
15
+ export interface SpritesSandboxOptions extends Omit<MastraSandboxOptions, 'processes'> {
16
+ /**
17
+ * Sprite name, also used as the sandbox id. An existing Sprite with this
18
+ * name is reused (including its filesystem); otherwise one is created.
19
+ * Generated when omitted.
20
+ */
21
+ id?: string;
22
+ /** Sprites API token. Falls back to the `SPRITES_TOKEN` environment variable. */
23
+ token?: string;
24
+ /** Sprites API base URL. Defaults to the SDK default (`https://api.sprites.dev`). */
25
+ baseURL?: string;
26
+ /** Machine configuration applied only when the Sprite is created. */
27
+ spriteConfig?: SpriteConfig;
28
+ /** Default command timeout in milliseconds. Per-command `timeout` wins. */
29
+ timeout?: number;
30
+ /** Override or extend the default agent instructions for this sandbox. */
31
+ instructions?: InstructionsOption;
32
+ }
33
+ export declare class SpritesSandbox extends MastraSandbox {
34
+ readonly id: string;
35
+ readonly name = "SpritesSandbox";
36
+ readonly provider = "sprites";
37
+ status: ProviderStatus;
38
+ readonly processes: SpritesProcessManager;
39
+ private _client;
40
+ private _sprite;
41
+ private _createdAt;
42
+ private readonly _token?;
43
+ private readonly _baseURL?;
44
+ private readonly _spriteConfig?;
45
+ private readonly _timeout?;
46
+ private readonly _instructionsOverride?;
47
+ constructor(options?: SpritesSandboxOptions);
48
+ /** The underlying SDK `Sprite`. Throws if the sandbox has not been started. */
49
+ get sprite(): Sprite;
50
+ /** Default command timeout in milliseconds, if configured. */
51
+ get defaultTimeout(): number | undefined;
52
+ private get client();
53
+ /**
54
+ * Get the Sprite named `id`, creating it when it does not exist.
55
+ * Reports `outcome: 'created'` only when a new Sprite was provisioned.
56
+ */
57
+ start(): Promise<SandboxStartResult>;
58
+ /**
59
+ * Release local resources: kill background processes started by this
60
+ * instance and close the SDK control connection.
61
+ *
62
+ * The Sprite itself is NOT deleted or suspended. Sprites hibernate on their
63
+ * own when idle, and `start()` reconnects to the same filesystem.
64
+ */
65
+ stop(): Promise<void>;
66
+ /**
67
+ * Permanently delete the Sprite and its filesystem. A Sprite that no longer
68
+ * exists is treated as already destroyed.
69
+ */
70
+ destroy(): Promise<void>;
71
+ /**
72
+ * Capture a checkpoint of the Sprite's current state.
73
+ *
74
+ * Checkpoints live inside this Sprite only and cannot seed other sandboxes,
75
+ * so `supportsCheckpoints` stays `false`.
76
+ */
77
+ snapshot(): Promise<void>;
78
+ private _killTrackedProcesses;
79
+ getInfo(): Promise<SandboxInfo>;
80
+ getInstructions(): string;
81
+ private _buildDefaultInstructions;
82
+ }
83
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Sprites Process Manager
3
+ *
4
+ * Runs each spawned command as its own `SpriteCommand` (a WebSocket exec
5
+ * session on the Sprite) and streams stdout/stderr into the core
6
+ * `ProcessHandle` buffers as chunks arrive.
7
+ */
8
+ import type { ProcessInfo, SpawnProcessOptions } from '@mastra/core/workspace';
9
+ import { ProcessHandle, SandboxProcessManager } from '@mastra/core/workspace';
10
+ import type { SpritesSandbox } from './index.js';
11
+ export declare const LOG_PREFIX = "[SpritesSandbox]";
12
+ export declare class SpritesProcessManager extends SandboxProcessManager<SpritesSandbox> {
13
+ private _spawnCounter;
14
+ spawn(command: string, options?: SpawnProcessOptions): Promise<ProcessHandle>;
15
+ /**
16
+ * Lists processes spawned by this instance. The Sprites exec API has no
17
+ * listing for non-detachable commands, so processes started elsewhere are
18
+ * not included.
19
+ */
20
+ list(): Promise<ProcessInfo[]>;
21
+ /** Kill every running process spawned by this instance. Does not start the sandbox. */
22
+ killAll(): Promise<void>;
23
+ }
24
+ //# sourceMappingURL=process-manager.d.ts.map
package/package.json ADDED
@@ -0,0 +1,68 @@
1
+ {
2
+ "name": "@mastra/sprites",
3
+ "version": "0.0.0-agent-tags-alpha-20261125185303",
4
+ "description": "Fly.io Sprites sandbox provider for Mastra workspaces",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": {
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.js"
13
+ },
14
+ "require": {
15
+ "types": "./dist/index.d.ts",
16
+ "default": "./dist/index.cjs"
17
+ }
18
+ },
19
+ "./package.json": "./package.json"
20
+ },
21
+ "license": "Apache-2.0",
22
+ "dependencies": {
23
+ "@fly/sprites": "^0.2.4"
24
+ },
25
+ "devDependencies": {
26
+ "@types/node": "22.19.15",
27
+ "@vitest/coverage-v8": "5.1.0",
28
+ "@vitest/ui": "5.1.0",
29
+ "dotenv": "^18.0.9",
30
+ "tsdown": "0.23.1",
31
+ "typescript": "^7.0.2",
32
+ "vitest": "5.1.0",
33
+ "@internal/lint": "0.0.0-agent-tags-alpha-20261125185303",
34
+ "@internal/types-builder": "0.0.0-agent-tags-alpha-20261125185303",
35
+ "@internal/workspace-test-utils": "0.0.95",
36
+ "@mastra/core": "0.0.0-agent-tags-alpha-20261125185303"
37
+ },
38
+ "peerDependencies": {
39
+ "@mastra/core": "0.0.0-agent-tags-alpha-20261125185303"
40
+ },
41
+ "files": [
42
+ "dist",
43
+ "!dist/**/*.d.*ts.map"
44
+ ],
45
+ "homepage": "https://mastra.ai",
46
+ "repository": {
47
+ "type": "git",
48
+ "url": "git+https://github.com/mastra-ai/mastra.git",
49
+ "directory": "workspaces/sprites"
50
+ },
51
+ "bugs": {
52
+ "url": "https://github.com/mastra-ai/mastra/issues"
53
+ },
54
+ "engines": {
55
+ "node": ">=24.0.0"
56
+ },
57
+ "scripts": {
58
+ "build": "tsdown --silent --config tsdown.config.ts",
59
+ "build:lib": "pnpm build",
60
+ "build:watch": "pnpm build --watch",
61
+ "test:unit": "vitest run --exclude '**/*.integration.test.ts'",
62
+ "test:watch": "vitest watch",
63
+ "test": "vitest run ./src/**/*.integration.test.ts",
64
+ "test:cloud": "pnpm test",
65
+ "lint": "oxlint --type-aware .",
66
+ "lint:fix": "oxlint --type-aware --fix ."
67
+ }
68
+ }