@meistrari/sandbox-sdk 1.5.2 → 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/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
  }
@@ -281,7 +288,7 @@ class SandboxClient {
281
288
  this.auth = config.auth;
282
289
  this.timeout = config.timeout ?? 3e5;
283
290
  }
284
- async fetch(path, options = {}) {
291
+ async fetch(path, options = {}, timeoutMs = this.timeout) {
285
292
  const url = `${this.apiUrl}${path}`;
286
293
  const headers = new Headers(options.headers);
287
294
  const authHeaders = this.auth.getHeaders();
@@ -289,11 +296,21 @@ class SandboxClient {
289
296
  headers.set(key, value);
290
297
  });
291
298
  headers.set("Content-Type", "application/json");
292
- const res = await fetch(url, { ...options, headers });
293
- if (!res.ok) {
294
- 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);
295
313
  }
296
- return await res.json();
297
314
  }
298
315
  // === Runs ===
299
316
  async createRun(request) {
@@ -480,6 +497,63 @@ class SandboxClient {
480
497
  });
481
498
  return response.data;
482
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
+ }
483
557
  // === File Operations ===
484
558
  async writeFile(sandboxId, path, content) {
485
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
  }
@@ -279,7 +286,7 @@ class SandboxClient {
279
286
  this.auth = config.auth;
280
287
  this.timeout = config.timeout ?? 3e5;
281
288
  }
282
- async fetch(path, options = {}) {
289
+ async fetch(path, options = {}, timeoutMs = this.timeout) {
283
290
  const url = `${this.apiUrl}${path}`;
284
291
  const headers = new Headers(options.headers);
285
292
  const authHeaders = this.auth.getHeaders();
@@ -287,11 +294,21 @@ class SandboxClient {
287
294
  headers.set(key, value);
288
295
  });
289
296
  headers.set("Content-Type", "application/json");
290
- const res = await fetch(url, { ...options, headers });
291
- if (!res.ok) {
292
- 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);
293
311
  }
294
- return await res.json();
295
312
  }
296
313
  // === Runs ===
297
314
  async createRun(request) {
@@ -478,6 +495,63 @@ class SandboxClient {
478
495
  });
479
496
  return response.data;
480
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
+ }
481
555
  // === File Operations ===
482
556
  async writeFile(sandboxId, path, content) {
483
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.2",
3
+ "version": "1.6.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {