@meistrari/sandbox-sdk 1.5.1 → 1.6.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/README.md CHANGED
@@ -213,20 +213,26 @@ const result = await sandbox.runCode(`
213
213
  await sandbox.kill()
214
214
  ```
215
215
 
216
- ### Selecting a Runtime
216
+ ### Selecting a Backend
217
217
 
218
218
  ```typescript
219
- // Pick the backend that runs the sandbox. Only 'lambda-microvm' is supported
220
- // today; omitting it uses the API's default runtime.
219
+ // `agent-sandbox`, `lambda-microvm` or `e2b`; omitting it uses the
220
+ // deployment's default. Naming one is a promise: the request is served by
221
+ // that backend or it fails.
221
222
  const run = await client.createRunAndWait({
222
223
  code: 'console.log("Hello")',
223
224
  language: 'typescript',
224
- runtime: 'lambda-microvm',
225
+ provider: 'lambda-microvm',
225
226
  })
226
227
 
227
- const sandbox = await client.createSandbox({ runtime: 'lambda-microvm' })
228
+ const sandbox = await client.createSandbox({ provider: 'lambda-microvm' })
228
229
  ```
229
230
 
231
+ `runtime` is the older name for the same setting and still works — it is
232
+ resolved to `provider` before the request goes out. Naming both to different
233
+ backends is refused rather than guessed. Prefer `provider`: it is what the API
234
+ reads, what a run reports back, and what `/health` lists.
235
+
230
236
  ### Streaming Output
231
237
 
232
238
  ```typescript
@@ -327,7 +333,8 @@ interface CreateRunRequest {
327
333
  timeoutMs?: number // ms (default: 300000)
328
334
  sandboxId?: string // Use existing sandbox
329
335
  persistent?: boolean // Keep sandbox after execution
330
- runtime?: SandboxRuntime // Sandbox backend (default: API's configured runtime)
336
+ provider?: string // Sandbox backend (default: the deployment's)
337
+ runtime?: SandboxRuntime // Older name for `provider`; resolved to it
331
338
  }
332
339
 
333
340
  interface RunCodeOptions {
package/dist/index.cjs CHANGED
@@ -186,6 +186,13 @@ class Sandbox {
186
186
  this.lastInfo = await this.client.resumeSandbox(this.sandboxId);
187
187
  return this.lastInfo;
188
188
  }
189
+ /**
190
+ * Builds a reusable, pre-warmed image from this sandbox. Unlike `suspend`,
191
+ * which checkpoints this one VM, the result can boot many sandboxes at once.
192
+ */
193
+ async createSnapshot(request) {
194
+ return await this.client.createSnapshot(this.sandboxId, request);
195
+ }
189
196
  async betaPause() {
190
197
  await this.suspend();
191
198
  }
@@ -259,6 +266,19 @@ function assertSupportedRuntime(runtime) {
259
266
  throw new Error(`Unsupported runtime "${runtime}". Supported runtimes: ${SANDBOX_RUNTIMES.join(", ")}`);
260
267
  }
261
268
  }
269
+ function withProvider(request) {
270
+ assertSupportedRuntime(request.runtime);
271
+ if (request.runtime === void 0) {
272
+ return request;
273
+ }
274
+ if (request.provider !== void 0 && request.provider !== request.runtime) {
275
+ throw new Error(
276
+ `Conflicting backends: runtime "${request.runtime}" and provider "${request.provider}". They are the same setting; name only one.`
277
+ );
278
+ }
279
+ const { runtime, ...rest } = request;
280
+ return { ...rest, provider: runtime };
281
+ }
262
282
  class SandboxClient {
263
283
  constructor(config) {
264
284
  __publicField(this, "apiUrl");
@@ -268,7 +288,7 @@ class SandboxClient {
268
288
  this.auth = config.auth;
269
289
  this.timeout = config.timeout ?? 3e5;
270
290
  }
271
- async fetch(path, options = {}) {
291
+ async fetch(path, options = {}, timeoutMs = this.timeout) {
272
292
  const url = `${this.apiUrl}${path}`;
273
293
  const headers = new Headers(options.headers);
274
294
  const authHeaders = this.auth.getHeaders();
@@ -276,18 +296,27 @@ class SandboxClient {
276
296
  headers.set(key, value);
277
297
  });
278
298
  headers.set("Content-Type", "application/json");
279
- const res = await fetch(url, { ...options, headers });
280
- if (!res.ok) {
281
- throw await FetchError.from(url, options.method ?? "GET", res);
299
+ const controller = new AbortController();
300
+ const abort = () => controller.abort(options.signal?.reason);
301
+ options.signal?.addEventListener("abort", abort, { once: true });
302
+ if (options.signal?.aborted)
303
+ abort();
304
+ const timer = setTimeout(() => controller.abort(new Error("Sandbox request timed out")), Math.max(1, Math.min(this.timeout, timeoutMs)));
305
+ try {
306
+ const res = await fetch(url, { ...options, headers, signal: controller.signal });
307
+ if (!res.ok)
308
+ throw await FetchError.from(url, options.method ?? "GET", res);
309
+ return await res.json();
310
+ } finally {
311
+ clearTimeout(timer);
312
+ options.signal?.removeEventListener("abort", abort);
282
313
  }
283
- return await res.json();
284
314
  }
285
315
  // === Runs ===
286
316
  async createRun(request) {
287
- assertSupportedRuntime(request.runtime);
288
317
  const response = await this.fetch("/api/runs", {
289
318
  method: "POST",
290
- body: JSON.stringify(request)
319
+ body: JSON.stringify(withProvider(request))
291
320
  });
292
321
  return new SandboxRun(this, response.data);
293
322
  }
@@ -296,7 +325,7 @@ class SandboxClient {
296
325
  return await run.waitForCompletion();
297
326
  }
298
327
  async *streamRun(request) {
299
- assertSupportedRuntime(request.runtime);
328
+ const resolved = withProvider(request);
300
329
  const url = `${this.apiUrl}/api/runs/stream`;
301
330
  const headers = new Headers();
302
331
  const authHeaders = this.auth.getHeaders();
@@ -307,7 +336,7 @@ class SandboxClient {
307
336
  const res = await fetch(url, {
308
337
  method: "POST",
309
338
  headers,
310
- body: JSON.stringify(request)
339
+ body: JSON.stringify(resolved)
311
340
  });
312
341
  if (!res.ok) {
313
342
  throw await FetchError.from(url, "POST", res);
@@ -406,10 +435,9 @@ class SandboxClient {
406
435
  }
407
436
  // === Sandboxes ===
408
437
  async createSandbox(request = {}) {
409
- assertSupportedRuntime(request.runtime);
410
438
  const response = await this.fetch("/api/sandboxes", {
411
439
  method: "POST",
412
- body: JSON.stringify(request)
440
+ body: JSON.stringify(withProvider(request))
413
441
  });
414
442
  return new Sandbox(this, response.data.sandboxId, this.auth, response.data);
415
443
  }
@@ -469,6 +497,63 @@ class SandboxClient {
469
497
  });
470
498
  return response.data;
471
499
  }
500
+ // === Snapshots ===
501
+ /**
502
+ * Asks the API to build a reusable, pre-warmed image from a running
503
+ * sandbox. The build is asynchronous: the answer is `building` and
504
+ * `waitForSnapshot` is how a caller learns when it can be restored.
505
+ */
506
+ async createSnapshot(sandboxId, request) {
507
+ const response = await this.fetch(`/api/sandboxes/${encodeURIComponent(sandboxId)}/snapshots`, {
508
+ method: "POST",
509
+ body: JSON.stringify(request)
510
+ });
511
+ return response.data;
512
+ }
513
+ async getSnapshot(snapshotId) {
514
+ return (await this.fetch(`/api/snapshots/${encodeURIComponent(snapshotId)}`)).data;
515
+ }
516
+ async listSnapshots() {
517
+ return (await this.fetch("/api/snapshots")).data;
518
+ }
519
+ async deleteSnapshot(snapshotId) {
520
+ return (await this.fetch(`/api/snapshots/${encodeURIComponent(snapshotId)}`, { method: "DELETE" })).data;
521
+ }
522
+ /**
523
+ * Polls until the snapshot is `ready`. Any other terminal state, the
524
+ * deadline (default one hour, the API's own build budget) or the caller's
525
+ * `signal` end the wait with an error.
526
+ */
527
+ async waitForSnapshot(snapshotId, options = {}) {
528
+ const deadline = Date.now() + (options.timeoutMs ?? 36e5);
529
+ if (!Number.isFinite(deadline) || !Number.isFinite(options.pollIntervalMs ?? 5e3))
530
+ throw new Error("Snapshot wait intervals must be finite");
531
+ for (; ; ) {
532
+ options.signal?.throwIfAborted();
533
+ if (Date.now() >= deadline)
534
+ throw new Error("Snapshot build wait timed out");
535
+ const snapshot = (await this.fetch(`/api/snapshots/${encodeURIComponent(snapshotId)}`, { signal: options.signal }, deadline - Date.now())).data;
536
+ if (snapshot.state === "ready")
537
+ return snapshot;
538
+ if (snapshot.state !== "building")
539
+ throw new Error(snapshot.errorMessage ?? `Snapshot is ${snapshot.state}`);
540
+ await new Promise((resolve, reject) => {
541
+ let timer;
542
+ const abort = () => {
543
+ clearTimeout(timer);
544
+ options.signal?.removeEventListener("abort", abort);
545
+ reject(options.signal?.reason);
546
+ };
547
+ timer = setTimeout(() => {
548
+ options.signal?.removeEventListener("abort", abort);
549
+ resolve();
550
+ }, Math.min(Math.max(options.pollIntervalMs ?? 5e3, 10), Math.max(0, deadline - Date.now())));
551
+ options.signal?.addEventListener("abort", abort, { once: true });
552
+ if (options.signal?.aborted)
553
+ abort();
554
+ });
555
+ }
556
+ }
472
557
  // === File Operations ===
473
558
  async writeFile(sandboxId, path, content) {
474
559
  const isBuffer = content instanceof Uint8Array;
package/dist/index.d.cts CHANGED
@@ -83,6 +83,7 @@ interface CreateRunRequest {
83
83
  };
84
84
  }
85
85
  interface CreateSandboxRequest {
86
+ snapshotId?: string;
86
87
  cpuSize?: number;
87
88
  memSize?: number;
88
89
  sandboxTtlSeconds?: number;
@@ -95,6 +96,32 @@ interface CreateSandboxRequest {
95
96
  /** Backend to host it; the deployment's default when omitted. */
96
97
  provider?: string;
97
98
  }
99
+ interface SnapshotRecipe {
100
+ paths: string[];
101
+ exclude?: string[];
102
+ startCommand: string;
103
+ readyFile: string;
104
+ workdir: string;
105
+ env?: Record<string, string>;
106
+ readyTimeoutSeconds?: number;
107
+ }
108
+ interface CreateSnapshotRequest {
109
+ name: string;
110
+ idempotencyKey: string;
111
+ recipe: SnapshotRecipe;
112
+ metadata?: Record<string, string>;
113
+ }
114
+ interface SnapshotInfo {
115
+ snapshotId: string;
116
+ name: string;
117
+ provider: string;
118
+ state: 'building' | 'ready' | 'failed' | 'deleting' | 'deleted';
119
+ sourceSandboxId: string;
120
+ memoryMib: number;
121
+ metadata: Record<string, string>;
122
+ errorMessage: string | null;
123
+ createdAt: string;
124
+ }
98
125
  type FileCategory = 'input' | 'skill' | 'settings' | 'context' | 'workspace' | 'output';
99
126
  interface FileInput {
100
127
  name: string;
@@ -212,6 +239,11 @@ declare class Sandbox {
212
239
  extend(ttlSeconds: number): Promise<SandboxInfo>;
213
240
  suspend(): Promise<SandboxInfo>;
214
241
  resume(): Promise<SandboxInfo>;
242
+ /**
243
+ * Builds a reusable, pre-warmed image from this sandbox. Unlike `suspend`,
244
+ * which checkpoints this one VM, the result can boot many sandboxes at once.
245
+ */
246
+ createSnapshot(request: CreateSnapshotRequest): Promise<SnapshotInfo>;
215
247
  betaPause(): Promise<void>;
216
248
  setTimeout(ms: number): void;
217
249
  }
@@ -259,6 +291,25 @@ declare class SandboxClient {
259
291
  extendSandbox(sandboxId: string, ttlSeconds: number): Promise<SandboxInfo>;
260
292
  suspendSandbox(sandboxId: string): Promise<SandboxInfo>;
261
293
  resumeSandbox(sandboxId: string): Promise<SandboxInfo>;
294
+ /**
295
+ * Asks the API to build a reusable, pre-warmed image from a running
296
+ * sandbox. The build is asynchronous: the answer is `building` and
297
+ * `waitForSnapshot` is how a caller learns when it can be restored.
298
+ */
299
+ createSnapshot(sandboxId: string, request: CreateSnapshotRequest): Promise<SnapshotInfo>;
300
+ getSnapshot(snapshotId: string): Promise<SnapshotInfo>;
301
+ listSnapshots(): Promise<SnapshotInfo[]>;
302
+ deleteSnapshot(snapshotId: string): Promise<SnapshotInfo>;
303
+ /**
304
+ * Polls until the snapshot is `ready`. Any other terminal state, the
305
+ * deadline (default one hour, the API's own build budget) or the caller's
306
+ * `signal` end the wait with an error.
307
+ */
308
+ waitForSnapshot(snapshotId: string, options?: {
309
+ timeoutMs?: number;
310
+ pollIntervalMs?: number;
311
+ signal?: AbortSignal;
312
+ }): Promise<SnapshotInfo>;
262
313
  writeFile(sandboxId: string, path: string, content: string | Uint8Array): Promise<void>;
263
314
  readFile(sandboxId: string, path: string, options?: FileReadOptions): Promise<string | Blob>;
264
315
  fileExists(sandboxId: string, path: string): Promise<boolean>;
@@ -369,4 +420,4 @@ declare function parseRunLifecycleEvent(raw: unknown): RunLifecycleEvent | null;
369
420
  declare function sandbox(config: SandboxConfig): SandboxClient;
370
421
 
371
422
  export { DataTokenAuthStrategy, FetchError, RUN_LIFECYCLE_EVENT_TYPES, RUN_LIFECYCLE_TERMINAL_TYPES, RUN_LIFECYCLE_TOPIC, SANDBOX_LIFECYCLE_EVENT_TYPES, SANDBOX_LIFECYCLE_ITEM, SANDBOX_LIFECYCLE_TOPIC, SANDBOX_RUNTIMES, Sandbox, SandboxClient, SandboxRun, isRunLifecycleEvent, isSandboxLifecycleEvent, lifecycleSchemaRegistryEnv, lifecycleSchemaSubject, lifecycleTopicEnv, parseRunLifecycleEvent, parseSandboxLifecycleEvent, runLifecycleTopicEnv, sandbox, sandboxLifecycleTopicEnv };
372
- export type { AuthStrategy, CreateRunRequest, CreateSandboxRequest, ExecCommandOptions, ExecCommandResult, ExecutionResult, FileInput, LifecycleTopic, ListSandboxesOptions, RunCodeOptions, RunLifecycleEvent, RunLifecycleEventType, RunLifecycleSource, RunResponse, SandboxCommands, SandboxConfig, SandboxFiles, SandboxInfo, SandboxLifecycleEvent, SandboxLifecycleEventType, SandboxLifecycleSource, SandboxOnTimeout, SandboxRuntime, SandboxState, Status, StreamCallbacks, StreamEvent };
423
+ export type { AuthStrategy, CreateRunRequest, CreateSandboxRequest, CreateSnapshotRequest, ExecCommandOptions, ExecCommandResult, ExecutionResult, FileInput, LifecycleTopic, ListSandboxesOptions, RunCodeOptions, RunLifecycleEvent, RunLifecycleEventType, RunLifecycleSource, RunResponse, SandboxCommands, SandboxConfig, SandboxFiles, SandboxInfo, SandboxLifecycleEvent, SandboxLifecycleEventType, SandboxLifecycleSource, SandboxOnTimeout, SandboxRuntime, SandboxState, SnapshotInfo, SnapshotRecipe, Status, StreamCallbacks, StreamEvent };
package/dist/index.d.mts CHANGED
@@ -83,6 +83,7 @@ interface CreateRunRequest {
83
83
  };
84
84
  }
85
85
  interface CreateSandboxRequest {
86
+ snapshotId?: string;
86
87
  cpuSize?: number;
87
88
  memSize?: number;
88
89
  sandboxTtlSeconds?: number;
@@ -95,6 +96,32 @@ interface CreateSandboxRequest {
95
96
  /** Backend to host it; the deployment's default when omitted. */
96
97
  provider?: string;
97
98
  }
99
+ interface SnapshotRecipe {
100
+ paths: string[];
101
+ exclude?: string[];
102
+ startCommand: string;
103
+ readyFile: string;
104
+ workdir: string;
105
+ env?: Record<string, string>;
106
+ readyTimeoutSeconds?: number;
107
+ }
108
+ interface CreateSnapshotRequest {
109
+ name: string;
110
+ idempotencyKey: string;
111
+ recipe: SnapshotRecipe;
112
+ metadata?: Record<string, string>;
113
+ }
114
+ interface SnapshotInfo {
115
+ snapshotId: string;
116
+ name: string;
117
+ provider: string;
118
+ state: 'building' | 'ready' | 'failed' | 'deleting' | 'deleted';
119
+ sourceSandboxId: string;
120
+ memoryMib: number;
121
+ metadata: Record<string, string>;
122
+ errorMessage: string | null;
123
+ createdAt: string;
124
+ }
98
125
  type FileCategory = 'input' | 'skill' | 'settings' | 'context' | 'workspace' | 'output';
99
126
  interface FileInput {
100
127
  name: string;
@@ -212,6 +239,11 @@ declare class Sandbox {
212
239
  extend(ttlSeconds: number): Promise<SandboxInfo>;
213
240
  suspend(): Promise<SandboxInfo>;
214
241
  resume(): Promise<SandboxInfo>;
242
+ /**
243
+ * Builds a reusable, pre-warmed image from this sandbox. Unlike `suspend`,
244
+ * which checkpoints this one VM, the result can boot many sandboxes at once.
245
+ */
246
+ createSnapshot(request: CreateSnapshotRequest): Promise<SnapshotInfo>;
215
247
  betaPause(): Promise<void>;
216
248
  setTimeout(ms: number): void;
217
249
  }
@@ -259,6 +291,25 @@ declare class SandboxClient {
259
291
  extendSandbox(sandboxId: string, ttlSeconds: number): Promise<SandboxInfo>;
260
292
  suspendSandbox(sandboxId: string): Promise<SandboxInfo>;
261
293
  resumeSandbox(sandboxId: string): Promise<SandboxInfo>;
294
+ /**
295
+ * Asks the API to build a reusable, pre-warmed image from a running
296
+ * sandbox. The build is asynchronous: the answer is `building` and
297
+ * `waitForSnapshot` is how a caller learns when it can be restored.
298
+ */
299
+ createSnapshot(sandboxId: string, request: CreateSnapshotRequest): Promise<SnapshotInfo>;
300
+ getSnapshot(snapshotId: string): Promise<SnapshotInfo>;
301
+ listSnapshots(): Promise<SnapshotInfo[]>;
302
+ deleteSnapshot(snapshotId: string): Promise<SnapshotInfo>;
303
+ /**
304
+ * Polls until the snapshot is `ready`. Any other terminal state, the
305
+ * deadline (default one hour, the API's own build budget) or the caller's
306
+ * `signal` end the wait with an error.
307
+ */
308
+ waitForSnapshot(snapshotId: string, options?: {
309
+ timeoutMs?: number;
310
+ pollIntervalMs?: number;
311
+ signal?: AbortSignal;
312
+ }): Promise<SnapshotInfo>;
262
313
  writeFile(sandboxId: string, path: string, content: string | Uint8Array): Promise<void>;
263
314
  readFile(sandboxId: string, path: string, options?: FileReadOptions): Promise<string | Blob>;
264
315
  fileExists(sandboxId: string, path: string): Promise<boolean>;
@@ -369,4 +420,4 @@ declare function parseRunLifecycleEvent(raw: unknown): RunLifecycleEvent | null;
369
420
  declare function sandbox(config: SandboxConfig): SandboxClient;
370
421
 
371
422
  export { DataTokenAuthStrategy, FetchError, RUN_LIFECYCLE_EVENT_TYPES, RUN_LIFECYCLE_TERMINAL_TYPES, RUN_LIFECYCLE_TOPIC, SANDBOX_LIFECYCLE_EVENT_TYPES, SANDBOX_LIFECYCLE_ITEM, SANDBOX_LIFECYCLE_TOPIC, SANDBOX_RUNTIMES, Sandbox, SandboxClient, SandboxRun, isRunLifecycleEvent, isSandboxLifecycleEvent, lifecycleSchemaRegistryEnv, lifecycleSchemaSubject, lifecycleTopicEnv, parseRunLifecycleEvent, parseSandboxLifecycleEvent, runLifecycleTopicEnv, sandbox, sandboxLifecycleTopicEnv };
372
- export type { AuthStrategy, CreateRunRequest, CreateSandboxRequest, ExecCommandOptions, ExecCommandResult, ExecutionResult, FileInput, LifecycleTopic, ListSandboxesOptions, RunCodeOptions, RunLifecycleEvent, RunLifecycleEventType, RunLifecycleSource, RunResponse, SandboxCommands, SandboxConfig, SandboxFiles, SandboxInfo, SandboxLifecycleEvent, SandboxLifecycleEventType, SandboxLifecycleSource, SandboxOnTimeout, SandboxRuntime, SandboxState, Status, StreamCallbacks, StreamEvent };
423
+ export type { AuthStrategy, CreateRunRequest, CreateSandboxRequest, CreateSnapshotRequest, ExecCommandOptions, ExecCommandResult, ExecutionResult, FileInput, LifecycleTopic, ListSandboxesOptions, RunCodeOptions, RunLifecycleEvent, RunLifecycleEventType, RunLifecycleSource, RunResponse, SandboxCommands, SandboxConfig, SandboxFiles, SandboxInfo, SandboxLifecycleEvent, SandboxLifecycleEventType, SandboxLifecycleSource, SandboxOnTimeout, SandboxRuntime, SandboxState, SnapshotInfo, SnapshotRecipe, Status, StreamCallbacks, StreamEvent };
package/dist/index.d.ts CHANGED
@@ -83,6 +83,7 @@ interface CreateRunRequest {
83
83
  };
84
84
  }
85
85
  interface CreateSandboxRequest {
86
+ snapshotId?: string;
86
87
  cpuSize?: number;
87
88
  memSize?: number;
88
89
  sandboxTtlSeconds?: number;
@@ -95,6 +96,32 @@ interface CreateSandboxRequest {
95
96
  /** Backend to host it; the deployment's default when omitted. */
96
97
  provider?: string;
97
98
  }
99
+ interface SnapshotRecipe {
100
+ paths: string[];
101
+ exclude?: string[];
102
+ startCommand: string;
103
+ readyFile: string;
104
+ workdir: string;
105
+ env?: Record<string, string>;
106
+ readyTimeoutSeconds?: number;
107
+ }
108
+ interface CreateSnapshotRequest {
109
+ name: string;
110
+ idempotencyKey: string;
111
+ recipe: SnapshotRecipe;
112
+ metadata?: Record<string, string>;
113
+ }
114
+ interface SnapshotInfo {
115
+ snapshotId: string;
116
+ name: string;
117
+ provider: string;
118
+ state: 'building' | 'ready' | 'failed' | 'deleting' | 'deleted';
119
+ sourceSandboxId: string;
120
+ memoryMib: number;
121
+ metadata: Record<string, string>;
122
+ errorMessage: string | null;
123
+ createdAt: string;
124
+ }
98
125
  type FileCategory = 'input' | 'skill' | 'settings' | 'context' | 'workspace' | 'output';
99
126
  interface FileInput {
100
127
  name: string;
@@ -212,6 +239,11 @@ declare class Sandbox {
212
239
  extend(ttlSeconds: number): Promise<SandboxInfo>;
213
240
  suspend(): Promise<SandboxInfo>;
214
241
  resume(): Promise<SandboxInfo>;
242
+ /**
243
+ * Builds a reusable, pre-warmed image from this sandbox. Unlike `suspend`,
244
+ * which checkpoints this one VM, the result can boot many sandboxes at once.
245
+ */
246
+ createSnapshot(request: CreateSnapshotRequest): Promise<SnapshotInfo>;
215
247
  betaPause(): Promise<void>;
216
248
  setTimeout(ms: number): void;
217
249
  }
@@ -259,6 +291,25 @@ declare class SandboxClient {
259
291
  extendSandbox(sandboxId: string, ttlSeconds: number): Promise<SandboxInfo>;
260
292
  suspendSandbox(sandboxId: string): Promise<SandboxInfo>;
261
293
  resumeSandbox(sandboxId: string): Promise<SandboxInfo>;
294
+ /**
295
+ * Asks the API to build a reusable, pre-warmed image from a running
296
+ * sandbox. The build is asynchronous: the answer is `building` and
297
+ * `waitForSnapshot` is how a caller learns when it can be restored.
298
+ */
299
+ createSnapshot(sandboxId: string, request: CreateSnapshotRequest): Promise<SnapshotInfo>;
300
+ getSnapshot(snapshotId: string): Promise<SnapshotInfo>;
301
+ listSnapshots(): Promise<SnapshotInfo[]>;
302
+ deleteSnapshot(snapshotId: string): Promise<SnapshotInfo>;
303
+ /**
304
+ * Polls until the snapshot is `ready`. Any other terminal state, the
305
+ * deadline (default one hour, the API's own build budget) or the caller's
306
+ * `signal` end the wait with an error.
307
+ */
308
+ waitForSnapshot(snapshotId: string, options?: {
309
+ timeoutMs?: number;
310
+ pollIntervalMs?: number;
311
+ signal?: AbortSignal;
312
+ }): Promise<SnapshotInfo>;
262
313
  writeFile(sandboxId: string, path: string, content: string | Uint8Array): Promise<void>;
263
314
  readFile(sandboxId: string, path: string, options?: FileReadOptions): Promise<string | Blob>;
264
315
  fileExists(sandboxId: string, path: string): Promise<boolean>;
@@ -369,4 +420,4 @@ declare function parseRunLifecycleEvent(raw: unknown): RunLifecycleEvent | null;
369
420
  declare function sandbox(config: SandboxConfig): SandboxClient;
370
421
 
371
422
  export { DataTokenAuthStrategy, FetchError, RUN_LIFECYCLE_EVENT_TYPES, RUN_LIFECYCLE_TERMINAL_TYPES, RUN_LIFECYCLE_TOPIC, SANDBOX_LIFECYCLE_EVENT_TYPES, SANDBOX_LIFECYCLE_ITEM, SANDBOX_LIFECYCLE_TOPIC, SANDBOX_RUNTIMES, Sandbox, SandboxClient, SandboxRun, isRunLifecycleEvent, isSandboxLifecycleEvent, lifecycleSchemaRegistryEnv, lifecycleSchemaSubject, lifecycleTopicEnv, parseRunLifecycleEvent, parseSandboxLifecycleEvent, runLifecycleTopicEnv, sandbox, sandboxLifecycleTopicEnv };
372
- export type { AuthStrategy, CreateRunRequest, CreateSandboxRequest, ExecCommandOptions, ExecCommandResult, ExecutionResult, FileInput, LifecycleTopic, ListSandboxesOptions, RunCodeOptions, RunLifecycleEvent, RunLifecycleEventType, RunLifecycleSource, RunResponse, SandboxCommands, SandboxConfig, SandboxFiles, SandboxInfo, SandboxLifecycleEvent, SandboxLifecycleEventType, SandboxLifecycleSource, SandboxOnTimeout, SandboxRuntime, SandboxState, Status, StreamCallbacks, StreamEvent };
423
+ export type { AuthStrategy, CreateRunRequest, CreateSandboxRequest, CreateSnapshotRequest, ExecCommandOptions, ExecCommandResult, ExecutionResult, FileInput, LifecycleTopic, ListSandboxesOptions, RunCodeOptions, RunLifecycleEvent, RunLifecycleEventType, RunLifecycleSource, RunResponse, SandboxCommands, SandboxConfig, SandboxFiles, SandboxInfo, SandboxLifecycleEvent, SandboxLifecycleEventType, SandboxLifecycleSource, SandboxOnTimeout, SandboxRuntime, SandboxState, SnapshotInfo, SnapshotRecipe, Status, StreamCallbacks, StreamEvent };
package/dist/index.mjs CHANGED
@@ -184,6 +184,13 @@ class Sandbox {
184
184
  this.lastInfo = await this.client.resumeSandbox(this.sandboxId);
185
185
  return this.lastInfo;
186
186
  }
187
+ /**
188
+ * Builds a reusable, pre-warmed image from this sandbox. Unlike `suspend`,
189
+ * which checkpoints this one VM, the result can boot many sandboxes at once.
190
+ */
191
+ async createSnapshot(request) {
192
+ return await this.client.createSnapshot(this.sandboxId, request);
193
+ }
187
194
  async betaPause() {
188
195
  await this.suspend();
189
196
  }
@@ -257,6 +264,19 @@ function assertSupportedRuntime(runtime) {
257
264
  throw new Error(`Unsupported runtime "${runtime}". Supported runtimes: ${SANDBOX_RUNTIMES.join(", ")}`);
258
265
  }
259
266
  }
267
+ function withProvider(request) {
268
+ assertSupportedRuntime(request.runtime);
269
+ if (request.runtime === void 0) {
270
+ return request;
271
+ }
272
+ if (request.provider !== void 0 && request.provider !== request.runtime) {
273
+ throw new Error(
274
+ `Conflicting backends: runtime "${request.runtime}" and provider "${request.provider}". They are the same setting; name only one.`
275
+ );
276
+ }
277
+ const { runtime, ...rest } = request;
278
+ return { ...rest, provider: runtime };
279
+ }
260
280
  class SandboxClient {
261
281
  constructor(config) {
262
282
  __publicField(this, "apiUrl");
@@ -266,7 +286,7 @@ class SandboxClient {
266
286
  this.auth = config.auth;
267
287
  this.timeout = config.timeout ?? 3e5;
268
288
  }
269
- async fetch(path, options = {}) {
289
+ async fetch(path, options = {}, timeoutMs = this.timeout) {
270
290
  const url = `${this.apiUrl}${path}`;
271
291
  const headers = new Headers(options.headers);
272
292
  const authHeaders = this.auth.getHeaders();
@@ -274,18 +294,27 @@ class SandboxClient {
274
294
  headers.set(key, value);
275
295
  });
276
296
  headers.set("Content-Type", "application/json");
277
- const res = await fetch(url, { ...options, headers });
278
- if (!res.ok) {
279
- throw await FetchError.from(url, options.method ?? "GET", res);
297
+ const controller = new AbortController();
298
+ const abort = () => controller.abort(options.signal?.reason);
299
+ options.signal?.addEventListener("abort", abort, { once: true });
300
+ if (options.signal?.aborted)
301
+ abort();
302
+ const timer = setTimeout(() => controller.abort(new Error("Sandbox request timed out")), Math.max(1, Math.min(this.timeout, timeoutMs)));
303
+ try {
304
+ const res = await fetch(url, { ...options, headers, signal: controller.signal });
305
+ if (!res.ok)
306
+ throw await FetchError.from(url, options.method ?? "GET", res);
307
+ return await res.json();
308
+ } finally {
309
+ clearTimeout(timer);
310
+ options.signal?.removeEventListener("abort", abort);
280
311
  }
281
- return await res.json();
282
312
  }
283
313
  // === Runs ===
284
314
  async createRun(request) {
285
- assertSupportedRuntime(request.runtime);
286
315
  const response = await this.fetch("/api/runs", {
287
316
  method: "POST",
288
- body: JSON.stringify(request)
317
+ body: JSON.stringify(withProvider(request))
289
318
  });
290
319
  return new SandboxRun(this, response.data);
291
320
  }
@@ -294,7 +323,7 @@ class SandboxClient {
294
323
  return await run.waitForCompletion();
295
324
  }
296
325
  async *streamRun(request) {
297
- assertSupportedRuntime(request.runtime);
326
+ const resolved = withProvider(request);
298
327
  const url = `${this.apiUrl}/api/runs/stream`;
299
328
  const headers = new Headers();
300
329
  const authHeaders = this.auth.getHeaders();
@@ -305,7 +334,7 @@ class SandboxClient {
305
334
  const res = await fetch(url, {
306
335
  method: "POST",
307
336
  headers,
308
- body: JSON.stringify(request)
337
+ body: JSON.stringify(resolved)
309
338
  });
310
339
  if (!res.ok) {
311
340
  throw await FetchError.from(url, "POST", res);
@@ -404,10 +433,9 @@ class SandboxClient {
404
433
  }
405
434
  // === Sandboxes ===
406
435
  async createSandbox(request = {}) {
407
- assertSupportedRuntime(request.runtime);
408
436
  const response = await this.fetch("/api/sandboxes", {
409
437
  method: "POST",
410
- body: JSON.stringify(request)
438
+ body: JSON.stringify(withProvider(request))
411
439
  });
412
440
  return new Sandbox(this, response.data.sandboxId, this.auth, response.data);
413
441
  }
@@ -467,6 +495,63 @@ class SandboxClient {
467
495
  });
468
496
  return response.data;
469
497
  }
498
+ // === Snapshots ===
499
+ /**
500
+ * Asks the API to build a reusable, pre-warmed image from a running
501
+ * sandbox. The build is asynchronous: the answer is `building` and
502
+ * `waitForSnapshot` is how a caller learns when it can be restored.
503
+ */
504
+ async createSnapshot(sandboxId, request) {
505
+ const response = await this.fetch(`/api/sandboxes/${encodeURIComponent(sandboxId)}/snapshots`, {
506
+ method: "POST",
507
+ body: JSON.stringify(request)
508
+ });
509
+ return response.data;
510
+ }
511
+ async getSnapshot(snapshotId) {
512
+ return (await this.fetch(`/api/snapshots/${encodeURIComponent(snapshotId)}`)).data;
513
+ }
514
+ async listSnapshots() {
515
+ return (await this.fetch("/api/snapshots")).data;
516
+ }
517
+ async deleteSnapshot(snapshotId) {
518
+ return (await this.fetch(`/api/snapshots/${encodeURIComponent(snapshotId)}`, { method: "DELETE" })).data;
519
+ }
520
+ /**
521
+ * Polls until the snapshot is `ready`. Any other terminal state, the
522
+ * deadline (default one hour, the API's own build budget) or the caller's
523
+ * `signal` end the wait with an error.
524
+ */
525
+ async waitForSnapshot(snapshotId, options = {}) {
526
+ const deadline = Date.now() + (options.timeoutMs ?? 36e5);
527
+ if (!Number.isFinite(deadline) || !Number.isFinite(options.pollIntervalMs ?? 5e3))
528
+ throw new Error("Snapshot wait intervals must be finite");
529
+ for (; ; ) {
530
+ options.signal?.throwIfAborted();
531
+ if (Date.now() >= deadline)
532
+ throw new Error("Snapshot build wait timed out");
533
+ const snapshot = (await this.fetch(`/api/snapshots/${encodeURIComponent(snapshotId)}`, { signal: options.signal }, deadline - Date.now())).data;
534
+ if (snapshot.state === "ready")
535
+ return snapshot;
536
+ if (snapshot.state !== "building")
537
+ throw new Error(snapshot.errorMessage ?? `Snapshot is ${snapshot.state}`);
538
+ await new Promise((resolve, reject) => {
539
+ let timer;
540
+ const abort = () => {
541
+ clearTimeout(timer);
542
+ options.signal?.removeEventListener("abort", abort);
543
+ reject(options.signal?.reason);
544
+ };
545
+ timer = setTimeout(() => {
546
+ options.signal?.removeEventListener("abort", abort);
547
+ resolve();
548
+ }, Math.min(Math.max(options.pollIntervalMs ?? 5e3, 10), Math.max(0, deadline - Date.now())));
549
+ options.signal?.addEventListener("abort", abort, { once: true });
550
+ if (options.signal?.aborted)
551
+ abort();
552
+ });
553
+ }
554
+ }
470
555
  // === File Operations ===
471
556
  async writeFile(sandboxId, path, content) {
472
557
  const isBuffer = content instanceof Uint8Array;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@meistrari/sandbox-sdk",
3
- "version": "1.5.1",
3
+ "version": "1.6.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -16,7 +16,8 @@
16
16
  ],
17
17
  "scripts": {
18
18
  "build": "unbuild",
19
- "test": "vitest"
19
+ "test": "bun test test",
20
+ "test:manual": "bun run test/manual/integration.ts"
20
21
  },
21
22
  "dependencies": {
22
23
  "eventsource-parser": "^3.0.0"