@meistrari/sandbox-sdk 1.3.0 → 1.5.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,64 @@ 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
+ if (options.provider) {
433
+ params.set("provider", options.provider);
434
+ }
435
+ const query = params.size > 0 ? `?${params.toString()}` : "";
436
+ const response = await this.fetch(`/api/sandboxes${query}`);
437
+ return response.data;
438
+ }
410
439
  async connectToSandbox(sandboxId) {
411
- await this.getSandboxStatus(sandboxId);
412
- return new Sandbox(this, sandboxId, this.auth);
440
+ const info = await this.getSandbox(sandboxId);
441
+ return new Sandbox(this, sandboxId, this.auth, info);
413
442
  }
414
443
  async deleteSandbox(sandboxId) {
415
444
  await this.fetch(`/api/sandboxes/${sandboxId}`, { method: "DELETE" });
416
445
  }
446
+ async execCommand(sandboxId, command, options = {}) {
447
+ const response = await this.fetch(`/api/sandboxes/${sandboxId}/exec`, {
448
+ method: "POST",
449
+ body: JSON.stringify({ command, ...options })
450
+ });
451
+ return response.data;
452
+ }
453
+ async extendSandbox(sandboxId, ttlSeconds) {
454
+ const response = await this.fetch(`/api/sandboxes/${sandboxId}/extend`, {
455
+ method: "POST",
456
+ body: JSON.stringify({ ttlSeconds })
457
+ });
458
+ return response.data;
459
+ }
460
+ async suspendSandbox(sandboxId) {
461
+ const response = await this.fetch(`/api/sandboxes/${sandboxId}/suspend`, {
462
+ method: "POST"
463
+ });
464
+ return response.data;
465
+ }
466
+ async resumeSandbox(sandboxId) {
467
+ const response = await this.fetch(`/api/sandboxes/${sandboxId}/resume`, {
468
+ method: "POST"
469
+ });
470
+ return response.data;
471
+ }
417
472
  // === File Operations ===
418
473
  async writeFile(sandboxId, path, content) {
419
474
  const isBuffer = content instanceof Uint8Array;
@@ -490,14 +545,108 @@ class DataTokenAuthStrategy {
490
545
  }
491
546
  }
492
547
 
548
+ const SANDBOX_LIFECYCLE_TOPIC = "sandbox-lifecycle";
549
+ const RUN_LIFECYCLE_TOPIC = "run-lifecycle";
550
+ const SANDBOX_LIFECYCLE_ITEM = "lifecycle";
551
+ const SANDBOX_LIFECYCLE_EVENT_TYPES = [
552
+ "created",
553
+ "ready",
554
+ "suspended",
555
+ "resumed",
556
+ "terminated",
557
+ "failed",
558
+ "expired"
559
+ ];
560
+ const RUN_LIFECYCLE_EVENT_TYPES = [
561
+ "created",
562
+ "started",
563
+ "completed",
564
+ "failed",
565
+ "timeout",
566
+ "cancelled"
567
+ ];
568
+ const RUN_LIFECYCLE_TERMINAL_TYPES = ["completed", "failed", "timeout", "cancelled"];
569
+ function envSegment(value) {
570
+ return value.toUpperCase().replaceAll("-", "_");
571
+ }
572
+ function lifecycleTopicEnv(topic, binding = SANDBOX_LIFECYCLE_ITEM) {
573
+ return `KAFKA_${envSegment(binding)}_TOPIC_${envSegment(topic)}`;
574
+ }
575
+ function sandboxLifecycleTopicEnv(binding = SANDBOX_LIFECYCLE_ITEM) {
576
+ return lifecycleTopicEnv(SANDBOX_LIFECYCLE_TOPIC, binding);
577
+ }
578
+ function runLifecycleTopicEnv(binding = SANDBOX_LIFECYCLE_ITEM) {
579
+ return lifecycleTopicEnv(RUN_LIFECYCLE_TOPIC, binding);
580
+ }
581
+ function lifecycleSchemaRegistryEnv(binding = SANDBOX_LIFECYCLE_ITEM) {
582
+ return `KAFKA_${envSegment(binding)}_SCHEMA_REGISTRY_URL`;
583
+ }
584
+ function lifecycleSchemaSubject(topic) {
585
+ return `${topic}-value`;
586
+ }
587
+ function isRecord(value) {
588
+ return typeof value === "object" && value !== null;
589
+ }
590
+ function isOptionalString(value) {
591
+ return value === void 0 || value === null || typeof value === "string";
592
+ }
593
+ function isSandboxLifecycleEvent(value) {
594
+ if (!isRecord(value)) {
595
+ return false;
596
+ }
597
+ return value.version === 1 && typeof value.eventId === "string" && SANDBOX_LIFECYCLE_EVENT_TYPES.includes(value.type) && typeof value.sandboxId === "string" && typeof value.workspaceId === "string" && typeof value.provider === "string" && typeof value.externalId === "string" && isOptionalString(value.image) && typeof value.state === "string" && isRecord(value.metadata) && typeof value.occurredAt === "string" && typeof value.source === "string";
598
+ }
599
+ function isRunLifecycleEvent(value) {
600
+ if (!isRecord(value)) {
601
+ return false;
602
+ }
603
+ return value.version === 1 && typeof value.eventId === "string" && RUN_LIFECYCLE_EVENT_TYPES.includes(value.type) && typeof value.runId === "string" && typeof value.workspaceId === "string" && isOptionalString(value.sandboxId) && isOptionalString(value.provider) && typeof value.language === "string" && typeof value.status === "string" && typeof value.occurredAt === "string" && typeof value.source === "string";
604
+ }
605
+ function parseSandboxLifecycleEvent(raw) {
606
+ const value = decoded(raw);
607
+ return isSandboxLifecycleEvent(value) ? value : null;
608
+ }
609
+ function parseRunLifecycleEvent(raw) {
610
+ const value = decoded(raw);
611
+ return isRunLifecycleEvent(value) ? value : null;
612
+ }
613
+ function decoded(raw) {
614
+ if (raw === null || raw === void 0) {
615
+ return null;
616
+ }
617
+ if (typeof raw === "string") {
618
+ try {
619
+ return JSON.parse(raw);
620
+ } catch {
621
+ return null;
622
+ }
623
+ }
624
+ return raw;
625
+ }
626
+
493
627
  function sandbox(config) {
494
628
  return new SandboxClient(config);
495
629
  }
496
630
 
497
631
  exports.DataTokenAuthStrategy = DataTokenAuthStrategy;
498
632
  exports.FetchError = FetchError;
633
+ exports.RUN_LIFECYCLE_EVENT_TYPES = RUN_LIFECYCLE_EVENT_TYPES;
634
+ exports.RUN_LIFECYCLE_TERMINAL_TYPES = RUN_LIFECYCLE_TERMINAL_TYPES;
635
+ exports.RUN_LIFECYCLE_TOPIC = RUN_LIFECYCLE_TOPIC;
636
+ exports.SANDBOX_LIFECYCLE_EVENT_TYPES = SANDBOX_LIFECYCLE_EVENT_TYPES;
637
+ exports.SANDBOX_LIFECYCLE_ITEM = SANDBOX_LIFECYCLE_ITEM;
638
+ exports.SANDBOX_LIFECYCLE_TOPIC = SANDBOX_LIFECYCLE_TOPIC;
499
639
  exports.SANDBOX_RUNTIMES = SANDBOX_RUNTIMES;
500
640
  exports.Sandbox = Sandbox;
501
641
  exports.SandboxClient = SandboxClient;
502
642
  exports.SandboxRun = SandboxRun;
643
+ exports.isRunLifecycleEvent = isRunLifecycleEvent;
644
+ exports.isSandboxLifecycleEvent = isSandboxLifecycleEvent;
645
+ exports.lifecycleSchemaRegistryEnv = lifecycleSchemaRegistryEnv;
646
+ exports.lifecycleSchemaSubject = lifecycleSchemaSubject;
647
+ exports.lifecycleTopicEnv = lifecycleTopicEnv;
648
+ exports.parseRunLifecycleEvent = parseRunLifecycleEvent;
649
+ exports.parseSandboxLifecycleEvent = parseSandboxLifecycleEvent;
650
+ exports.runLifecycleTopicEnv = runLifecycleTopicEnv;
503
651
  exports.sandbox = sandbox;
652
+ exports.sandboxLifecycleTopicEnv = sandboxLifecycleTopicEnv;
package/dist/index.d.cts CHANGED
@@ -6,8 +6,43 @@ 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
+ /** Backend to ask; the deployment's default when omitted. */
33
+ provider?: string;
34
+ }
35
+ interface ExecCommandOptions {
36
+ cwd?: string;
37
+ env?: Record<string, string>;
38
+ timeoutMs?: number;
39
+ user?: string;
40
+ }
41
+ interface ExecCommandResult {
42
+ stdout: string;
43
+ stderr: string;
44
+ exitCode: number;
45
+ }
11
46
  interface CreateRunRequest {
12
47
  code: string;
13
48
  language?: 'javascript' | 'typescript' | 'python' | 'bash' | 'ts' | 'js';
@@ -21,6 +56,8 @@ interface CreateRunRequest {
21
56
  persistent?: boolean;
22
57
  sandboxTtlSeconds?: number;
23
58
  runtime?: SandboxRuntime;
59
+ /** Backend to run on (`agent-sandbox`, `lambda-microvm`, `e2b`); the deployment's default when omitted. */
60
+ provider?: string;
24
61
  }
25
62
  interface CreateSandboxRequest {
26
63
  cpuSize?: number;
@@ -28,6 +65,12 @@ interface CreateSandboxRequest {
28
65
  sandboxTtlSeconds?: number;
29
66
  files?: FileInput[];
30
67
  runtime?: SandboxRuntime;
68
+ image?: string;
69
+ env?: Record<string, string>;
70
+ metadata?: Record<string, string>;
71
+ onTimeout?: SandboxOnTimeout;
72
+ /** Backend to host it; the deployment's default when omitted. */
73
+ provider?: string;
31
74
  }
32
75
  type FileCategory = 'input' | 'skill' | 'settings' | 'context' | 'workspace' | 'output';
33
76
  interface FileInput {
@@ -52,6 +95,8 @@ interface BulkUploadResult {
52
95
  }>;
53
96
  }
54
97
  type Status = 'pending' | 'running' | 'completed' | 'failed' | 'timeout' | 'cancelled';
98
+ /** A run's status, as `run-lifecycle` events and `RunResponse` report it. */
99
+ type RunStatus = Status;
55
100
  interface RunResponse {
56
101
  id: string;
57
102
  workspaceId: string;
@@ -118,7 +163,7 @@ interface SandboxFiles {
118
163
  uploadBulk: (files: BulkFileInput[]) => Promise<BulkUploadResult>;
119
164
  }
120
165
  interface SandboxCommands {
121
- run: (command: string) => Promise<{
166
+ run: (command: string, options?: ExecCommandOptions) => Promise<{
122
167
  stdout: string;
123
168
  stderr: string;
124
169
  exitCode?: number;
@@ -132,22 +177,18 @@ declare class Sandbox {
132
177
  readonly files: SandboxFiles;
133
178
  readonly commands: SandboxCommands;
134
179
  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>;
180
+ private lastInfo?;
181
+ constructor(client: SandboxClient, sandboxId: string, auth: AuthStrategy, info?: SandboxInfo);
182
+ get info(): SandboxInfo | undefined;
183
+ static create(client: SandboxClient, options?: CreateSandboxRequest): Promise<Sandbox>;
147
184
  static connect(client: SandboxClient, sandboxId: string): Promise<Sandbox>;
148
185
  private normalizeLanguage;
149
186
  runCode(script: string, options?: RunCodeOptions): Promise<ExecutionResult>;
150
187
  kill(): Promise<void>;
188
+ getInfo(): Promise<SandboxInfo>;
189
+ extend(ttlSeconds: number): Promise<SandboxInfo>;
190
+ suspend(): Promise<SandboxInfo>;
191
+ resume(): Promise<SandboxInfo>;
151
192
  betaPause(): Promise<void>;
152
193
  setTimeout(ms: number): void;
153
194
  }
@@ -183,12 +224,18 @@ declare class SandboxClient {
183
224
  streamRun(request: CreateRunRequest): AsyncGenerator<StreamEvent>;
184
225
  getRun(runId: string): Promise<SandboxRun>;
185
226
  createSandbox(request?: CreateSandboxRequest): Promise<Sandbox>;
227
+ getSandbox(sandboxId: string): Promise<SandboxInfo>;
186
228
  getSandboxStatus(sandboxId: string): Promise<{
187
229
  sandboxId: string;
188
230
  status: Status;
189
231
  }>;
232
+ listSandboxes(options?: ListSandboxesOptions): Promise<SandboxInfo[]>;
190
233
  connectToSandbox(sandboxId: string): Promise<Sandbox>;
191
234
  deleteSandbox(sandboxId: string): Promise<void>;
235
+ execCommand(sandboxId: string, command: string, options?: ExecCommandOptions): Promise<ExecCommandResult>;
236
+ extendSandbox(sandboxId: string, ttlSeconds: number): Promise<SandboxInfo>;
237
+ suspendSandbox(sandboxId: string): Promise<SandboxInfo>;
238
+ resumeSandbox(sandboxId: string): Promise<SandboxInfo>;
192
239
  writeFile(sandboxId: string, path: string, content: string | Uint8Array): Promise<void>;
193
240
  readFile(sandboxId: string, path: string, options?: FileReadOptions): Promise<string | Blob>;
194
241
  fileExists(sandboxId: string, path: string): Promise<boolean>;
@@ -212,7 +259,91 @@ declare class FetchError extends Error {
212
259
  static from(url: string, method: string, res: Response): Promise<FetchError>;
213
260
  }
214
261
 
262
+ /**
263
+ * Lifecycle topics of the `lifecycle` Kafka item, one per aggregate and keyed
264
+ * by its id: `sandbox-lifecycle` by `sandboxId`, `run-lifecycle` by `runId`.
265
+ *
266
+ * Values are Avro in the Confluent wire format; the schema of each topic is
267
+ * registered under `<topic>-value` (`lifecycleSchemaSubject`). Decode with a
268
+ * registry client — `@kafkajs/confluent-schema-registry` against
269
+ * `KAFKA_<BINDING>_SCHEMA_REGISTRY_URL` — then narrow the decoded record with
270
+ * `isSandboxLifecycleEvent` / `isRunLifecycleEvent`. The message headers
271
+ * `event-type`, `event-id` and `workspace-id` carry enough to filter and
272
+ * dedupe without decoding.
273
+ */
274
+ declare const SANDBOX_LIFECYCLE_TOPIC = "sandbox-lifecycle";
275
+ declare const RUN_LIFECYCLE_TOPIC = "run-lifecycle";
276
+ declare const SANDBOX_LIFECYCLE_ITEM = "lifecycle";
277
+ type LifecycleTopic = typeof SANDBOX_LIFECYCLE_TOPIC | typeof RUN_LIFECYCLE_TOPIC;
278
+ declare const SANDBOX_LIFECYCLE_EVENT_TYPES: readonly ["created", "ready", "suspended", "resumed", "terminated", "failed", "expired"];
279
+ type SandboxLifecycleEventType = (typeof SANDBOX_LIFECYCLE_EVENT_TYPES)[number];
280
+ type SandboxLifecycleSource = 'api' | 'provider-webhook' | 'provider-watch';
281
+ /**
282
+ * One sandbox transition, delivered at-least-once on the `sandbox-lifecycle`
283
+ * topic keyed by `sandboxId`. Consumers dedupe by `eventId`.
284
+ */
285
+ interface SandboxLifecycleEvent {
286
+ version: 1;
287
+ eventId: string;
288
+ type: SandboxLifecycleEventType;
289
+ sandboxId: string;
290
+ workspaceId: string;
291
+ provider: string;
292
+ externalId: string;
293
+ image?: string | null;
294
+ state: SandboxState;
295
+ metadata: Record<string, string>;
296
+ occurredAt: string;
297
+ source: SandboxLifecycleSource;
298
+ }
299
+ declare const RUN_LIFECYCLE_EVENT_TYPES: readonly ["created", "started", "completed", "failed", "timeout", "cancelled"];
300
+ type RunLifecycleEventType = (typeof RUN_LIFECYCLE_EVENT_TYPES)[number];
301
+ type RunLifecycleSource = 'api' | 'executor' | 'maintenance';
302
+ /**
303
+ * One run status transition, delivered at-least-once on the `run-lifecycle`
304
+ * topic keyed by `runId`. A run emits each `type` at most once; a terminal
305
+ * event carries the exit code, duration and Vault references of its output,
306
+ * so a consumer needs no `GET /api/runs/:id` to act on it.
307
+ */
308
+ interface RunLifecycleEvent {
309
+ version: 1;
310
+ eventId: string;
311
+ type: RunLifecycleEventType;
312
+ runId: string;
313
+ workspaceId: string;
314
+ sandboxId?: string | null;
315
+ provider?: string | null;
316
+ language: string;
317
+ status: RunStatus;
318
+ exitCode?: number | null;
319
+ durationMs?: number | null;
320
+ errorMessage?: string | null;
321
+ stdoutVaultRef?: string | null;
322
+ stderrVaultRef?: string | null;
323
+ occurredAt: string;
324
+ source: RunLifecycleSource;
325
+ }
326
+ declare const RUN_LIFECYCLE_TERMINAL_TYPES: readonly RunLifecycleEventType[];
327
+ /** `KAFKA_<BINDING>_TOPIC_<TOPIC>`: the resolved topic name the chart injects. */
328
+ declare function lifecycleTopicEnv(topic: LifecycleTopic, binding?: string): string;
329
+ declare function sandboxLifecycleTopicEnv(binding?: string): string;
330
+ declare function runLifecycleTopicEnv(binding?: string): string;
331
+ /** `KAFKA_<BINDING>_SCHEMA_REGISTRY_URL`: the Confluent-compatible registry the values were encoded against. */
332
+ declare function lifecycleSchemaRegistryEnv(binding?: string): string;
333
+ /** The registry subject a topic's value schema lives under (TopicNameStrategy). */
334
+ declare function lifecycleSchemaSubject(topic: LifecycleTopic): string;
335
+ declare function isSandboxLifecycleEvent(value: unknown): value is SandboxLifecycleEvent;
336
+ declare function isRunLifecycleEvent(value: unknown): value is RunLifecycleEvent;
337
+ /**
338
+ * Narrows a decoded record to a sandbox event. Accepts the object a registry
339
+ * client decoded, or JSON text for a value that was re-serialised along the
340
+ * way; returns null for anything else, including the raw Avro bytes, which
341
+ * only the registry can decode.
342
+ */
343
+ declare function parseSandboxLifecycleEvent(raw: unknown): SandboxLifecycleEvent | null;
344
+ declare function parseRunLifecycleEvent(raw: unknown): RunLifecycleEvent | null;
345
+
215
346
  declare function sandbox(config: SandboxConfig): SandboxClient;
216
347
 
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 };
348
+ 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 };
349
+ 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 };
package/dist/index.d.mts CHANGED
@@ -6,8 +6,43 @@ 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
+ /** Backend to ask; the deployment's default when omitted. */
33
+ provider?: string;
34
+ }
35
+ interface ExecCommandOptions {
36
+ cwd?: string;
37
+ env?: Record<string, string>;
38
+ timeoutMs?: number;
39
+ user?: string;
40
+ }
41
+ interface ExecCommandResult {
42
+ stdout: string;
43
+ stderr: string;
44
+ exitCode: number;
45
+ }
11
46
  interface CreateRunRequest {
12
47
  code: string;
13
48
  language?: 'javascript' | 'typescript' | 'python' | 'bash' | 'ts' | 'js';
@@ -21,6 +56,8 @@ interface CreateRunRequest {
21
56
  persistent?: boolean;
22
57
  sandboxTtlSeconds?: number;
23
58
  runtime?: SandboxRuntime;
59
+ /** Backend to run on (`agent-sandbox`, `lambda-microvm`, `e2b`); the deployment's default when omitted. */
60
+ provider?: string;
24
61
  }
25
62
  interface CreateSandboxRequest {
26
63
  cpuSize?: number;
@@ -28,6 +65,12 @@ interface CreateSandboxRequest {
28
65
  sandboxTtlSeconds?: number;
29
66
  files?: FileInput[];
30
67
  runtime?: SandboxRuntime;
68
+ image?: string;
69
+ env?: Record<string, string>;
70
+ metadata?: Record<string, string>;
71
+ onTimeout?: SandboxOnTimeout;
72
+ /** Backend to host it; the deployment's default when omitted. */
73
+ provider?: string;
31
74
  }
32
75
  type FileCategory = 'input' | 'skill' | 'settings' | 'context' | 'workspace' | 'output';
33
76
  interface FileInput {
@@ -52,6 +95,8 @@ interface BulkUploadResult {
52
95
  }>;
53
96
  }
54
97
  type Status = 'pending' | 'running' | 'completed' | 'failed' | 'timeout' | 'cancelled';
98
+ /** A run's status, as `run-lifecycle` events and `RunResponse` report it. */
99
+ type RunStatus = Status;
55
100
  interface RunResponse {
56
101
  id: string;
57
102
  workspaceId: string;
@@ -118,7 +163,7 @@ interface SandboxFiles {
118
163
  uploadBulk: (files: BulkFileInput[]) => Promise<BulkUploadResult>;
119
164
  }
120
165
  interface SandboxCommands {
121
- run: (command: string) => Promise<{
166
+ run: (command: string, options?: ExecCommandOptions) => Promise<{
122
167
  stdout: string;
123
168
  stderr: string;
124
169
  exitCode?: number;
@@ -132,22 +177,18 @@ declare class Sandbox {
132
177
  readonly files: SandboxFiles;
133
178
  readonly commands: SandboxCommands;
134
179
  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>;
180
+ private lastInfo?;
181
+ constructor(client: SandboxClient, sandboxId: string, auth: AuthStrategy, info?: SandboxInfo);
182
+ get info(): SandboxInfo | undefined;
183
+ static create(client: SandboxClient, options?: CreateSandboxRequest): Promise<Sandbox>;
147
184
  static connect(client: SandboxClient, sandboxId: string): Promise<Sandbox>;
148
185
  private normalizeLanguage;
149
186
  runCode(script: string, options?: RunCodeOptions): Promise<ExecutionResult>;
150
187
  kill(): Promise<void>;
188
+ getInfo(): Promise<SandboxInfo>;
189
+ extend(ttlSeconds: number): Promise<SandboxInfo>;
190
+ suspend(): Promise<SandboxInfo>;
191
+ resume(): Promise<SandboxInfo>;
151
192
  betaPause(): Promise<void>;
152
193
  setTimeout(ms: number): void;
153
194
  }
@@ -183,12 +224,18 @@ declare class SandboxClient {
183
224
  streamRun(request: CreateRunRequest): AsyncGenerator<StreamEvent>;
184
225
  getRun(runId: string): Promise<SandboxRun>;
185
226
  createSandbox(request?: CreateSandboxRequest): Promise<Sandbox>;
227
+ getSandbox(sandboxId: string): Promise<SandboxInfo>;
186
228
  getSandboxStatus(sandboxId: string): Promise<{
187
229
  sandboxId: string;
188
230
  status: Status;
189
231
  }>;
232
+ listSandboxes(options?: ListSandboxesOptions): Promise<SandboxInfo[]>;
190
233
  connectToSandbox(sandboxId: string): Promise<Sandbox>;
191
234
  deleteSandbox(sandboxId: string): Promise<void>;
235
+ execCommand(sandboxId: string, command: string, options?: ExecCommandOptions): Promise<ExecCommandResult>;
236
+ extendSandbox(sandboxId: string, ttlSeconds: number): Promise<SandboxInfo>;
237
+ suspendSandbox(sandboxId: string): Promise<SandboxInfo>;
238
+ resumeSandbox(sandboxId: string): Promise<SandboxInfo>;
192
239
  writeFile(sandboxId: string, path: string, content: string | Uint8Array): Promise<void>;
193
240
  readFile(sandboxId: string, path: string, options?: FileReadOptions): Promise<string | Blob>;
194
241
  fileExists(sandboxId: string, path: string): Promise<boolean>;
@@ -212,7 +259,91 @@ declare class FetchError extends Error {
212
259
  static from(url: string, method: string, res: Response): Promise<FetchError>;
213
260
  }
214
261
 
262
+ /**
263
+ * Lifecycle topics of the `lifecycle` Kafka item, one per aggregate and keyed
264
+ * by its id: `sandbox-lifecycle` by `sandboxId`, `run-lifecycle` by `runId`.
265
+ *
266
+ * Values are Avro in the Confluent wire format; the schema of each topic is
267
+ * registered under `<topic>-value` (`lifecycleSchemaSubject`). Decode with a
268
+ * registry client — `@kafkajs/confluent-schema-registry` against
269
+ * `KAFKA_<BINDING>_SCHEMA_REGISTRY_URL` — then narrow the decoded record with
270
+ * `isSandboxLifecycleEvent` / `isRunLifecycleEvent`. The message headers
271
+ * `event-type`, `event-id` and `workspace-id` carry enough to filter and
272
+ * dedupe without decoding.
273
+ */
274
+ declare const SANDBOX_LIFECYCLE_TOPIC = "sandbox-lifecycle";
275
+ declare const RUN_LIFECYCLE_TOPIC = "run-lifecycle";
276
+ declare const SANDBOX_LIFECYCLE_ITEM = "lifecycle";
277
+ type LifecycleTopic = typeof SANDBOX_LIFECYCLE_TOPIC | typeof RUN_LIFECYCLE_TOPIC;
278
+ declare const SANDBOX_LIFECYCLE_EVENT_TYPES: readonly ["created", "ready", "suspended", "resumed", "terminated", "failed", "expired"];
279
+ type SandboxLifecycleEventType = (typeof SANDBOX_LIFECYCLE_EVENT_TYPES)[number];
280
+ type SandboxLifecycleSource = 'api' | 'provider-webhook' | 'provider-watch';
281
+ /**
282
+ * One sandbox transition, delivered at-least-once on the `sandbox-lifecycle`
283
+ * topic keyed by `sandboxId`. Consumers dedupe by `eventId`.
284
+ */
285
+ interface SandboxLifecycleEvent {
286
+ version: 1;
287
+ eventId: string;
288
+ type: SandboxLifecycleEventType;
289
+ sandboxId: string;
290
+ workspaceId: string;
291
+ provider: string;
292
+ externalId: string;
293
+ image?: string | null;
294
+ state: SandboxState;
295
+ metadata: Record<string, string>;
296
+ occurredAt: string;
297
+ source: SandboxLifecycleSource;
298
+ }
299
+ declare const RUN_LIFECYCLE_EVENT_TYPES: readonly ["created", "started", "completed", "failed", "timeout", "cancelled"];
300
+ type RunLifecycleEventType = (typeof RUN_LIFECYCLE_EVENT_TYPES)[number];
301
+ type RunLifecycleSource = 'api' | 'executor' | 'maintenance';
302
+ /**
303
+ * One run status transition, delivered at-least-once on the `run-lifecycle`
304
+ * topic keyed by `runId`. A run emits each `type` at most once; a terminal
305
+ * event carries the exit code, duration and Vault references of its output,
306
+ * so a consumer needs no `GET /api/runs/:id` to act on it.
307
+ */
308
+ interface RunLifecycleEvent {
309
+ version: 1;
310
+ eventId: string;
311
+ type: RunLifecycleEventType;
312
+ runId: string;
313
+ workspaceId: string;
314
+ sandboxId?: string | null;
315
+ provider?: string | null;
316
+ language: string;
317
+ status: RunStatus;
318
+ exitCode?: number | null;
319
+ durationMs?: number | null;
320
+ errorMessage?: string | null;
321
+ stdoutVaultRef?: string | null;
322
+ stderrVaultRef?: string | null;
323
+ occurredAt: string;
324
+ source: RunLifecycleSource;
325
+ }
326
+ declare const RUN_LIFECYCLE_TERMINAL_TYPES: readonly RunLifecycleEventType[];
327
+ /** `KAFKA_<BINDING>_TOPIC_<TOPIC>`: the resolved topic name the chart injects. */
328
+ declare function lifecycleTopicEnv(topic: LifecycleTopic, binding?: string): string;
329
+ declare function sandboxLifecycleTopicEnv(binding?: string): string;
330
+ declare function runLifecycleTopicEnv(binding?: string): string;
331
+ /** `KAFKA_<BINDING>_SCHEMA_REGISTRY_URL`: the Confluent-compatible registry the values were encoded against. */
332
+ declare function lifecycleSchemaRegistryEnv(binding?: string): string;
333
+ /** The registry subject a topic's value schema lives under (TopicNameStrategy). */
334
+ declare function lifecycleSchemaSubject(topic: LifecycleTopic): string;
335
+ declare function isSandboxLifecycleEvent(value: unknown): value is SandboxLifecycleEvent;
336
+ declare function isRunLifecycleEvent(value: unknown): value is RunLifecycleEvent;
337
+ /**
338
+ * Narrows a decoded record to a sandbox event. Accepts the object a registry
339
+ * client decoded, or JSON text for a value that was re-serialised along the
340
+ * way; returns null for anything else, including the raw Avro bytes, which
341
+ * only the registry can decode.
342
+ */
343
+ declare function parseSandboxLifecycleEvent(raw: unknown): SandboxLifecycleEvent | null;
344
+ declare function parseRunLifecycleEvent(raw: unknown): RunLifecycleEvent | null;
345
+
215
346
  declare function sandbox(config: SandboxConfig): SandboxClient;
216
347
 
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 };
348
+ 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 };
349
+ 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 };
package/dist/index.d.ts CHANGED
@@ -6,8 +6,43 @@ 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
+ /** Backend to ask; the deployment's default when omitted. */
33
+ provider?: string;
34
+ }
35
+ interface ExecCommandOptions {
36
+ cwd?: string;
37
+ env?: Record<string, string>;
38
+ timeoutMs?: number;
39
+ user?: string;
40
+ }
41
+ interface ExecCommandResult {
42
+ stdout: string;
43
+ stderr: string;
44
+ exitCode: number;
45
+ }
11
46
  interface CreateRunRequest {
12
47
  code: string;
13
48
  language?: 'javascript' | 'typescript' | 'python' | 'bash' | 'ts' | 'js';
@@ -21,6 +56,8 @@ interface CreateRunRequest {
21
56
  persistent?: boolean;
22
57
  sandboxTtlSeconds?: number;
23
58
  runtime?: SandboxRuntime;
59
+ /** Backend to run on (`agent-sandbox`, `lambda-microvm`, `e2b`); the deployment's default when omitted. */
60
+ provider?: string;
24
61
  }
25
62
  interface CreateSandboxRequest {
26
63
  cpuSize?: number;
@@ -28,6 +65,12 @@ interface CreateSandboxRequest {
28
65
  sandboxTtlSeconds?: number;
29
66
  files?: FileInput[];
30
67
  runtime?: SandboxRuntime;
68
+ image?: string;
69
+ env?: Record<string, string>;
70
+ metadata?: Record<string, string>;
71
+ onTimeout?: SandboxOnTimeout;
72
+ /** Backend to host it; the deployment's default when omitted. */
73
+ provider?: string;
31
74
  }
32
75
  type FileCategory = 'input' | 'skill' | 'settings' | 'context' | 'workspace' | 'output';
33
76
  interface FileInput {
@@ -52,6 +95,8 @@ interface BulkUploadResult {
52
95
  }>;
53
96
  }
54
97
  type Status = 'pending' | 'running' | 'completed' | 'failed' | 'timeout' | 'cancelled';
98
+ /** A run's status, as `run-lifecycle` events and `RunResponse` report it. */
99
+ type RunStatus = Status;
55
100
  interface RunResponse {
56
101
  id: string;
57
102
  workspaceId: string;
@@ -118,7 +163,7 @@ interface SandboxFiles {
118
163
  uploadBulk: (files: BulkFileInput[]) => Promise<BulkUploadResult>;
119
164
  }
120
165
  interface SandboxCommands {
121
- run: (command: string) => Promise<{
166
+ run: (command: string, options?: ExecCommandOptions) => Promise<{
122
167
  stdout: string;
123
168
  stderr: string;
124
169
  exitCode?: number;
@@ -132,22 +177,18 @@ declare class Sandbox {
132
177
  readonly files: SandboxFiles;
133
178
  readonly commands: SandboxCommands;
134
179
  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>;
180
+ private lastInfo?;
181
+ constructor(client: SandboxClient, sandboxId: string, auth: AuthStrategy, info?: SandboxInfo);
182
+ get info(): SandboxInfo | undefined;
183
+ static create(client: SandboxClient, options?: CreateSandboxRequest): Promise<Sandbox>;
147
184
  static connect(client: SandboxClient, sandboxId: string): Promise<Sandbox>;
148
185
  private normalizeLanguage;
149
186
  runCode(script: string, options?: RunCodeOptions): Promise<ExecutionResult>;
150
187
  kill(): Promise<void>;
188
+ getInfo(): Promise<SandboxInfo>;
189
+ extend(ttlSeconds: number): Promise<SandboxInfo>;
190
+ suspend(): Promise<SandboxInfo>;
191
+ resume(): Promise<SandboxInfo>;
151
192
  betaPause(): Promise<void>;
152
193
  setTimeout(ms: number): void;
153
194
  }
@@ -183,12 +224,18 @@ declare class SandboxClient {
183
224
  streamRun(request: CreateRunRequest): AsyncGenerator<StreamEvent>;
184
225
  getRun(runId: string): Promise<SandboxRun>;
185
226
  createSandbox(request?: CreateSandboxRequest): Promise<Sandbox>;
227
+ getSandbox(sandboxId: string): Promise<SandboxInfo>;
186
228
  getSandboxStatus(sandboxId: string): Promise<{
187
229
  sandboxId: string;
188
230
  status: Status;
189
231
  }>;
232
+ listSandboxes(options?: ListSandboxesOptions): Promise<SandboxInfo[]>;
190
233
  connectToSandbox(sandboxId: string): Promise<Sandbox>;
191
234
  deleteSandbox(sandboxId: string): Promise<void>;
235
+ execCommand(sandboxId: string, command: string, options?: ExecCommandOptions): Promise<ExecCommandResult>;
236
+ extendSandbox(sandboxId: string, ttlSeconds: number): Promise<SandboxInfo>;
237
+ suspendSandbox(sandboxId: string): Promise<SandboxInfo>;
238
+ resumeSandbox(sandboxId: string): Promise<SandboxInfo>;
192
239
  writeFile(sandboxId: string, path: string, content: string | Uint8Array): Promise<void>;
193
240
  readFile(sandboxId: string, path: string, options?: FileReadOptions): Promise<string | Blob>;
194
241
  fileExists(sandboxId: string, path: string): Promise<boolean>;
@@ -212,7 +259,91 @@ declare class FetchError extends Error {
212
259
  static from(url: string, method: string, res: Response): Promise<FetchError>;
213
260
  }
214
261
 
262
+ /**
263
+ * Lifecycle topics of the `lifecycle` Kafka item, one per aggregate and keyed
264
+ * by its id: `sandbox-lifecycle` by `sandboxId`, `run-lifecycle` by `runId`.
265
+ *
266
+ * Values are Avro in the Confluent wire format; the schema of each topic is
267
+ * registered under `<topic>-value` (`lifecycleSchemaSubject`). Decode with a
268
+ * registry client — `@kafkajs/confluent-schema-registry` against
269
+ * `KAFKA_<BINDING>_SCHEMA_REGISTRY_URL` — then narrow the decoded record with
270
+ * `isSandboxLifecycleEvent` / `isRunLifecycleEvent`. The message headers
271
+ * `event-type`, `event-id` and `workspace-id` carry enough to filter and
272
+ * dedupe without decoding.
273
+ */
274
+ declare const SANDBOX_LIFECYCLE_TOPIC = "sandbox-lifecycle";
275
+ declare const RUN_LIFECYCLE_TOPIC = "run-lifecycle";
276
+ declare const SANDBOX_LIFECYCLE_ITEM = "lifecycle";
277
+ type LifecycleTopic = typeof SANDBOX_LIFECYCLE_TOPIC | typeof RUN_LIFECYCLE_TOPIC;
278
+ declare const SANDBOX_LIFECYCLE_EVENT_TYPES: readonly ["created", "ready", "suspended", "resumed", "terminated", "failed", "expired"];
279
+ type SandboxLifecycleEventType = (typeof SANDBOX_LIFECYCLE_EVENT_TYPES)[number];
280
+ type SandboxLifecycleSource = 'api' | 'provider-webhook' | 'provider-watch';
281
+ /**
282
+ * One sandbox transition, delivered at-least-once on the `sandbox-lifecycle`
283
+ * topic keyed by `sandboxId`. Consumers dedupe by `eventId`.
284
+ */
285
+ interface SandboxLifecycleEvent {
286
+ version: 1;
287
+ eventId: string;
288
+ type: SandboxLifecycleEventType;
289
+ sandboxId: string;
290
+ workspaceId: string;
291
+ provider: string;
292
+ externalId: string;
293
+ image?: string | null;
294
+ state: SandboxState;
295
+ metadata: Record<string, string>;
296
+ occurredAt: string;
297
+ source: SandboxLifecycleSource;
298
+ }
299
+ declare const RUN_LIFECYCLE_EVENT_TYPES: readonly ["created", "started", "completed", "failed", "timeout", "cancelled"];
300
+ type RunLifecycleEventType = (typeof RUN_LIFECYCLE_EVENT_TYPES)[number];
301
+ type RunLifecycleSource = 'api' | 'executor' | 'maintenance';
302
+ /**
303
+ * One run status transition, delivered at-least-once on the `run-lifecycle`
304
+ * topic keyed by `runId`. A run emits each `type` at most once; a terminal
305
+ * event carries the exit code, duration and Vault references of its output,
306
+ * so a consumer needs no `GET /api/runs/:id` to act on it.
307
+ */
308
+ interface RunLifecycleEvent {
309
+ version: 1;
310
+ eventId: string;
311
+ type: RunLifecycleEventType;
312
+ runId: string;
313
+ workspaceId: string;
314
+ sandboxId?: string | null;
315
+ provider?: string | null;
316
+ language: string;
317
+ status: RunStatus;
318
+ exitCode?: number | null;
319
+ durationMs?: number | null;
320
+ errorMessage?: string | null;
321
+ stdoutVaultRef?: string | null;
322
+ stderrVaultRef?: string | null;
323
+ occurredAt: string;
324
+ source: RunLifecycleSource;
325
+ }
326
+ declare const RUN_LIFECYCLE_TERMINAL_TYPES: readonly RunLifecycleEventType[];
327
+ /** `KAFKA_<BINDING>_TOPIC_<TOPIC>`: the resolved topic name the chart injects. */
328
+ declare function lifecycleTopicEnv(topic: LifecycleTopic, binding?: string): string;
329
+ declare function sandboxLifecycleTopicEnv(binding?: string): string;
330
+ declare function runLifecycleTopicEnv(binding?: string): string;
331
+ /** `KAFKA_<BINDING>_SCHEMA_REGISTRY_URL`: the Confluent-compatible registry the values were encoded against. */
332
+ declare function lifecycleSchemaRegistryEnv(binding?: string): string;
333
+ /** The registry subject a topic's value schema lives under (TopicNameStrategy). */
334
+ declare function lifecycleSchemaSubject(topic: LifecycleTopic): string;
335
+ declare function isSandboxLifecycleEvent(value: unknown): value is SandboxLifecycleEvent;
336
+ declare function isRunLifecycleEvent(value: unknown): value is RunLifecycleEvent;
337
+ /**
338
+ * Narrows a decoded record to a sandbox event. Accepts the object a registry
339
+ * client decoded, or JSON text for a value that was re-serialised along the
340
+ * way; returns null for anything else, including the raw Avro bytes, which
341
+ * only the registry can decode.
342
+ */
343
+ declare function parseSandboxLifecycleEvent(raw: unknown): SandboxLifecycleEvent | null;
344
+ declare function parseRunLifecycleEvent(raw: unknown): RunLifecycleEvent | null;
345
+
215
346
  declare function sandbox(config: SandboxConfig): SandboxClient;
216
347
 
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 };
348
+ 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 };
349
+ 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 };
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,64 @@ 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
+ if (options.provider) {
431
+ params.set("provider", options.provider);
432
+ }
433
+ const query = params.size > 0 ? `?${params.toString()}` : "";
434
+ const response = await this.fetch(`/api/sandboxes${query}`);
435
+ return response.data;
436
+ }
408
437
  async connectToSandbox(sandboxId) {
409
- await this.getSandboxStatus(sandboxId);
410
- return new Sandbox(this, sandboxId, this.auth);
438
+ const info = await this.getSandbox(sandboxId);
439
+ return new Sandbox(this, sandboxId, this.auth, info);
411
440
  }
412
441
  async deleteSandbox(sandboxId) {
413
442
  await this.fetch(`/api/sandboxes/${sandboxId}`, { method: "DELETE" });
414
443
  }
444
+ async execCommand(sandboxId, command, options = {}) {
445
+ const response = await this.fetch(`/api/sandboxes/${sandboxId}/exec`, {
446
+ method: "POST",
447
+ body: JSON.stringify({ command, ...options })
448
+ });
449
+ return response.data;
450
+ }
451
+ async extendSandbox(sandboxId, ttlSeconds) {
452
+ const response = await this.fetch(`/api/sandboxes/${sandboxId}/extend`, {
453
+ method: "POST",
454
+ body: JSON.stringify({ ttlSeconds })
455
+ });
456
+ return response.data;
457
+ }
458
+ async suspendSandbox(sandboxId) {
459
+ const response = await this.fetch(`/api/sandboxes/${sandboxId}/suspend`, {
460
+ method: "POST"
461
+ });
462
+ return response.data;
463
+ }
464
+ async resumeSandbox(sandboxId) {
465
+ const response = await this.fetch(`/api/sandboxes/${sandboxId}/resume`, {
466
+ method: "POST"
467
+ });
468
+ return response.data;
469
+ }
415
470
  // === File Operations ===
416
471
  async writeFile(sandboxId, path, content) {
417
472
  const isBuffer = content instanceof Uint8Array;
@@ -488,8 +543,87 @@ class DataTokenAuthStrategy {
488
543
  }
489
544
  }
490
545
 
546
+ const SANDBOX_LIFECYCLE_TOPIC = "sandbox-lifecycle";
547
+ const RUN_LIFECYCLE_TOPIC = "run-lifecycle";
548
+ const SANDBOX_LIFECYCLE_ITEM = "lifecycle";
549
+ const SANDBOX_LIFECYCLE_EVENT_TYPES = [
550
+ "created",
551
+ "ready",
552
+ "suspended",
553
+ "resumed",
554
+ "terminated",
555
+ "failed",
556
+ "expired"
557
+ ];
558
+ const RUN_LIFECYCLE_EVENT_TYPES = [
559
+ "created",
560
+ "started",
561
+ "completed",
562
+ "failed",
563
+ "timeout",
564
+ "cancelled"
565
+ ];
566
+ const RUN_LIFECYCLE_TERMINAL_TYPES = ["completed", "failed", "timeout", "cancelled"];
567
+ function envSegment(value) {
568
+ return value.toUpperCase().replaceAll("-", "_");
569
+ }
570
+ function lifecycleTopicEnv(topic, binding = SANDBOX_LIFECYCLE_ITEM) {
571
+ return `KAFKA_${envSegment(binding)}_TOPIC_${envSegment(topic)}`;
572
+ }
573
+ function sandboxLifecycleTopicEnv(binding = SANDBOX_LIFECYCLE_ITEM) {
574
+ return lifecycleTopicEnv(SANDBOX_LIFECYCLE_TOPIC, binding);
575
+ }
576
+ function runLifecycleTopicEnv(binding = SANDBOX_LIFECYCLE_ITEM) {
577
+ return lifecycleTopicEnv(RUN_LIFECYCLE_TOPIC, binding);
578
+ }
579
+ function lifecycleSchemaRegistryEnv(binding = SANDBOX_LIFECYCLE_ITEM) {
580
+ return `KAFKA_${envSegment(binding)}_SCHEMA_REGISTRY_URL`;
581
+ }
582
+ function lifecycleSchemaSubject(topic) {
583
+ return `${topic}-value`;
584
+ }
585
+ function isRecord(value) {
586
+ return typeof value === "object" && value !== null;
587
+ }
588
+ function isOptionalString(value) {
589
+ return value === void 0 || value === null || typeof value === "string";
590
+ }
591
+ function isSandboxLifecycleEvent(value) {
592
+ if (!isRecord(value)) {
593
+ return false;
594
+ }
595
+ return value.version === 1 && typeof value.eventId === "string" && SANDBOX_LIFECYCLE_EVENT_TYPES.includes(value.type) && typeof value.sandboxId === "string" && typeof value.workspaceId === "string" && typeof value.provider === "string" && typeof value.externalId === "string" && isOptionalString(value.image) && typeof value.state === "string" && isRecord(value.metadata) && typeof value.occurredAt === "string" && typeof value.source === "string";
596
+ }
597
+ function isRunLifecycleEvent(value) {
598
+ if (!isRecord(value)) {
599
+ return false;
600
+ }
601
+ return value.version === 1 && typeof value.eventId === "string" && RUN_LIFECYCLE_EVENT_TYPES.includes(value.type) && typeof value.runId === "string" && typeof value.workspaceId === "string" && isOptionalString(value.sandboxId) && isOptionalString(value.provider) && typeof value.language === "string" && typeof value.status === "string" && typeof value.occurredAt === "string" && typeof value.source === "string";
602
+ }
603
+ function parseSandboxLifecycleEvent(raw) {
604
+ const value = decoded(raw);
605
+ return isSandboxLifecycleEvent(value) ? value : null;
606
+ }
607
+ function parseRunLifecycleEvent(raw) {
608
+ const value = decoded(raw);
609
+ return isRunLifecycleEvent(value) ? value : null;
610
+ }
611
+ function decoded(raw) {
612
+ if (raw === null || raw === void 0) {
613
+ return null;
614
+ }
615
+ if (typeof raw === "string") {
616
+ try {
617
+ return JSON.parse(raw);
618
+ } catch {
619
+ return null;
620
+ }
621
+ }
622
+ return raw;
623
+ }
624
+
491
625
  function sandbox(config) {
492
626
  return new SandboxClient(config);
493
627
  }
494
628
 
495
- export { DataTokenAuthStrategy, FetchError, SANDBOX_RUNTIMES, Sandbox, SandboxClient, SandboxRun, sandbox };
629
+ 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 };
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.5.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
  }