@meistrari/sandbox-sdk 1.3.0 → 1.4.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
@@ -3,7 +3,7 @@
3
3
  const node_buffer = require('node:buffer');
4
4
  const eventsourceParser = require('eventsource-parser');
5
5
 
6
- const SANDBOX_RUNTIMES = ["lambda-microvm"];
6
+ const SANDBOX_RUNTIMES = ["lambda-microvm", "agent-sandbox", "e2b"];
7
7
 
8
8
  class FetchError extends Error {
9
9
  constructor(message, url, method, status, response) {
@@ -72,14 +72,16 @@ var __publicField$2 = (obj, key, value) => {
72
72
  return value;
73
73
  };
74
74
  class Sandbox {
75
- constructor(client, sandboxId, auth) {
75
+ constructor(client, sandboxId, auth, info) {
76
76
  this.client = client;
77
77
  this.auth = auth;
78
78
  __publicField$2(this, "sandboxId");
79
79
  __publicField$2(this, "files");
80
80
  __publicField$2(this, "commands");
81
81
  __publicField$2(this, "timeoutMs", 3e5);
82
+ __publicField$2(this, "lastInfo");
82
83
  this.sandboxId = sandboxId;
84
+ this.lastInfo = info;
83
85
  const readFile = async (path, options) => {
84
86
  return await this.client.readFile(sandboxId, path, options);
85
87
  };
@@ -92,16 +94,12 @@ class Sandbox {
92
94
  uploadBulk: async (files) => await this.client.uploadBulkFiles(sandboxId, files)
93
95
  };
94
96
  this.commands = {
95
- run: async (command) => {
96
- const result = await this.runCode(command, { language: "bash" });
97
- return {
98
- stdout: result.stdout,
99
- stderr: result.stderr,
100
- exitCode: result.exitCode
101
- };
102
- }
97
+ run: async (command, options) => await this.client.execCommand(sandboxId, command, options)
103
98
  };
104
99
  }
100
+ get info() {
101
+ return this.lastInfo;
102
+ }
105
103
  // Factory methods (static)
106
104
  static async create(client, options = {}) {
107
105
  return await client.createSandbox(options);
@@ -172,7 +170,24 @@ class Sandbox {
172
170
  }
173
171
  }
174
172
  }
173
+ async getInfo() {
174
+ this.lastInfo = await this.client.getSandbox(this.sandboxId);
175
+ return this.lastInfo;
176
+ }
177
+ async extend(ttlSeconds) {
178
+ this.lastInfo = await this.client.extendSandbox(this.sandboxId, ttlSeconds);
179
+ return this.lastInfo;
180
+ }
181
+ async suspend() {
182
+ this.lastInfo = await this.client.suspendSandbox(this.sandboxId);
183
+ return this.lastInfo;
184
+ }
185
+ async resume() {
186
+ this.lastInfo = await this.client.resumeSandbox(this.sandboxId);
187
+ return this.lastInfo;
188
+ }
175
189
  async betaPause() {
190
+ await this.suspend();
176
191
  }
177
192
  setTimeout(ms) {
178
193
  this.timeoutMs = ms;
@@ -396,24 +411,61 @@ class SandboxClient {
396
411
  method: "POST",
397
412
  body: JSON.stringify(request)
398
413
  });
399
- await pollUntilComplete(
400
- async () => await this.getSandboxStatus(response.data.sandboxId),
401
- { intervalMs: 200, maxAttempts: 150 }
402
- // 30s max
403
- );
404
- return new Sandbox(this, response.data.sandboxId, this.auth);
414
+ return new Sandbox(this, response.data.sandboxId, this.auth, response.data);
405
415
  }
406
- async getSandboxStatus(sandboxId) {
416
+ async getSandbox(sandboxId) {
407
417
  const response = await this.fetch(`/api/sandboxes/${sandboxId}`);
408
418
  return response.data;
409
419
  }
420
+ async getSandboxStatus(sandboxId) {
421
+ const { sandboxId: id, status } = await this.getSandbox(sandboxId);
422
+ return { sandboxId: id, status };
423
+ }
424
+ async listSandboxes(options = {}) {
425
+ const params = new URLSearchParams();
426
+ for (const [key, value] of Object.entries(options.metadata ?? {})) {
427
+ params.set(`metadata.${key}`, value);
428
+ }
429
+ if (options.states && options.states.length > 0) {
430
+ params.set("state", options.states.join(","));
431
+ }
432
+ const query = params.size > 0 ? `?${params.toString()}` : "";
433
+ const response = await this.fetch(`/api/sandboxes${query}`);
434
+ return response.data;
435
+ }
410
436
  async connectToSandbox(sandboxId) {
411
- await this.getSandboxStatus(sandboxId);
412
- return new Sandbox(this, sandboxId, this.auth);
437
+ const info = await this.getSandbox(sandboxId);
438
+ return new Sandbox(this, sandboxId, this.auth, info);
413
439
  }
414
440
  async deleteSandbox(sandboxId) {
415
441
  await this.fetch(`/api/sandboxes/${sandboxId}`, { method: "DELETE" });
416
442
  }
443
+ async execCommand(sandboxId, command, options = {}) {
444
+ const response = await this.fetch(`/api/sandboxes/${sandboxId}/exec`, {
445
+ method: "POST",
446
+ body: JSON.stringify({ command, ...options })
447
+ });
448
+ return response.data;
449
+ }
450
+ async extendSandbox(sandboxId, ttlSeconds) {
451
+ const response = await this.fetch(`/api/sandboxes/${sandboxId}/extend`, {
452
+ method: "POST",
453
+ body: JSON.stringify({ ttlSeconds })
454
+ });
455
+ return response.data;
456
+ }
457
+ async suspendSandbox(sandboxId) {
458
+ const response = await this.fetch(`/api/sandboxes/${sandboxId}/suspend`, {
459
+ method: "POST"
460
+ });
461
+ return response.data;
462
+ }
463
+ async resumeSandbox(sandboxId) {
464
+ const response = await this.fetch(`/api/sandboxes/${sandboxId}/resume`, {
465
+ method: "POST"
466
+ });
467
+ return response.data;
468
+ }
417
469
  // === File Operations ===
418
470
  async writeFile(sandboxId, path, content) {
419
471
  const isBuffer = content instanceof Uint8Array;
@@ -490,14 +542,54 @@ class DataTokenAuthStrategy {
490
542
  }
491
543
  }
492
544
 
545
+ const SANDBOX_LIFECYCLE_TOPIC = "sandbox-lifecycle";
546
+ const SANDBOX_LIFECYCLE_ITEM = "lifecycle";
547
+ const SANDBOX_LIFECYCLE_EVENT_TYPES = [
548
+ "created",
549
+ "ready",
550
+ "suspended",
551
+ "resumed",
552
+ "terminated",
553
+ "failed",
554
+ "expired"
555
+ ];
556
+ function sandboxLifecycleTopicEnv(binding = SANDBOX_LIFECYCLE_ITEM) {
557
+ return `KAFKA_${binding.toUpperCase().replaceAll("-", "_")}_TOPIC_${SANDBOX_LIFECYCLE_TOPIC.toUpperCase().replaceAll("-", "_")}`;
558
+ }
559
+ function isSandboxLifecycleEvent(value) {
560
+ if (typeof value !== "object" || value === null) {
561
+ return false;
562
+ }
563
+ const event = value;
564
+ return event.version === 1 && typeof event.eventId === "string" && SANDBOX_LIFECYCLE_EVENT_TYPES.includes(event.type) && typeof event.sandboxId === "string" && typeof event.workspaceId === "string" && typeof event.provider === "string" && typeof event.externalId === "string" && typeof event.state === "string" && typeof event.metadata === "object" && event.metadata !== null && typeof event.occurredAt === "string" && typeof event.source === "string";
565
+ }
566
+ function parseSandboxLifecycleEvent(raw) {
567
+ if (raw === null || raw === void 0) {
568
+ return null;
569
+ }
570
+ try {
571
+ const text = typeof raw === "string" ? raw : new TextDecoder().decode(raw);
572
+ const value = JSON.parse(text);
573
+ return isSandboxLifecycleEvent(value) ? value : null;
574
+ } catch {
575
+ return null;
576
+ }
577
+ }
578
+
493
579
  function sandbox(config) {
494
580
  return new SandboxClient(config);
495
581
  }
496
582
 
497
583
  exports.DataTokenAuthStrategy = DataTokenAuthStrategy;
498
584
  exports.FetchError = FetchError;
585
+ exports.SANDBOX_LIFECYCLE_EVENT_TYPES = SANDBOX_LIFECYCLE_EVENT_TYPES;
586
+ exports.SANDBOX_LIFECYCLE_ITEM = SANDBOX_LIFECYCLE_ITEM;
587
+ exports.SANDBOX_LIFECYCLE_TOPIC = SANDBOX_LIFECYCLE_TOPIC;
499
588
  exports.SANDBOX_RUNTIMES = SANDBOX_RUNTIMES;
500
589
  exports.Sandbox = Sandbox;
501
590
  exports.SandboxClient = SandboxClient;
502
591
  exports.SandboxRun = SandboxRun;
592
+ exports.isSandboxLifecycleEvent = isSandboxLifecycleEvent;
593
+ exports.parseSandboxLifecycleEvent = parseSandboxLifecycleEvent;
503
594
  exports.sandbox = sandbox;
595
+ exports.sandboxLifecycleTopicEnv = sandboxLifecycleTopicEnv;
package/dist/index.d.cts CHANGED
@@ -6,8 +6,41 @@ interface SandboxConfig {
6
6
  interface AuthStrategy {
7
7
  getHeaders: () => Headers;
8
8
  }
9
- declare const SANDBOX_RUNTIMES: readonly ["lambda-microvm"];
9
+ declare const SANDBOX_RUNTIMES: readonly ["lambda-microvm", "agent-sandbox", "e2b"];
10
10
  type SandboxRuntime = (typeof SANDBOX_RUNTIMES)[number];
11
+ type SandboxState = 'pending' | 'running' | 'suspended' | 'terminated' | 'failed';
12
+ type SandboxOnTimeout = 'suspend' | 'terminate';
13
+ interface SandboxInfo {
14
+ sandboxId: string;
15
+ status: Status;
16
+ provider: string;
17
+ externalId: string;
18
+ state: SandboxState;
19
+ image?: string;
20
+ metadata: Record<string, string>;
21
+ memSize: number;
22
+ cpuSize: number;
23
+ persistent: boolean;
24
+ createdAt: string;
25
+ lastUsedAt: string;
26
+ expiresAt?: string;
27
+ errorMessage?: string;
28
+ }
29
+ interface ListSandboxesOptions {
30
+ metadata?: Record<string, string>;
31
+ states?: SandboxState[];
32
+ }
33
+ interface ExecCommandOptions {
34
+ cwd?: string;
35
+ env?: Record<string, string>;
36
+ timeoutMs?: number;
37
+ user?: string;
38
+ }
39
+ interface ExecCommandResult {
40
+ stdout: string;
41
+ stderr: string;
42
+ exitCode: number;
43
+ }
11
44
  interface CreateRunRequest {
12
45
  code: string;
13
46
  language?: 'javascript' | 'typescript' | 'python' | 'bash' | 'ts' | 'js';
@@ -28,6 +61,10 @@ interface CreateSandboxRequest {
28
61
  sandboxTtlSeconds?: number;
29
62
  files?: FileInput[];
30
63
  runtime?: SandboxRuntime;
64
+ image?: string;
65
+ env?: Record<string, string>;
66
+ metadata?: Record<string, string>;
67
+ onTimeout?: SandboxOnTimeout;
31
68
  }
32
69
  type FileCategory = 'input' | 'skill' | 'settings' | 'context' | 'workspace' | 'output';
33
70
  interface FileInput {
@@ -118,7 +155,7 @@ interface SandboxFiles {
118
155
  uploadBulk: (files: BulkFileInput[]) => Promise<BulkUploadResult>;
119
156
  }
120
157
  interface SandboxCommands {
121
- run: (command: string) => Promise<{
158
+ run: (command: string, options?: ExecCommandOptions) => Promise<{
122
159
  stdout: string;
123
160
  stderr: string;
124
161
  exitCode?: number;
@@ -132,22 +169,18 @@ declare class Sandbox {
132
169
  readonly files: SandboxFiles;
133
170
  readonly commands: SandboxCommands;
134
171
  private timeoutMs;
135
- constructor(client: SandboxClient, sandboxId: string, auth: AuthStrategy);
136
- static create(client: SandboxClient, options?: {
137
- memSize?: number;
138
- cpuSize?: number;
139
- runtime?: SandboxRuntime;
140
- files?: Array<{
141
- name: string;
142
- content: string;
143
- encoding: 'utf8' | 'base64';
144
- path?: string;
145
- }>;
146
- }): Promise<Sandbox>;
172
+ private lastInfo?;
173
+ constructor(client: SandboxClient, sandboxId: string, auth: AuthStrategy, info?: SandboxInfo);
174
+ get info(): SandboxInfo | undefined;
175
+ static create(client: SandboxClient, options?: CreateSandboxRequest): Promise<Sandbox>;
147
176
  static connect(client: SandboxClient, sandboxId: string): Promise<Sandbox>;
148
177
  private normalizeLanguage;
149
178
  runCode(script: string, options?: RunCodeOptions): Promise<ExecutionResult>;
150
179
  kill(): Promise<void>;
180
+ getInfo(): Promise<SandboxInfo>;
181
+ extend(ttlSeconds: number): Promise<SandboxInfo>;
182
+ suspend(): Promise<SandboxInfo>;
183
+ resume(): Promise<SandboxInfo>;
151
184
  betaPause(): Promise<void>;
152
185
  setTimeout(ms: number): void;
153
186
  }
@@ -183,12 +216,18 @@ declare class SandboxClient {
183
216
  streamRun(request: CreateRunRequest): AsyncGenerator<StreamEvent>;
184
217
  getRun(runId: string): Promise<SandboxRun>;
185
218
  createSandbox(request?: CreateSandboxRequest): Promise<Sandbox>;
219
+ getSandbox(sandboxId: string): Promise<SandboxInfo>;
186
220
  getSandboxStatus(sandboxId: string): Promise<{
187
221
  sandboxId: string;
188
222
  status: Status;
189
223
  }>;
224
+ listSandboxes(options?: ListSandboxesOptions): Promise<SandboxInfo[]>;
190
225
  connectToSandbox(sandboxId: string): Promise<Sandbox>;
191
226
  deleteSandbox(sandboxId: string): Promise<void>;
227
+ execCommand(sandboxId: string, command: string, options?: ExecCommandOptions): Promise<ExecCommandResult>;
228
+ extendSandbox(sandboxId: string, ttlSeconds: number): Promise<SandboxInfo>;
229
+ suspendSandbox(sandboxId: string): Promise<SandboxInfo>;
230
+ resumeSandbox(sandboxId: string): Promise<SandboxInfo>;
192
231
  writeFile(sandboxId: string, path: string, content: string | Uint8Array): Promise<void>;
193
232
  readFile(sandboxId: string, path: string, options?: FileReadOptions): Promise<string | Blob>;
194
233
  fileExists(sandboxId: string, path: string): Promise<boolean>;
@@ -212,7 +251,34 @@ declare class FetchError extends Error {
212
251
  static from(url: string, method: string, res: Response): Promise<FetchError>;
213
252
  }
214
253
 
254
+ declare const SANDBOX_LIFECYCLE_TOPIC = "sandbox-lifecycle";
255
+ declare const SANDBOX_LIFECYCLE_ITEM = "lifecycle";
256
+ declare const SANDBOX_LIFECYCLE_EVENT_TYPES: readonly ["created", "ready", "suspended", "resumed", "terminated", "failed", "expired"];
257
+ type SandboxLifecycleEventType = (typeof SANDBOX_LIFECYCLE_EVENT_TYPES)[number];
258
+ type SandboxLifecycleSource = 'api' | 'provider-webhook' | 'provider-watch';
259
+ /**
260
+ * One sandbox transition, delivered at-least-once on the `sandbox-lifecycle`
261
+ * topic keyed by `sandboxId`. Consumers dedupe by `eventId`.
262
+ */
263
+ interface SandboxLifecycleEvent {
264
+ version: 1;
265
+ eventId: string;
266
+ type: SandboxLifecycleEventType;
267
+ sandboxId: string;
268
+ workspaceId: string;
269
+ provider: string;
270
+ externalId: string;
271
+ image?: string;
272
+ state: SandboxState;
273
+ metadata: Record<string, string>;
274
+ occurredAt: string;
275
+ source: SandboxLifecycleSource;
276
+ }
277
+ declare function sandboxLifecycleTopicEnv(binding?: string): string;
278
+ declare function isSandboxLifecycleEvent(value: unknown): value is SandboxLifecycleEvent;
279
+ declare function parseSandboxLifecycleEvent(raw: string | Uint8Array | null | undefined): SandboxLifecycleEvent | null;
280
+
215
281
  declare function sandbox(config: SandboxConfig): SandboxClient;
216
282
 
217
- export { DataTokenAuthStrategy, FetchError, SANDBOX_RUNTIMES, Sandbox, SandboxClient, SandboxRun, sandbox };
218
- export type { AuthStrategy, CreateRunRequest, CreateSandboxRequest, ExecutionResult, FileInput, RunCodeOptions, RunResponse, SandboxCommands, SandboxConfig, SandboxFiles, SandboxRuntime, Status, StreamCallbacks, StreamEvent };
283
+ export { DataTokenAuthStrategy, FetchError, SANDBOX_LIFECYCLE_EVENT_TYPES, SANDBOX_LIFECYCLE_ITEM, SANDBOX_LIFECYCLE_TOPIC, SANDBOX_RUNTIMES, Sandbox, SandboxClient, SandboxRun, isSandboxLifecycleEvent, parseSandboxLifecycleEvent, sandbox, sandboxLifecycleTopicEnv };
284
+ export type { AuthStrategy, CreateRunRequest, CreateSandboxRequest, ExecCommandOptions, ExecCommandResult, ExecutionResult, FileInput, ListSandboxesOptions, RunCodeOptions, RunResponse, SandboxCommands, SandboxConfig, SandboxFiles, SandboxInfo, SandboxLifecycleEvent, SandboxLifecycleEventType, SandboxLifecycleSource, SandboxOnTimeout, SandboxRuntime, SandboxState, Status, StreamCallbacks, StreamEvent };
package/dist/index.d.mts CHANGED
@@ -6,8 +6,41 @@ interface SandboxConfig {
6
6
  interface AuthStrategy {
7
7
  getHeaders: () => Headers;
8
8
  }
9
- declare const SANDBOX_RUNTIMES: readonly ["lambda-microvm"];
9
+ declare const SANDBOX_RUNTIMES: readonly ["lambda-microvm", "agent-sandbox", "e2b"];
10
10
  type SandboxRuntime = (typeof SANDBOX_RUNTIMES)[number];
11
+ type SandboxState = 'pending' | 'running' | 'suspended' | 'terminated' | 'failed';
12
+ type SandboxOnTimeout = 'suspend' | 'terminate';
13
+ interface SandboxInfo {
14
+ sandboxId: string;
15
+ status: Status;
16
+ provider: string;
17
+ externalId: string;
18
+ state: SandboxState;
19
+ image?: string;
20
+ metadata: Record<string, string>;
21
+ memSize: number;
22
+ cpuSize: number;
23
+ persistent: boolean;
24
+ createdAt: string;
25
+ lastUsedAt: string;
26
+ expiresAt?: string;
27
+ errorMessage?: string;
28
+ }
29
+ interface ListSandboxesOptions {
30
+ metadata?: Record<string, string>;
31
+ states?: SandboxState[];
32
+ }
33
+ interface ExecCommandOptions {
34
+ cwd?: string;
35
+ env?: Record<string, string>;
36
+ timeoutMs?: number;
37
+ user?: string;
38
+ }
39
+ interface ExecCommandResult {
40
+ stdout: string;
41
+ stderr: string;
42
+ exitCode: number;
43
+ }
11
44
  interface CreateRunRequest {
12
45
  code: string;
13
46
  language?: 'javascript' | 'typescript' | 'python' | 'bash' | 'ts' | 'js';
@@ -28,6 +61,10 @@ interface CreateSandboxRequest {
28
61
  sandboxTtlSeconds?: number;
29
62
  files?: FileInput[];
30
63
  runtime?: SandboxRuntime;
64
+ image?: string;
65
+ env?: Record<string, string>;
66
+ metadata?: Record<string, string>;
67
+ onTimeout?: SandboxOnTimeout;
31
68
  }
32
69
  type FileCategory = 'input' | 'skill' | 'settings' | 'context' | 'workspace' | 'output';
33
70
  interface FileInput {
@@ -118,7 +155,7 @@ interface SandboxFiles {
118
155
  uploadBulk: (files: BulkFileInput[]) => Promise<BulkUploadResult>;
119
156
  }
120
157
  interface SandboxCommands {
121
- run: (command: string) => Promise<{
158
+ run: (command: string, options?: ExecCommandOptions) => Promise<{
122
159
  stdout: string;
123
160
  stderr: string;
124
161
  exitCode?: number;
@@ -132,22 +169,18 @@ declare class Sandbox {
132
169
  readonly files: SandboxFiles;
133
170
  readonly commands: SandboxCommands;
134
171
  private timeoutMs;
135
- constructor(client: SandboxClient, sandboxId: string, auth: AuthStrategy);
136
- static create(client: SandboxClient, options?: {
137
- memSize?: number;
138
- cpuSize?: number;
139
- runtime?: SandboxRuntime;
140
- files?: Array<{
141
- name: string;
142
- content: string;
143
- encoding: 'utf8' | 'base64';
144
- path?: string;
145
- }>;
146
- }): Promise<Sandbox>;
172
+ private lastInfo?;
173
+ constructor(client: SandboxClient, sandboxId: string, auth: AuthStrategy, info?: SandboxInfo);
174
+ get info(): SandboxInfo | undefined;
175
+ static create(client: SandboxClient, options?: CreateSandboxRequest): Promise<Sandbox>;
147
176
  static connect(client: SandboxClient, sandboxId: string): Promise<Sandbox>;
148
177
  private normalizeLanguage;
149
178
  runCode(script: string, options?: RunCodeOptions): Promise<ExecutionResult>;
150
179
  kill(): Promise<void>;
180
+ getInfo(): Promise<SandboxInfo>;
181
+ extend(ttlSeconds: number): Promise<SandboxInfo>;
182
+ suspend(): Promise<SandboxInfo>;
183
+ resume(): Promise<SandboxInfo>;
151
184
  betaPause(): Promise<void>;
152
185
  setTimeout(ms: number): void;
153
186
  }
@@ -183,12 +216,18 @@ declare class SandboxClient {
183
216
  streamRun(request: CreateRunRequest): AsyncGenerator<StreamEvent>;
184
217
  getRun(runId: string): Promise<SandboxRun>;
185
218
  createSandbox(request?: CreateSandboxRequest): Promise<Sandbox>;
219
+ getSandbox(sandboxId: string): Promise<SandboxInfo>;
186
220
  getSandboxStatus(sandboxId: string): Promise<{
187
221
  sandboxId: string;
188
222
  status: Status;
189
223
  }>;
224
+ listSandboxes(options?: ListSandboxesOptions): Promise<SandboxInfo[]>;
190
225
  connectToSandbox(sandboxId: string): Promise<Sandbox>;
191
226
  deleteSandbox(sandboxId: string): Promise<void>;
227
+ execCommand(sandboxId: string, command: string, options?: ExecCommandOptions): Promise<ExecCommandResult>;
228
+ extendSandbox(sandboxId: string, ttlSeconds: number): Promise<SandboxInfo>;
229
+ suspendSandbox(sandboxId: string): Promise<SandboxInfo>;
230
+ resumeSandbox(sandboxId: string): Promise<SandboxInfo>;
192
231
  writeFile(sandboxId: string, path: string, content: string | Uint8Array): Promise<void>;
193
232
  readFile(sandboxId: string, path: string, options?: FileReadOptions): Promise<string | Blob>;
194
233
  fileExists(sandboxId: string, path: string): Promise<boolean>;
@@ -212,7 +251,34 @@ declare class FetchError extends Error {
212
251
  static from(url: string, method: string, res: Response): Promise<FetchError>;
213
252
  }
214
253
 
254
+ declare const SANDBOX_LIFECYCLE_TOPIC = "sandbox-lifecycle";
255
+ declare const SANDBOX_LIFECYCLE_ITEM = "lifecycle";
256
+ declare const SANDBOX_LIFECYCLE_EVENT_TYPES: readonly ["created", "ready", "suspended", "resumed", "terminated", "failed", "expired"];
257
+ type SandboxLifecycleEventType = (typeof SANDBOX_LIFECYCLE_EVENT_TYPES)[number];
258
+ type SandboxLifecycleSource = 'api' | 'provider-webhook' | 'provider-watch';
259
+ /**
260
+ * One sandbox transition, delivered at-least-once on the `sandbox-lifecycle`
261
+ * topic keyed by `sandboxId`. Consumers dedupe by `eventId`.
262
+ */
263
+ interface SandboxLifecycleEvent {
264
+ version: 1;
265
+ eventId: string;
266
+ type: SandboxLifecycleEventType;
267
+ sandboxId: string;
268
+ workspaceId: string;
269
+ provider: string;
270
+ externalId: string;
271
+ image?: string;
272
+ state: SandboxState;
273
+ metadata: Record<string, string>;
274
+ occurredAt: string;
275
+ source: SandboxLifecycleSource;
276
+ }
277
+ declare function sandboxLifecycleTopicEnv(binding?: string): string;
278
+ declare function isSandboxLifecycleEvent(value: unknown): value is SandboxLifecycleEvent;
279
+ declare function parseSandboxLifecycleEvent(raw: string | Uint8Array | null | undefined): SandboxLifecycleEvent | null;
280
+
215
281
  declare function sandbox(config: SandboxConfig): SandboxClient;
216
282
 
217
- export { DataTokenAuthStrategy, FetchError, SANDBOX_RUNTIMES, Sandbox, SandboxClient, SandboxRun, sandbox };
218
- export type { AuthStrategy, CreateRunRequest, CreateSandboxRequest, ExecutionResult, FileInput, RunCodeOptions, RunResponse, SandboxCommands, SandboxConfig, SandboxFiles, SandboxRuntime, Status, StreamCallbacks, StreamEvent };
283
+ export { DataTokenAuthStrategy, FetchError, SANDBOX_LIFECYCLE_EVENT_TYPES, SANDBOX_LIFECYCLE_ITEM, SANDBOX_LIFECYCLE_TOPIC, SANDBOX_RUNTIMES, Sandbox, SandboxClient, SandboxRun, isSandboxLifecycleEvent, parseSandboxLifecycleEvent, sandbox, sandboxLifecycleTopicEnv };
284
+ export type { AuthStrategy, CreateRunRequest, CreateSandboxRequest, ExecCommandOptions, ExecCommandResult, ExecutionResult, FileInput, ListSandboxesOptions, RunCodeOptions, RunResponse, SandboxCommands, SandboxConfig, SandboxFiles, SandboxInfo, SandboxLifecycleEvent, SandboxLifecycleEventType, SandboxLifecycleSource, SandboxOnTimeout, SandboxRuntime, SandboxState, Status, StreamCallbacks, StreamEvent };
package/dist/index.d.ts CHANGED
@@ -6,8 +6,41 @@ interface SandboxConfig {
6
6
  interface AuthStrategy {
7
7
  getHeaders: () => Headers;
8
8
  }
9
- declare const SANDBOX_RUNTIMES: readonly ["lambda-microvm"];
9
+ declare const SANDBOX_RUNTIMES: readonly ["lambda-microvm", "agent-sandbox", "e2b"];
10
10
  type SandboxRuntime = (typeof SANDBOX_RUNTIMES)[number];
11
+ type SandboxState = 'pending' | 'running' | 'suspended' | 'terminated' | 'failed';
12
+ type SandboxOnTimeout = 'suspend' | 'terminate';
13
+ interface SandboxInfo {
14
+ sandboxId: string;
15
+ status: Status;
16
+ provider: string;
17
+ externalId: string;
18
+ state: SandboxState;
19
+ image?: string;
20
+ metadata: Record<string, string>;
21
+ memSize: number;
22
+ cpuSize: number;
23
+ persistent: boolean;
24
+ createdAt: string;
25
+ lastUsedAt: string;
26
+ expiresAt?: string;
27
+ errorMessage?: string;
28
+ }
29
+ interface ListSandboxesOptions {
30
+ metadata?: Record<string, string>;
31
+ states?: SandboxState[];
32
+ }
33
+ interface ExecCommandOptions {
34
+ cwd?: string;
35
+ env?: Record<string, string>;
36
+ timeoutMs?: number;
37
+ user?: string;
38
+ }
39
+ interface ExecCommandResult {
40
+ stdout: string;
41
+ stderr: string;
42
+ exitCode: number;
43
+ }
11
44
  interface CreateRunRequest {
12
45
  code: string;
13
46
  language?: 'javascript' | 'typescript' | 'python' | 'bash' | 'ts' | 'js';
@@ -28,6 +61,10 @@ interface CreateSandboxRequest {
28
61
  sandboxTtlSeconds?: number;
29
62
  files?: FileInput[];
30
63
  runtime?: SandboxRuntime;
64
+ image?: string;
65
+ env?: Record<string, string>;
66
+ metadata?: Record<string, string>;
67
+ onTimeout?: SandboxOnTimeout;
31
68
  }
32
69
  type FileCategory = 'input' | 'skill' | 'settings' | 'context' | 'workspace' | 'output';
33
70
  interface FileInput {
@@ -118,7 +155,7 @@ interface SandboxFiles {
118
155
  uploadBulk: (files: BulkFileInput[]) => Promise<BulkUploadResult>;
119
156
  }
120
157
  interface SandboxCommands {
121
- run: (command: string) => Promise<{
158
+ run: (command: string, options?: ExecCommandOptions) => Promise<{
122
159
  stdout: string;
123
160
  stderr: string;
124
161
  exitCode?: number;
@@ -132,22 +169,18 @@ declare class Sandbox {
132
169
  readonly files: SandboxFiles;
133
170
  readonly commands: SandboxCommands;
134
171
  private timeoutMs;
135
- constructor(client: SandboxClient, sandboxId: string, auth: AuthStrategy);
136
- static create(client: SandboxClient, options?: {
137
- memSize?: number;
138
- cpuSize?: number;
139
- runtime?: SandboxRuntime;
140
- files?: Array<{
141
- name: string;
142
- content: string;
143
- encoding: 'utf8' | 'base64';
144
- path?: string;
145
- }>;
146
- }): Promise<Sandbox>;
172
+ private lastInfo?;
173
+ constructor(client: SandboxClient, sandboxId: string, auth: AuthStrategy, info?: SandboxInfo);
174
+ get info(): SandboxInfo | undefined;
175
+ static create(client: SandboxClient, options?: CreateSandboxRequest): Promise<Sandbox>;
147
176
  static connect(client: SandboxClient, sandboxId: string): Promise<Sandbox>;
148
177
  private normalizeLanguage;
149
178
  runCode(script: string, options?: RunCodeOptions): Promise<ExecutionResult>;
150
179
  kill(): Promise<void>;
180
+ getInfo(): Promise<SandboxInfo>;
181
+ extend(ttlSeconds: number): Promise<SandboxInfo>;
182
+ suspend(): Promise<SandboxInfo>;
183
+ resume(): Promise<SandboxInfo>;
151
184
  betaPause(): Promise<void>;
152
185
  setTimeout(ms: number): void;
153
186
  }
@@ -183,12 +216,18 @@ declare class SandboxClient {
183
216
  streamRun(request: CreateRunRequest): AsyncGenerator<StreamEvent>;
184
217
  getRun(runId: string): Promise<SandboxRun>;
185
218
  createSandbox(request?: CreateSandboxRequest): Promise<Sandbox>;
219
+ getSandbox(sandboxId: string): Promise<SandboxInfo>;
186
220
  getSandboxStatus(sandboxId: string): Promise<{
187
221
  sandboxId: string;
188
222
  status: Status;
189
223
  }>;
224
+ listSandboxes(options?: ListSandboxesOptions): Promise<SandboxInfo[]>;
190
225
  connectToSandbox(sandboxId: string): Promise<Sandbox>;
191
226
  deleteSandbox(sandboxId: string): Promise<void>;
227
+ execCommand(sandboxId: string, command: string, options?: ExecCommandOptions): Promise<ExecCommandResult>;
228
+ extendSandbox(sandboxId: string, ttlSeconds: number): Promise<SandboxInfo>;
229
+ suspendSandbox(sandboxId: string): Promise<SandboxInfo>;
230
+ resumeSandbox(sandboxId: string): Promise<SandboxInfo>;
192
231
  writeFile(sandboxId: string, path: string, content: string | Uint8Array): Promise<void>;
193
232
  readFile(sandboxId: string, path: string, options?: FileReadOptions): Promise<string | Blob>;
194
233
  fileExists(sandboxId: string, path: string): Promise<boolean>;
@@ -212,7 +251,34 @@ declare class FetchError extends Error {
212
251
  static from(url: string, method: string, res: Response): Promise<FetchError>;
213
252
  }
214
253
 
254
+ declare const SANDBOX_LIFECYCLE_TOPIC = "sandbox-lifecycle";
255
+ declare const SANDBOX_LIFECYCLE_ITEM = "lifecycle";
256
+ declare const SANDBOX_LIFECYCLE_EVENT_TYPES: readonly ["created", "ready", "suspended", "resumed", "terminated", "failed", "expired"];
257
+ type SandboxLifecycleEventType = (typeof SANDBOX_LIFECYCLE_EVENT_TYPES)[number];
258
+ type SandboxLifecycleSource = 'api' | 'provider-webhook' | 'provider-watch';
259
+ /**
260
+ * One sandbox transition, delivered at-least-once on the `sandbox-lifecycle`
261
+ * topic keyed by `sandboxId`. Consumers dedupe by `eventId`.
262
+ */
263
+ interface SandboxLifecycleEvent {
264
+ version: 1;
265
+ eventId: string;
266
+ type: SandboxLifecycleEventType;
267
+ sandboxId: string;
268
+ workspaceId: string;
269
+ provider: string;
270
+ externalId: string;
271
+ image?: string;
272
+ state: SandboxState;
273
+ metadata: Record<string, string>;
274
+ occurredAt: string;
275
+ source: SandboxLifecycleSource;
276
+ }
277
+ declare function sandboxLifecycleTopicEnv(binding?: string): string;
278
+ declare function isSandboxLifecycleEvent(value: unknown): value is SandboxLifecycleEvent;
279
+ declare function parseSandboxLifecycleEvent(raw: string | Uint8Array | null | undefined): SandboxLifecycleEvent | null;
280
+
215
281
  declare function sandbox(config: SandboxConfig): SandboxClient;
216
282
 
217
- export { DataTokenAuthStrategy, FetchError, SANDBOX_RUNTIMES, Sandbox, SandboxClient, SandboxRun, sandbox };
218
- export type { AuthStrategy, CreateRunRequest, CreateSandboxRequest, ExecutionResult, FileInput, RunCodeOptions, RunResponse, SandboxCommands, SandboxConfig, SandboxFiles, SandboxRuntime, Status, StreamCallbacks, StreamEvent };
283
+ export { DataTokenAuthStrategy, FetchError, SANDBOX_LIFECYCLE_EVENT_TYPES, SANDBOX_LIFECYCLE_ITEM, SANDBOX_LIFECYCLE_TOPIC, SANDBOX_RUNTIMES, Sandbox, SandboxClient, SandboxRun, isSandboxLifecycleEvent, parseSandboxLifecycleEvent, sandbox, sandboxLifecycleTopicEnv };
284
+ export type { AuthStrategy, CreateRunRequest, CreateSandboxRequest, ExecCommandOptions, ExecCommandResult, ExecutionResult, FileInput, ListSandboxesOptions, RunCodeOptions, RunResponse, SandboxCommands, SandboxConfig, SandboxFiles, SandboxInfo, SandboxLifecycleEvent, SandboxLifecycleEventType, SandboxLifecycleSource, SandboxOnTimeout, SandboxRuntime, SandboxState, Status, StreamCallbacks, StreamEvent };
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Buffer } from 'node:buffer';
2
2
  import { createParser } from 'eventsource-parser';
3
3
 
4
- const SANDBOX_RUNTIMES = ["lambda-microvm"];
4
+ const SANDBOX_RUNTIMES = ["lambda-microvm", "agent-sandbox", "e2b"];
5
5
 
6
6
  class FetchError extends Error {
7
7
  constructor(message, url, method, status, response) {
@@ -70,14 +70,16 @@ var __publicField$2 = (obj, key, value) => {
70
70
  return value;
71
71
  };
72
72
  class Sandbox {
73
- constructor(client, sandboxId, auth) {
73
+ constructor(client, sandboxId, auth, info) {
74
74
  this.client = client;
75
75
  this.auth = auth;
76
76
  __publicField$2(this, "sandboxId");
77
77
  __publicField$2(this, "files");
78
78
  __publicField$2(this, "commands");
79
79
  __publicField$2(this, "timeoutMs", 3e5);
80
+ __publicField$2(this, "lastInfo");
80
81
  this.sandboxId = sandboxId;
82
+ this.lastInfo = info;
81
83
  const readFile = async (path, options) => {
82
84
  return await this.client.readFile(sandboxId, path, options);
83
85
  };
@@ -90,16 +92,12 @@ class Sandbox {
90
92
  uploadBulk: async (files) => await this.client.uploadBulkFiles(sandboxId, files)
91
93
  };
92
94
  this.commands = {
93
- run: async (command) => {
94
- const result = await this.runCode(command, { language: "bash" });
95
- return {
96
- stdout: result.stdout,
97
- stderr: result.stderr,
98
- exitCode: result.exitCode
99
- };
100
- }
95
+ run: async (command, options) => await this.client.execCommand(sandboxId, command, options)
101
96
  };
102
97
  }
98
+ get info() {
99
+ return this.lastInfo;
100
+ }
103
101
  // Factory methods (static)
104
102
  static async create(client, options = {}) {
105
103
  return await client.createSandbox(options);
@@ -170,7 +168,24 @@ class Sandbox {
170
168
  }
171
169
  }
172
170
  }
171
+ async getInfo() {
172
+ this.lastInfo = await this.client.getSandbox(this.sandboxId);
173
+ return this.lastInfo;
174
+ }
175
+ async extend(ttlSeconds) {
176
+ this.lastInfo = await this.client.extendSandbox(this.sandboxId, ttlSeconds);
177
+ return this.lastInfo;
178
+ }
179
+ async suspend() {
180
+ this.lastInfo = await this.client.suspendSandbox(this.sandboxId);
181
+ return this.lastInfo;
182
+ }
183
+ async resume() {
184
+ this.lastInfo = await this.client.resumeSandbox(this.sandboxId);
185
+ return this.lastInfo;
186
+ }
173
187
  async betaPause() {
188
+ await this.suspend();
174
189
  }
175
190
  setTimeout(ms) {
176
191
  this.timeoutMs = ms;
@@ -394,24 +409,61 @@ class SandboxClient {
394
409
  method: "POST",
395
410
  body: JSON.stringify(request)
396
411
  });
397
- await pollUntilComplete(
398
- async () => await this.getSandboxStatus(response.data.sandboxId),
399
- { intervalMs: 200, maxAttempts: 150 }
400
- // 30s max
401
- );
402
- return new Sandbox(this, response.data.sandboxId, this.auth);
412
+ return new Sandbox(this, response.data.sandboxId, this.auth, response.data);
403
413
  }
404
- async getSandboxStatus(sandboxId) {
414
+ async getSandbox(sandboxId) {
405
415
  const response = await this.fetch(`/api/sandboxes/${sandboxId}`);
406
416
  return response.data;
407
417
  }
418
+ async getSandboxStatus(sandboxId) {
419
+ const { sandboxId: id, status } = await this.getSandbox(sandboxId);
420
+ return { sandboxId: id, status };
421
+ }
422
+ async listSandboxes(options = {}) {
423
+ const params = new URLSearchParams();
424
+ for (const [key, value] of Object.entries(options.metadata ?? {})) {
425
+ params.set(`metadata.${key}`, value);
426
+ }
427
+ if (options.states && options.states.length > 0) {
428
+ params.set("state", options.states.join(","));
429
+ }
430
+ const query = params.size > 0 ? `?${params.toString()}` : "";
431
+ const response = await this.fetch(`/api/sandboxes${query}`);
432
+ return response.data;
433
+ }
408
434
  async connectToSandbox(sandboxId) {
409
- await this.getSandboxStatus(sandboxId);
410
- return new Sandbox(this, sandboxId, this.auth);
435
+ const info = await this.getSandbox(sandboxId);
436
+ return new Sandbox(this, sandboxId, this.auth, info);
411
437
  }
412
438
  async deleteSandbox(sandboxId) {
413
439
  await this.fetch(`/api/sandboxes/${sandboxId}`, { method: "DELETE" });
414
440
  }
441
+ async execCommand(sandboxId, command, options = {}) {
442
+ const response = await this.fetch(`/api/sandboxes/${sandboxId}/exec`, {
443
+ method: "POST",
444
+ body: JSON.stringify({ command, ...options })
445
+ });
446
+ return response.data;
447
+ }
448
+ async extendSandbox(sandboxId, ttlSeconds) {
449
+ const response = await this.fetch(`/api/sandboxes/${sandboxId}/extend`, {
450
+ method: "POST",
451
+ body: JSON.stringify({ ttlSeconds })
452
+ });
453
+ return response.data;
454
+ }
455
+ async suspendSandbox(sandboxId) {
456
+ const response = await this.fetch(`/api/sandboxes/${sandboxId}/suspend`, {
457
+ method: "POST"
458
+ });
459
+ return response.data;
460
+ }
461
+ async resumeSandbox(sandboxId) {
462
+ const response = await this.fetch(`/api/sandboxes/${sandboxId}/resume`, {
463
+ method: "POST"
464
+ });
465
+ return response.data;
466
+ }
415
467
  // === File Operations ===
416
468
  async writeFile(sandboxId, path, content) {
417
469
  const isBuffer = content instanceof Uint8Array;
@@ -488,8 +540,42 @@ class DataTokenAuthStrategy {
488
540
  }
489
541
  }
490
542
 
543
+ const SANDBOX_LIFECYCLE_TOPIC = "sandbox-lifecycle";
544
+ const SANDBOX_LIFECYCLE_ITEM = "lifecycle";
545
+ const SANDBOX_LIFECYCLE_EVENT_TYPES = [
546
+ "created",
547
+ "ready",
548
+ "suspended",
549
+ "resumed",
550
+ "terminated",
551
+ "failed",
552
+ "expired"
553
+ ];
554
+ function sandboxLifecycleTopicEnv(binding = SANDBOX_LIFECYCLE_ITEM) {
555
+ return `KAFKA_${binding.toUpperCase().replaceAll("-", "_")}_TOPIC_${SANDBOX_LIFECYCLE_TOPIC.toUpperCase().replaceAll("-", "_")}`;
556
+ }
557
+ function isSandboxLifecycleEvent(value) {
558
+ if (typeof value !== "object" || value === null) {
559
+ return false;
560
+ }
561
+ const event = value;
562
+ return event.version === 1 && typeof event.eventId === "string" && SANDBOX_LIFECYCLE_EVENT_TYPES.includes(event.type) && typeof event.sandboxId === "string" && typeof event.workspaceId === "string" && typeof event.provider === "string" && typeof event.externalId === "string" && typeof event.state === "string" && typeof event.metadata === "object" && event.metadata !== null && typeof event.occurredAt === "string" && typeof event.source === "string";
563
+ }
564
+ function parseSandboxLifecycleEvent(raw) {
565
+ if (raw === null || raw === void 0) {
566
+ return null;
567
+ }
568
+ try {
569
+ const text = typeof raw === "string" ? raw : new TextDecoder().decode(raw);
570
+ const value = JSON.parse(text);
571
+ return isSandboxLifecycleEvent(value) ? value : null;
572
+ } catch {
573
+ return null;
574
+ }
575
+ }
576
+
491
577
  function sandbox(config) {
492
578
  return new SandboxClient(config);
493
579
  }
494
580
 
495
- export { DataTokenAuthStrategy, FetchError, SANDBOX_RUNTIMES, Sandbox, SandboxClient, SandboxRun, sandbox };
581
+ export { DataTokenAuthStrategy, FetchError, SANDBOX_LIFECYCLE_EVENT_TYPES, SANDBOX_LIFECYCLE_ITEM, SANDBOX_LIFECYCLE_TOPIC, SANDBOX_RUNTIMES, Sandbox, SandboxClient, SandboxRun, isSandboxLifecycleEvent, parseSandboxLifecycleEvent, sandbox, sandboxLifecycleTopicEnv };
package/package.json CHANGED
@@ -1,29 +1,29 @@
1
1
  {
2
- "name": "@meistrari/sandbox-sdk",
3
- "version": "1.3.0",
4
- "type": "module",
5
- "exports": {
6
- ".": {
7
- "types": "./dist/index.d.ts",
8
- "import": "./dist/index.mjs",
9
- "require": "./dist/index.cjs"
2
+ "name": "@meistrari/sandbox-sdk",
3
+ "version": "1.4.0",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": {
7
+ "types": "./dist/index.d.ts",
8
+ "import": "./dist/index.mjs",
9
+ "require": "./dist/index.cjs"
10
+ }
11
+ },
12
+ "main": "dist/index.mjs",
13
+ "types": "dist/index.d.ts",
14
+ "files": [
15
+ "dist"
16
+ ],
17
+ "scripts": {
18
+ "build": "unbuild",
19
+ "test": "vitest"
20
+ },
21
+ "dependencies": {
22
+ "eventsource-parser": "^3.0.0"
23
+ },
24
+ "devDependencies": {
25
+ "unbuild": "^2.0.0",
26
+ "vitest": "^2.0.0",
27
+ "typescript": "^5.0.0"
10
28
  }
11
- },
12
- "main": "dist/index.mjs",
13
- "types": "dist/index.d.ts",
14
- "files": [
15
- "dist"
16
- ],
17
- "scripts": {
18
- "build": "unbuild",
19
- "test": "vitest"
20
- },
21
- "dependencies": {
22
- "eventsource-parser": "^3.0.0"
23
- },
24
- "devDependencies": {
25
- "unbuild": "^2.0.0",
26
- "vitest": "^2.0.0",
27
- "typescript": "^5.0.0"
28
- }
29
29
  }