@meistrari/sandbox-sdk 1.7.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -216,7 +216,7 @@ await sandbox.kill()
216
216
  ### Selecting a Backend
217
217
 
218
218
  ```typescript
219
- // `agent-sandbox`, `lambda-microvm` or `e2b`; omitting it uses the
219
+ // `agent-sandbox`, `lambda-microvm`, `e2b`, `e2b-cluster` or `cube`; omitting it uses the
220
220
  // deployment's default. Naming one is a promise: the request is served by
221
221
  // that backend or it fails.
222
222
  const run = await client.createRunAndWait({
@@ -254,6 +254,65 @@ const sandbox = await Sandbox.connect(client, existingSandboxId)
254
254
  await sandbox.runCode('console.log("I am back!")')
255
255
  ```
256
256
 
257
+ ### Direct Access
258
+
259
+ On a backend with direct access (`e2b`, `e2b-cluster` and `cube`), the caller that created a
260
+ sandbox can talk to it without going through this API: commands, files, PTY
261
+ and WebSocket go straight to the backend's sandbox proxy. Creation, listing,
262
+ suspend, extend and delete still go through the API.
263
+
264
+ ```typescript
265
+ const sandbox = await client.createSandbox({
266
+ provider: 'e2b',
267
+ privateTraffic: true, // seal it: every port demands a token
268
+ onTimeout: 'suspend',
269
+ })
270
+
271
+ const access = sandbox.access
272
+ // {
273
+ // envdAccessToken: header X-Access-Token, to the in-sandbox agent (envd)
274
+ // trafficAccessToken: header e2b-traffic-access-token, to every other port
275
+ // sandboxUrl: base URL of the sandbox proxy, when one address serves every sandbox
276
+ // sandboxDomain: otherwise <port>-<externalId>.<sandboxDomain>
277
+ // envdVersion: version of the in-sandbox agent
278
+ // }
279
+ const engineId = sandbox.info?.externalId // the id direct access addresses
280
+
281
+ await sandbox.suspend()
282
+ await sandbox.resume()
283
+ sandbox.access // filled in again, including tokens the backend only returns at creation
284
+ ```
285
+
286
+ - **The tokens are credentials.** Whoever holds them and reaches the proxy
287
+ drives the sandbox. Keep them out of logs, traces and error messages. The
288
+ `Sandbox` object keeps them in a private field, so `JSON.stringify(sandbox)`
289
+ and `console.log(sandbox)` do not print them; `sandbox.access` and the raw
290
+ `client.getSandbox()` answer do.
291
+ - `sandbox.access` follows create, `getInfo()` and `resume()`. `extend()` and
292
+ `suspend()` answer no access and do not erase it. `listSandboxes()` never
293
+ carries it.
294
+ - On `e2b`, without `privateTraffic` there is no `trafficAccessToken` and the
295
+ sandbox's ports answer anyone who reaches the proxy.
296
+ - `lambda-microvm` and `agent-sandbox` have no direct access: `access` is
297
+ `undefined`, and `privateTraffic: true` is refused with 409.
298
+ - `e2b-cluster` (the E2B runtime in our cluster) seals every sandbox:
299
+ `privateTraffic` is not needed, `privateTraffic: false` is ignored, and
300
+ `access` always carries both tokens and the proxy's `sandboxUrl`.
301
+ - `cube` (CubeSandbox) seals every sandbox too, with one token: there is no
302
+ `envdAccessToken`, and `trafficAccessToken` goes on every request, the ones
303
+ to the in-sandbox agent included. The address is always `sandboxUrl`.
304
+ - On `cube`, `sandboxTtlSeconds` and `extend()` count idleness, not lifetime:
305
+ every request the sandbox receives starts the count again and `expiresAt`
306
+ moves with it. `suspend()` takes the deadline away: the sandbox has no
307
+ `expiresAt`, `extend()` gives it none, and once it runs again it counts the
308
+ backend's default idle timeout (15 minutes unless the deployment sets
309
+ `CUBE_DEFAULT_TIMEOUT_SECONDS`), not what `sandboxTtlSeconds` or `extend()`
310
+ said.
311
+ - A backend that creates a sandbox that has to be sealed (asked for with
312
+ `privateTraffic`, or on `e2b-cluster` and `cube`) without a token that seals
313
+ it is a 502, and the sandbox is torn down: a sealed create never returns an
314
+ open sandbox. Do not retry it.
315
+
257
316
  ## API Reference
258
317
 
259
318
  ### `sandbox(config)`
@@ -289,6 +348,8 @@ const client = sandbox({
289
348
  | Property | Type | Description |
290
349
  |----------|------|-------------|
291
350
  | `sandboxId` | `string` | Unique sandbox identifier |
351
+ | `info` | `SandboxInfo \| undefined` | Last descriptor the API answered, without `access` |
352
+ | `access` | `SandboxAccess \| undefined` | Direct-access address and tokens; see [Direct Access](#direct-access) |
292
353
  | `files` | `SandboxFiles` | File operations interface |
293
354
  | `commands` | `SandboxCommands` | Command execution interface |
294
355
 
@@ -320,7 +381,7 @@ const client = sandbox({
320
381
  ```typescript
321
382
  type Status = 'pending' | 'running' | 'completed' | 'failed' | 'timeout' | 'cancelled'
322
383
 
323
- type SandboxRuntime = 'lambda-microvm'
384
+ type SandboxRuntime = 'lambda-microvm' | 'agent-sandbox' | 'e2b' | 'e2b-cluster' | 'cube'
324
385
 
325
386
  interface CreateRunRequest {
326
387
  code: string
@@ -377,6 +438,41 @@ await sandbox.runCode(code, { onStdout: ({ line }) => console.log(line) })
377
438
  await sandbox.kill()
378
439
  ```
379
440
 
441
+ ## Service token
442
+
443
+ For a workload with no caller behind it (a worker pausing an idle sandbox, a
444
+ reaper). The API accepts it on its internal address only, and only for the
445
+ lifecycle of a sandbox (create, list, read, extend, suspend, resume and
446
+ delete) and for a live snapshot of one (no `recipe`), reading that snapshot
447
+ and deleting one. Commands, files, runs, snapshot recipes and the snapshot
448
+ listing through the API still need the data token of the workspace.
449
+
450
+ That does not keep a service from running code. On a backend with direct
451
+ access (`e2b`, `e2b-cluster` and `cube`), create, `connectToSandbox` and resume give the service the
452
+ sandbox's `access`, as they give the owner, and with it the service runs
453
+ commands, files and traffic against the sandbox directly: that is how
454
+ agent-api drives the data plane. A service token can run code in every
455
+ sandbox of every workspace it names.
456
+
457
+ ```javascript
458
+ import { sandbox, ServiceTokenAuthStrategy } from '@meistrari/sandbox-sdk'
459
+
460
+ const service = new ServiceTokenAuthStrategy({ serviceToken: process.env.SANDBOX_API_SERVICE_TOKEN, workspaceId })
461
+
462
+ // Every call acts in that workspace, the listing included; a sandbox of another one answers 404.
463
+ const client = sandbox({ apiUrl, auth: service })
464
+ const found = await client.listSandboxes({ metadata: { sessionId } })
465
+ const box = await client.connectToSandbox(found[0].sandboxId)
466
+ await box.suspend()
467
+
468
+ // Another workspace, another strategy.
469
+ const other = sandbox({ apiUrl, auth: service.forWorkspace(otherWorkspaceId) })
470
+ ```
471
+
472
+ The strategy always takes a `workspaceId`: the API has no service operation that spans workspaces. `forWorkspace` and the constructor throw on a workspace id that is missing, `undefined` or empty, so an id lost on the way fails before a request goes out.
473
+
474
+ Never pass the service token into a sandbox (env, files or metadata).
475
+
380
476
  ## Error Handling
381
477
 
382
478
  ```typescript
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", "agent-sandbox", "e2b"];
6
+ const SANDBOX_RUNTIMES = ["lambda-microvm", "agent-sandbox", "e2b", "e2b-cluster", "cube"];
7
7
 
8
8
  class FetchError extends Error {
9
9
  constructor(message, url, method, status, response) {
@@ -71,6 +71,25 @@ var __publicField$2 = (obj, key, value) => {
71
71
  __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
72
72
  return value;
73
73
  };
74
+ var __accessCheck$1 = (obj, member, msg) => {
75
+ if (!member.has(obj))
76
+ throw TypeError("Cannot " + msg);
77
+ };
78
+ var __privateGet$1 = (obj, member, getter) => {
79
+ __accessCheck$1(obj, member, "read from private field");
80
+ return getter ? getter.call(obj) : member.get(obj);
81
+ };
82
+ var __privateAdd$1 = (obj, member, value) => {
83
+ if (member.has(obj))
84
+ throw TypeError("Cannot add the same private member more than once");
85
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
86
+ };
87
+ var __privateSet$1 = (obj, member, value, setter) => {
88
+ __accessCheck$1(obj, member, "write to private field");
89
+ setter ? setter.call(obj, value) : member.set(obj, value);
90
+ return value;
91
+ };
92
+ var _access;
74
93
  class Sandbox {
75
94
  constructor(client, sandboxId, auth, info) {
76
95
  this.client = client;
@@ -80,8 +99,11 @@ class Sandbox {
80
99
  __publicField$2(this, "commands");
81
100
  __publicField$2(this, "timeoutMs", 3e5);
82
101
  __publicField$2(this, "lastInfo");
102
+ // A `#private` field, unlike `lastInfo`: it holds credentials, and this
103
+ // keeps them out of `JSON.stringify(sandbox)` and of `console.log(sandbox)`.
104
+ __privateAdd$1(this, _access, void 0);
83
105
  this.sandboxId = sandboxId;
84
- this.lastInfo = info;
106
+ this.remember(info);
85
107
  const readFile = async (path, options) => {
86
108
  return await this.client.readFile(sandboxId, path, options);
87
109
  };
@@ -97,9 +119,30 @@ class Sandbox {
97
119
  run: async (command, options) => await this.client.execCommand(sandboxId, command, options)
98
120
  };
99
121
  }
122
+ /** The last descriptor the API answered, without `access`. */
100
123
  get info() {
101
124
  return this.lastInfo;
102
125
  }
126
+ /**
127
+ * Direct-access address and credentials, as last answered by create,
128
+ * `getInfo` or `resume`. `extend` and `suspend` do not answer them and do
129
+ * not erase them. `undefined` on a backend without direct access.
130
+ *
131
+ * The tokens are credentials: do not log what this returns.
132
+ */
133
+ get access() {
134
+ return __privateGet$1(this, _access);
135
+ }
136
+ remember(info) {
137
+ if (!info) {
138
+ return;
139
+ }
140
+ const { access, ...rest } = info;
141
+ this.lastInfo = rest;
142
+ if (access) {
143
+ __privateSet$1(this, _access, access);
144
+ }
145
+ }
103
146
  // Factory methods (static)
104
147
  static async create(client, options = {}) {
105
148
  return await client.createSandbox(options);
@@ -170,21 +213,34 @@ class Sandbox {
170
213
  }
171
214
  }
172
215
  }
216
+ /** Reads the sandbox again; the answer carries `access` where the backend has it. */
173
217
  async getInfo() {
174
- this.lastInfo = await this.client.getSandbox(this.sandboxId);
175
- return this.lastInfo;
218
+ const info = await this.client.getSandbox(this.sandboxId);
219
+ this.remember(info);
220
+ return info;
176
221
  }
222
+ /**
223
+ * Gives the sandbox `ttlSeconds` from now; on `cube`, `ttlSeconds` of
224
+ * idleness, and nothing while the sandbox is suspended.
225
+ */
177
226
  async extend(ttlSeconds) {
178
- this.lastInfo = await this.client.extendSandbox(this.sandboxId, ttlSeconds);
179
- return this.lastInfo;
227
+ const info = await this.client.extendSandbox(this.sandboxId, ttlSeconds);
228
+ this.remember(info);
229
+ return info;
180
230
  }
181
231
  async suspend() {
182
- this.lastInfo = await this.client.suspendSandbox(this.sandboxId);
183
- return this.lastInfo;
232
+ const info = await this.client.suspendSandbox(this.sandboxId);
233
+ this.remember(info);
234
+ return info;
184
235
  }
236
+ /**
237
+ * Resumes the sandbox. The answer carries `access` again, including the
238
+ * tokens a backend only hands out at creation, and `this.access` follows.
239
+ */
185
240
  async resume() {
186
- this.lastInfo = await this.client.resumeSandbox(this.sandboxId);
187
- return this.lastInfo;
241
+ const info = await this.client.resumeSandbox(this.sandboxId);
242
+ this.remember(info);
243
+ return info;
188
244
  }
189
245
  /**
190
246
  * Builds a reusable, pre-warmed image from this sandbox. Unlike `suspend`,
@@ -200,6 +256,7 @@ class Sandbox {
200
256
  this.timeoutMs = ms;
201
257
  }
202
258
  }
259
+ _access = new WeakMap();
203
260
 
204
261
  var __defProp$1 = Object.defineProperty;
205
262
  var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
@@ -619,6 +676,25 @@ class SandboxClient {
619
676
  }
620
677
  }
621
678
 
679
+ var __accessCheck = (obj, member, msg) => {
680
+ if (!member.has(obj))
681
+ throw TypeError("Cannot " + msg);
682
+ };
683
+ var __privateGet = (obj, member, getter) => {
684
+ __accessCheck(obj, member, "read from private field");
685
+ return getter ? getter.call(obj) : member.get(obj);
686
+ };
687
+ var __privateAdd = (obj, member, value) => {
688
+ if (member.has(obj))
689
+ throw TypeError("Cannot add the same private member more than once");
690
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
691
+ };
692
+ var __privateSet = (obj, member, value, setter) => {
693
+ __accessCheck(obj, member, "write to private field");
694
+ setter ? setter.call(obj, value) : member.set(obj, value);
695
+ return value;
696
+ };
697
+ var _serviceToken, _workspaceId;
622
698
  class DataTokenAuthStrategy {
623
699
  constructor(dataToken) {
624
700
  this.dataToken = dataToken;
@@ -629,6 +705,41 @@ class DataTokenAuthStrategy {
629
705
  });
630
706
  }
631
707
  }
708
+ const SERVICE_TOKEN_HEADER = "x-sandbox-service-token";
709
+ const SERVICE_WORKSPACE_HEADER = "x-sandbox-workspace-id";
710
+ function assertWorkspaceId(workspaceId) {
711
+ if (typeof workspaceId !== "string" || workspaceId.trim() === "") {
712
+ throw new Error("ServiceTokenAuthStrategy needs a non-empty workspaceId");
713
+ }
714
+ }
715
+ const _ServiceTokenAuthStrategy = class _ServiceTokenAuthStrategy {
716
+ constructor(options) {
717
+ // Private fields, so the token is not part of what a logger or
718
+ // JSON.stringify prints when handed the strategy or the client holding it.
719
+ __privateAdd(this, _serviceToken, void 0);
720
+ __privateAdd(this, _workspaceId, void 0);
721
+ if (!options.serviceToken) {
722
+ throw new Error("ServiceTokenAuthStrategy needs a service token");
723
+ }
724
+ assertWorkspaceId(options.workspaceId);
725
+ __privateSet(this, _serviceToken, options.serviceToken);
726
+ __privateSet(this, _workspaceId, options.workspaceId);
727
+ }
728
+ /** The same service acting in `workspaceId`, which must be a workspace id. */
729
+ forWorkspace(workspaceId) {
730
+ assertWorkspaceId(workspaceId);
731
+ return new _ServiceTokenAuthStrategy({ serviceToken: __privateGet(this, _serviceToken), workspaceId });
732
+ }
733
+ getHeaders() {
734
+ return new Headers({
735
+ [SERVICE_TOKEN_HEADER]: __privateGet(this, _serviceToken),
736
+ [SERVICE_WORKSPACE_HEADER]: __privateGet(this, _workspaceId)
737
+ });
738
+ }
739
+ };
740
+ _serviceToken = new WeakMap();
741
+ _workspaceId = new WeakMap();
742
+ let ServiceTokenAuthStrategy = _ServiceTokenAuthStrategy;
632
743
 
633
744
  const SANDBOX_LIFECYCLE_TOPIC = "sandbox-lifecycle";
634
745
  const RUN_LIFECYCLE_TOPIC = "run-lifecycle";
@@ -722,9 +833,12 @@ exports.SANDBOX_LIFECYCLE_EVENT_TYPES = SANDBOX_LIFECYCLE_EVENT_TYPES;
722
833
  exports.SANDBOX_LIFECYCLE_ITEM = SANDBOX_LIFECYCLE_ITEM;
723
834
  exports.SANDBOX_LIFECYCLE_TOPIC = SANDBOX_LIFECYCLE_TOPIC;
724
835
  exports.SANDBOX_RUNTIMES = SANDBOX_RUNTIMES;
836
+ exports.SERVICE_TOKEN_HEADER = SERVICE_TOKEN_HEADER;
837
+ exports.SERVICE_WORKSPACE_HEADER = SERVICE_WORKSPACE_HEADER;
725
838
  exports.Sandbox = Sandbox;
726
839
  exports.SandboxClient = SandboxClient;
727
840
  exports.SandboxRun = SandboxRun;
841
+ exports.ServiceTokenAuthStrategy = ServiceTokenAuthStrategy;
728
842
  exports.isRunLifecycleEvent = isRunLifecycleEvent;
729
843
  exports.isSandboxLifecycleEvent = isSandboxLifecycleEvent;
730
844
  exports.lifecycleSchemaRegistryEnv = lifecycleSchemaRegistryEnv;
package/dist/index.d.cts CHANGED
@@ -6,14 +6,52 @@ interface SandboxConfig {
6
6
  interface AuthStrategy {
7
7
  getHeaders: () => Headers;
8
8
  }
9
- declare const SANDBOX_RUNTIMES: readonly ["lambda-microvm", "agent-sandbox", "e2b"];
9
+ declare const SANDBOX_RUNTIMES: readonly ["lambda-microvm", "agent-sandbox", "e2b", "e2b-cluster", "cube"];
10
10
  type SandboxRuntime = (typeof SANDBOX_RUNTIMES)[number];
11
11
  type SandboxState = 'pending' | 'running' | 'suspended' | 'terminated' | 'failed';
12
12
  type SandboxOnTimeout = 'suspend' | 'terminate';
13
+ /**
14
+ * What it takes to talk to one sandbox directly, on the backend's data plane
15
+ * (commands, files, PTY, WebSocket), addressing it by `SandboxInfo.externalId`.
16
+ *
17
+ * `envdAccessToken` and `trafficAccessToken` are **credentials**: whoever holds
18
+ * them drives the sandbox. Keep them out of logs, traces and error messages.
19
+ *
20
+ * Only a backend with direct access returns this (`e2b`, `e2b-cluster` and
21
+ * `cube`; `lambda-microvm` and `agent-sandbox` never do), and only on create,
22
+ * get and resume. Every field is optional because backends differ.
23
+ */
24
+ interface SandboxAccess {
25
+ /**
26
+ * Sent as `X-Access-Token` to the in-sandbox agent (envd). Never present
27
+ * on `cube`, where the agent asks for `trafficAccessToken` instead.
28
+ */
29
+ envdAccessToken?: string;
30
+ /**
31
+ * Sent as `e2b-traffic-access-token` to every other port; on `cube` to
32
+ * every port, the agent included. On `e2b` it exists only for a sandbox
33
+ * created with `privateTraffic`; on `e2b-cluster` and `cube` every sandbox
34
+ * has one.
35
+ */
36
+ trafficAccessToken?: string;
37
+ /**
38
+ * Base URL of the backend's sandbox proxy, when one address serves every
39
+ * sandbox and routes by the `E2b-Sandbox-Id` and `E2b-Sandbox-Port` headers.
40
+ */
41
+ sandboxUrl?: string;
42
+ /**
43
+ * Domain the ports are published under, as
44
+ * `<port>-<externalId>.<sandboxDomain>`. Used when `sandboxUrl` is absent.
45
+ */
46
+ sandboxDomain?: string;
47
+ /** Version of the in-sandbox agent. */
48
+ envdVersion?: string;
49
+ }
13
50
  interface SandboxInfo {
14
51
  sandboxId: string;
15
52
  status: Status;
16
53
  provider: string;
54
+ /** The backend's own id for the sandbox; what direct access addresses. */
17
55
  externalId: string;
18
56
  state: SandboxState;
19
57
  image?: string;
@@ -23,8 +61,19 @@ interface SandboxInfo {
23
61
  persistent: boolean;
24
62
  createdAt: string;
25
63
  lastUsedAt: string;
64
+ /**
65
+ * When the sandbox times out. On `cube` it moves forward with every
66
+ * request the sandbox receives, and is absent once the sandbox was
67
+ * suspended through this API, until it runs again.
68
+ */
26
69
  expiresAt?: string;
27
70
  errorMessage?: string;
71
+ /**
72
+ * Direct-access address and credentials. Present on what `createSandbox`,
73
+ * `getSandbox` and `resumeSandbox` answer, on a backend with direct access.
74
+ * Never on `listSandboxes`, `extendSandbox` or `suspendSandbox`.
75
+ */
76
+ access?: SandboxAccess;
28
77
  }
29
78
  interface ListSandboxesOptions {
30
79
  metadata?: Record<string, string>;
@@ -56,7 +105,7 @@ interface CreateRunRequest {
56
105
  persistent?: boolean;
57
106
  sandboxTtlSeconds?: number;
58
107
  runtime?: SandboxRuntime;
59
- /** Backend to run on (`agent-sandbox`, `lambda-microvm`, `e2b`); the deployment's default when omitted. */
108
+ /** Backend to run on (`agent-sandbox`, `lambda-microvm`, `e2b`, `e2b-cluster`, `cube`); the deployment's default when omitted. */
60
109
  provider?: string;
61
110
  /**
62
111
  * Backend to try when `provider` does not deliver. Naming it is asking for
@@ -86,6 +135,14 @@ interface CreateSandboxRequest {
86
135
  snapshotId?: string;
87
136
  cpuSize?: number;
88
137
  memSize?: number;
138
+ /**
139
+ * Seconds until the sandbox times out and `onTimeout` applies. On `cube`
140
+ * they count idleness, not lifetime: every request the sandbox receives
141
+ * starts the count again, so a sandbox in use outlives them. And a `cube`
142
+ * sandbox that was suspended through the API and runs again counts the
143
+ * backend's default idle timeout (15 minutes unless the deployment sets
144
+ * `CUBE_DEFAULT_TIMEOUT_SECONDS`), not these.
145
+ */
89
146
  sandboxTtlSeconds?: number;
90
147
  files?: FileInput[];
91
148
  runtime?: SandboxRuntime;
@@ -95,6 +152,18 @@ interface CreateSandboxRequest {
95
152
  onTimeout?: SandboxOnTimeout;
96
153
  /** Backend to host it; the deployment's default when omitted. */
97
154
  provider?: string;
155
+ /**
156
+ * Seal the sandbox: no port answers a request without a token from
157
+ * `access`. On `e2b` and `e2b-cluster` the agent asks for
158
+ * `access.envdAccessToken` and every other port for
159
+ * `access.trafficAccessToken`; on `cube` there is no envd token and
160
+ * `access.trafficAccessToken` guards every port, the agent included. The
161
+ * API answers 409 on a backend that cannot (`lambda-microvm`,
162
+ * `agent-sandbox`), and 502 when the backend created the sandbox without
163
+ * a token that seals it (it is torn down). `e2b-cluster` and `cube` seal
164
+ * every sandbox whatever this says, `false` included.
165
+ */
166
+ privateTraffic?: boolean;
98
167
  }
99
168
  interface SnapshotRecipe {
100
169
  paths: string[];
@@ -222,6 +291,7 @@ interface SandboxCommands {
222
291
  }
223
292
 
224
293
  declare class Sandbox {
294
+ #private;
225
295
  private client;
226
296
  private auth;
227
297
  readonly sandboxId: string;
@@ -230,15 +300,34 @@ declare class Sandbox {
230
300
  private timeoutMs;
231
301
  private lastInfo?;
232
302
  constructor(client: SandboxClient, sandboxId: string, auth: AuthStrategy, info?: SandboxInfo);
303
+ /** The last descriptor the API answered, without `access`. */
233
304
  get info(): SandboxInfo | undefined;
305
+ /**
306
+ * Direct-access address and credentials, as last answered by create,
307
+ * `getInfo` or `resume`. `extend` and `suspend` do not answer them and do
308
+ * not erase them. `undefined` on a backend without direct access.
309
+ *
310
+ * The tokens are credentials: do not log what this returns.
311
+ */
312
+ get access(): SandboxAccess | undefined;
313
+ private remember;
234
314
  static create(client: SandboxClient, options?: CreateSandboxRequest): Promise<Sandbox>;
235
315
  static connect(client: SandboxClient, sandboxId: string): Promise<Sandbox>;
236
316
  private normalizeLanguage;
237
317
  runCode(script: string, options?: RunCodeOptions): Promise<ExecutionResult>;
238
318
  kill(): Promise<void>;
319
+ /** Reads the sandbox again; the answer carries `access` where the backend has it. */
239
320
  getInfo(): Promise<SandboxInfo>;
321
+ /**
322
+ * Gives the sandbox `ttlSeconds` from now; on `cube`, `ttlSeconds` of
323
+ * idleness, and nothing while the sandbox is suspended.
324
+ */
240
325
  extend(ttlSeconds: number): Promise<SandboxInfo>;
241
326
  suspend(): Promise<SandboxInfo>;
327
+ /**
328
+ * Resumes the sandbox. The answer carries `access` again, including the
329
+ * tokens a backend only hands out at creation, and `this.access` follows.
330
+ */
242
331
  resume(): Promise<SandboxInfo>;
243
332
  /**
244
333
  * Builds a reusable, pre-warmed image from this sandbox. Unlike `suspend`,
@@ -324,6 +413,44 @@ declare class DataTokenAuthStrategy implements AuthStrategy {
324
413
  constructor(dataToken: string);
325
414
  getHeaders(): Headers;
326
415
  }
416
+ declare const SERVICE_TOKEN_HEADER = "x-sandbox-service-token";
417
+ declare const SERVICE_WORKSPACE_HEADER = "x-sandbox-workspace-id";
418
+ /**
419
+ * A service acts in one workspace, named on every request: the API has no
420
+ * operation that spans workspaces for it. A `workspaceId` that is missing,
421
+ * `undefined` or empty is an error, never a wider request.
422
+ */
423
+ interface ServiceTokenAuthOptions {
424
+ /** The service token of this workload. Never a value a sandbox can read. */
425
+ serviceToken: string;
426
+ /** The workspace to act in. */
427
+ workspaceId: string;
428
+ }
429
+ /**
430
+ * Authenticates a workload that has no caller behind it, such as a worker
431
+ * pausing an idle sandbox or a reaper. The API accepts it on its internal
432
+ * address only, and only for the lifecycle of a sandbox (create, list, read,
433
+ * extend, suspend, resume and delete) and for a live snapshot of one (no
434
+ * recipe), reading that snapshot and deleting one. Running commands, files,
435
+ * runs, snapshot recipes and the snapshot listing through the API still need
436
+ * the data token of the workspace.
437
+ *
438
+ * On a backend with direct access, create, read and resume answer `access`
439
+ * to the service as to the owner, and with it the service drives the sandbox
440
+ * itself (commands, files, traffic): that is how agent-api's workloads reach
441
+ * the data plane. Treat the strategy as able to run code in the sandboxes of
442
+ * every workspace it names.
443
+ *
444
+ * A sandbox is reached in the workspace named here and answers 404 in any
445
+ * other, so build one strategy per workspace with `forWorkspace`.
446
+ */
447
+ declare class ServiceTokenAuthStrategy implements AuthStrategy {
448
+ #private;
449
+ constructor(options: ServiceTokenAuthOptions);
450
+ /** The same service acting in `workspaceId`, which must be a workspace id. */
451
+ forWorkspace(workspaceId: string): ServiceTokenAuthStrategy;
452
+ getHeaders(): Headers;
453
+ }
327
454
 
328
455
  declare class FetchError extends Error {
329
456
  readonly url: string;
@@ -420,5 +547,5 @@ declare function parseRunLifecycleEvent(raw: unknown): RunLifecycleEvent | null;
420
547
 
421
548
  declare function sandbox(config: SandboxConfig): SandboxClient;
422
549
 
423
- 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 };
424
- export type { AuthStrategy, CreateRunRequest, CreateSandboxRequest, CreateSnapshotRequest, ExecCommandOptions, ExecCommandResult, ExecutionResult, FileInput, LifecycleTopic, ListSandboxesOptions, RunCodeOptions, RunLifecycleEvent, RunLifecycleEventType, RunLifecycleSource, RunResponse, SandboxCommands, SandboxConfig, SandboxFiles, SandboxInfo, SandboxLifecycleEvent, SandboxLifecycleEventType, SandboxLifecycleSource, SandboxOnTimeout, SandboxRuntime, SandboxState, SnapshotInfo, SnapshotRecipe, Status, StreamCallbacks, StreamEvent };
550
+ 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, SERVICE_TOKEN_HEADER, SERVICE_WORKSPACE_HEADER, Sandbox, SandboxClient, SandboxRun, ServiceTokenAuthStrategy, isRunLifecycleEvent, isSandboxLifecycleEvent, lifecycleSchemaRegistryEnv, lifecycleSchemaSubject, lifecycleTopicEnv, parseRunLifecycleEvent, parseSandboxLifecycleEvent, runLifecycleTopicEnv, sandbox, sandboxLifecycleTopicEnv };
551
+ export type { AuthStrategy, CreateRunRequest, CreateSandboxRequest, CreateSnapshotRequest, ExecCommandOptions, ExecCommandResult, ExecutionResult, FileInput, LifecycleTopic, ListSandboxesOptions, RunCodeOptions, RunLifecycleEvent, RunLifecycleEventType, RunLifecycleSource, RunResponse, SandboxAccess, SandboxCommands, SandboxConfig, SandboxFiles, SandboxInfo, SandboxLifecycleEvent, SandboxLifecycleEventType, SandboxLifecycleSource, SandboxOnTimeout, SandboxRuntime, SandboxState, ServiceTokenAuthOptions, SnapshotInfo, SnapshotRecipe, Status, StreamCallbacks, StreamEvent };
package/dist/index.d.mts CHANGED
@@ -6,14 +6,52 @@ interface SandboxConfig {
6
6
  interface AuthStrategy {
7
7
  getHeaders: () => Headers;
8
8
  }
9
- declare const SANDBOX_RUNTIMES: readonly ["lambda-microvm", "agent-sandbox", "e2b"];
9
+ declare const SANDBOX_RUNTIMES: readonly ["lambda-microvm", "agent-sandbox", "e2b", "e2b-cluster", "cube"];
10
10
  type SandboxRuntime = (typeof SANDBOX_RUNTIMES)[number];
11
11
  type SandboxState = 'pending' | 'running' | 'suspended' | 'terminated' | 'failed';
12
12
  type SandboxOnTimeout = 'suspend' | 'terminate';
13
+ /**
14
+ * What it takes to talk to one sandbox directly, on the backend's data plane
15
+ * (commands, files, PTY, WebSocket), addressing it by `SandboxInfo.externalId`.
16
+ *
17
+ * `envdAccessToken` and `trafficAccessToken` are **credentials**: whoever holds
18
+ * them drives the sandbox. Keep them out of logs, traces and error messages.
19
+ *
20
+ * Only a backend with direct access returns this (`e2b`, `e2b-cluster` and
21
+ * `cube`; `lambda-microvm` and `agent-sandbox` never do), and only on create,
22
+ * get and resume. Every field is optional because backends differ.
23
+ */
24
+ interface SandboxAccess {
25
+ /**
26
+ * Sent as `X-Access-Token` to the in-sandbox agent (envd). Never present
27
+ * on `cube`, where the agent asks for `trafficAccessToken` instead.
28
+ */
29
+ envdAccessToken?: string;
30
+ /**
31
+ * Sent as `e2b-traffic-access-token` to every other port; on `cube` to
32
+ * every port, the agent included. On `e2b` it exists only for a sandbox
33
+ * created with `privateTraffic`; on `e2b-cluster` and `cube` every sandbox
34
+ * has one.
35
+ */
36
+ trafficAccessToken?: string;
37
+ /**
38
+ * Base URL of the backend's sandbox proxy, when one address serves every
39
+ * sandbox and routes by the `E2b-Sandbox-Id` and `E2b-Sandbox-Port` headers.
40
+ */
41
+ sandboxUrl?: string;
42
+ /**
43
+ * Domain the ports are published under, as
44
+ * `<port>-<externalId>.<sandboxDomain>`. Used when `sandboxUrl` is absent.
45
+ */
46
+ sandboxDomain?: string;
47
+ /** Version of the in-sandbox agent. */
48
+ envdVersion?: string;
49
+ }
13
50
  interface SandboxInfo {
14
51
  sandboxId: string;
15
52
  status: Status;
16
53
  provider: string;
54
+ /** The backend's own id for the sandbox; what direct access addresses. */
17
55
  externalId: string;
18
56
  state: SandboxState;
19
57
  image?: string;
@@ -23,8 +61,19 @@ interface SandboxInfo {
23
61
  persistent: boolean;
24
62
  createdAt: string;
25
63
  lastUsedAt: string;
64
+ /**
65
+ * When the sandbox times out. On `cube` it moves forward with every
66
+ * request the sandbox receives, and is absent once the sandbox was
67
+ * suspended through this API, until it runs again.
68
+ */
26
69
  expiresAt?: string;
27
70
  errorMessage?: string;
71
+ /**
72
+ * Direct-access address and credentials. Present on what `createSandbox`,
73
+ * `getSandbox` and `resumeSandbox` answer, on a backend with direct access.
74
+ * Never on `listSandboxes`, `extendSandbox` or `suspendSandbox`.
75
+ */
76
+ access?: SandboxAccess;
28
77
  }
29
78
  interface ListSandboxesOptions {
30
79
  metadata?: Record<string, string>;
@@ -56,7 +105,7 @@ interface CreateRunRequest {
56
105
  persistent?: boolean;
57
106
  sandboxTtlSeconds?: number;
58
107
  runtime?: SandboxRuntime;
59
- /** Backend to run on (`agent-sandbox`, `lambda-microvm`, `e2b`); the deployment's default when omitted. */
108
+ /** Backend to run on (`agent-sandbox`, `lambda-microvm`, `e2b`, `e2b-cluster`, `cube`); the deployment's default when omitted. */
60
109
  provider?: string;
61
110
  /**
62
111
  * Backend to try when `provider` does not deliver. Naming it is asking for
@@ -86,6 +135,14 @@ interface CreateSandboxRequest {
86
135
  snapshotId?: string;
87
136
  cpuSize?: number;
88
137
  memSize?: number;
138
+ /**
139
+ * Seconds until the sandbox times out and `onTimeout` applies. On `cube`
140
+ * they count idleness, not lifetime: every request the sandbox receives
141
+ * starts the count again, so a sandbox in use outlives them. And a `cube`
142
+ * sandbox that was suspended through the API and runs again counts the
143
+ * backend's default idle timeout (15 minutes unless the deployment sets
144
+ * `CUBE_DEFAULT_TIMEOUT_SECONDS`), not these.
145
+ */
89
146
  sandboxTtlSeconds?: number;
90
147
  files?: FileInput[];
91
148
  runtime?: SandboxRuntime;
@@ -95,6 +152,18 @@ interface CreateSandboxRequest {
95
152
  onTimeout?: SandboxOnTimeout;
96
153
  /** Backend to host it; the deployment's default when omitted. */
97
154
  provider?: string;
155
+ /**
156
+ * Seal the sandbox: no port answers a request without a token from
157
+ * `access`. On `e2b` and `e2b-cluster` the agent asks for
158
+ * `access.envdAccessToken` and every other port for
159
+ * `access.trafficAccessToken`; on `cube` there is no envd token and
160
+ * `access.trafficAccessToken` guards every port, the agent included. The
161
+ * API answers 409 on a backend that cannot (`lambda-microvm`,
162
+ * `agent-sandbox`), and 502 when the backend created the sandbox without
163
+ * a token that seals it (it is torn down). `e2b-cluster` and `cube` seal
164
+ * every sandbox whatever this says, `false` included.
165
+ */
166
+ privateTraffic?: boolean;
98
167
  }
99
168
  interface SnapshotRecipe {
100
169
  paths: string[];
@@ -222,6 +291,7 @@ interface SandboxCommands {
222
291
  }
223
292
 
224
293
  declare class Sandbox {
294
+ #private;
225
295
  private client;
226
296
  private auth;
227
297
  readonly sandboxId: string;
@@ -230,15 +300,34 @@ declare class Sandbox {
230
300
  private timeoutMs;
231
301
  private lastInfo?;
232
302
  constructor(client: SandboxClient, sandboxId: string, auth: AuthStrategy, info?: SandboxInfo);
303
+ /** The last descriptor the API answered, without `access`. */
233
304
  get info(): SandboxInfo | undefined;
305
+ /**
306
+ * Direct-access address and credentials, as last answered by create,
307
+ * `getInfo` or `resume`. `extend` and `suspend` do not answer them and do
308
+ * not erase them. `undefined` on a backend without direct access.
309
+ *
310
+ * The tokens are credentials: do not log what this returns.
311
+ */
312
+ get access(): SandboxAccess | undefined;
313
+ private remember;
234
314
  static create(client: SandboxClient, options?: CreateSandboxRequest): Promise<Sandbox>;
235
315
  static connect(client: SandboxClient, sandboxId: string): Promise<Sandbox>;
236
316
  private normalizeLanguage;
237
317
  runCode(script: string, options?: RunCodeOptions): Promise<ExecutionResult>;
238
318
  kill(): Promise<void>;
319
+ /** Reads the sandbox again; the answer carries `access` where the backend has it. */
239
320
  getInfo(): Promise<SandboxInfo>;
321
+ /**
322
+ * Gives the sandbox `ttlSeconds` from now; on `cube`, `ttlSeconds` of
323
+ * idleness, and nothing while the sandbox is suspended.
324
+ */
240
325
  extend(ttlSeconds: number): Promise<SandboxInfo>;
241
326
  suspend(): Promise<SandboxInfo>;
327
+ /**
328
+ * Resumes the sandbox. The answer carries `access` again, including the
329
+ * tokens a backend only hands out at creation, and `this.access` follows.
330
+ */
242
331
  resume(): Promise<SandboxInfo>;
243
332
  /**
244
333
  * Builds a reusable, pre-warmed image from this sandbox. Unlike `suspend`,
@@ -324,6 +413,44 @@ declare class DataTokenAuthStrategy implements AuthStrategy {
324
413
  constructor(dataToken: string);
325
414
  getHeaders(): Headers;
326
415
  }
416
+ declare const SERVICE_TOKEN_HEADER = "x-sandbox-service-token";
417
+ declare const SERVICE_WORKSPACE_HEADER = "x-sandbox-workspace-id";
418
+ /**
419
+ * A service acts in one workspace, named on every request: the API has no
420
+ * operation that spans workspaces for it. A `workspaceId` that is missing,
421
+ * `undefined` or empty is an error, never a wider request.
422
+ */
423
+ interface ServiceTokenAuthOptions {
424
+ /** The service token of this workload. Never a value a sandbox can read. */
425
+ serviceToken: string;
426
+ /** The workspace to act in. */
427
+ workspaceId: string;
428
+ }
429
+ /**
430
+ * Authenticates a workload that has no caller behind it, such as a worker
431
+ * pausing an idle sandbox or a reaper. The API accepts it on its internal
432
+ * address only, and only for the lifecycle of a sandbox (create, list, read,
433
+ * extend, suspend, resume and delete) and for a live snapshot of one (no
434
+ * recipe), reading that snapshot and deleting one. Running commands, files,
435
+ * runs, snapshot recipes and the snapshot listing through the API still need
436
+ * the data token of the workspace.
437
+ *
438
+ * On a backend with direct access, create, read and resume answer `access`
439
+ * to the service as to the owner, and with it the service drives the sandbox
440
+ * itself (commands, files, traffic): that is how agent-api's workloads reach
441
+ * the data plane. Treat the strategy as able to run code in the sandboxes of
442
+ * every workspace it names.
443
+ *
444
+ * A sandbox is reached in the workspace named here and answers 404 in any
445
+ * other, so build one strategy per workspace with `forWorkspace`.
446
+ */
447
+ declare class ServiceTokenAuthStrategy implements AuthStrategy {
448
+ #private;
449
+ constructor(options: ServiceTokenAuthOptions);
450
+ /** The same service acting in `workspaceId`, which must be a workspace id. */
451
+ forWorkspace(workspaceId: string): ServiceTokenAuthStrategy;
452
+ getHeaders(): Headers;
453
+ }
327
454
 
328
455
  declare class FetchError extends Error {
329
456
  readonly url: string;
@@ -420,5 +547,5 @@ declare function parseRunLifecycleEvent(raw: unknown): RunLifecycleEvent | null;
420
547
 
421
548
  declare function sandbox(config: SandboxConfig): SandboxClient;
422
549
 
423
- 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 };
424
- export type { AuthStrategy, CreateRunRequest, CreateSandboxRequest, CreateSnapshotRequest, ExecCommandOptions, ExecCommandResult, ExecutionResult, FileInput, LifecycleTopic, ListSandboxesOptions, RunCodeOptions, RunLifecycleEvent, RunLifecycleEventType, RunLifecycleSource, RunResponse, SandboxCommands, SandboxConfig, SandboxFiles, SandboxInfo, SandboxLifecycleEvent, SandboxLifecycleEventType, SandboxLifecycleSource, SandboxOnTimeout, SandboxRuntime, SandboxState, SnapshotInfo, SnapshotRecipe, Status, StreamCallbacks, StreamEvent };
550
+ 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, SERVICE_TOKEN_HEADER, SERVICE_WORKSPACE_HEADER, Sandbox, SandboxClient, SandboxRun, ServiceTokenAuthStrategy, isRunLifecycleEvent, isSandboxLifecycleEvent, lifecycleSchemaRegistryEnv, lifecycleSchemaSubject, lifecycleTopicEnv, parseRunLifecycleEvent, parseSandboxLifecycleEvent, runLifecycleTopicEnv, sandbox, sandboxLifecycleTopicEnv };
551
+ export type { AuthStrategy, CreateRunRequest, CreateSandboxRequest, CreateSnapshotRequest, ExecCommandOptions, ExecCommandResult, ExecutionResult, FileInput, LifecycleTopic, ListSandboxesOptions, RunCodeOptions, RunLifecycleEvent, RunLifecycleEventType, RunLifecycleSource, RunResponse, SandboxAccess, SandboxCommands, SandboxConfig, SandboxFiles, SandboxInfo, SandboxLifecycleEvent, SandboxLifecycleEventType, SandboxLifecycleSource, SandboxOnTimeout, SandboxRuntime, SandboxState, ServiceTokenAuthOptions, SnapshotInfo, SnapshotRecipe, Status, StreamCallbacks, StreamEvent };
package/dist/index.d.ts CHANGED
@@ -6,14 +6,52 @@ interface SandboxConfig {
6
6
  interface AuthStrategy {
7
7
  getHeaders: () => Headers;
8
8
  }
9
- declare const SANDBOX_RUNTIMES: readonly ["lambda-microvm", "agent-sandbox", "e2b"];
9
+ declare const SANDBOX_RUNTIMES: readonly ["lambda-microvm", "agent-sandbox", "e2b", "e2b-cluster", "cube"];
10
10
  type SandboxRuntime = (typeof SANDBOX_RUNTIMES)[number];
11
11
  type SandboxState = 'pending' | 'running' | 'suspended' | 'terminated' | 'failed';
12
12
  type SandboxOnTimeout = 'suspend' | 'terminate';
13
+ /**
14
+ * What it takes to talk to one sandbox directly, on the backend's data plane
15
+ * (commands, files, PTY, WebSocket), addressing it by `SandboxInfo.externalId`.
16
+ *
17
+ * `envdAccessToken` and `trafficAccessToken` are **credentials**: whoever holds
18
+ * them drives the sandbox. Keep them out of logs, traces and error messages.
19
+ *
20
+ * Only a backend with direct access returns this (`e2b`, `e2b-cluster` and
21
+ * `cube`; `lambda-microvm` and `agent-sandbox` never do), and only on create,
22
+ * get and resume. Every field is optional because backends differ.
23
+ */
24
+ interface SandboxAccess {
25
+ /**
26
+ * Sent as `X-Access-Token` to the in-sandbox agent (envd). Never present
27
+ * on `cube`, where the agent asks for `trafficAccessToken` instead.
28
+ */
29
+ envdAccessToken?: string;
30
+ /**
31
+ * Sent as `e2b-traffic-access-token` to every other port; on `cube` to
32
+ * every port, the agent included. On `e2b` it exists only for a sandbox
33
+ * created with `privateTraffic`; on `e2b-cluster` and `cube` every sandbox
34
+ * has one.
35
+ */
36
+ trafficAccessToken?: string;
37
+ /**
38
+ * Base URL of the backend's sandbox proxy, when one address serves every
39
+ * sandbox and routes by the `E2b-Sandbox-Id` and `E2b-Sandbox-Port` headers.
40
+ */
41
+ sandboxUrl?: string;
42
+ /**
43
+ * Domain the ports are published under, as
44
+ * `<port>-<externalId>.<sandboxDomain>`. Used when `sandboxUrl` is absent.
45
+ */
46
+ sandboxDomain?: string;
47
+ /** Version of the in-sandbox agent. */
48
+ envdVersion?: string;
49
+ }
13
50
  interface SandboxInfo {
14
51
  sandboxId: string;
15
52
  status: Status;
16
53
  provider: string;
54
+ /** The backend's own id for the sandbox; what direct access addresses. */
17
55
  externalId: string;
18
56
  state: SandboxState;
19
57
  image?: string;
@@ -23,8 +61,19 @@ interface SandboxInfo {
23
61
  persistent: boolean;
24
62
  createdAt: string;
25
63
  lastUsedAt: string;
64
+ /**
65
+ * When the sandbox times out. On `cube` it moves forward with every
66
+ * request the sandbox receives, and is absent once the sandbox was
67
+ * suspended through this API, until it runs again.
68
+ */
26
69
  expiresAt?: string;
27
70
  errorMessage?: string;
71
+ /**
72
+ * Direct-access address and credentials. Present on what `createSandbox`,
73
+ * `getSandbox` and `resumeSandbox` answer, on a backend with direct access.
74
+ * Never on `listSandboxes`, `extendSandbox` or `suspendSandbox`.
75
+ */
76
+ access?: SandboxAccess;
28
77
  }
29
78
  interface ListSandboxesOptions {
30
79
  metadata?: Record<string, string>;
@@ -56,7 +105,7 @@ interface CreateRunRequest {
56
105
  persistent?: boolean;
57
106
  sandboxTtlSeconds?: number;
58
107
  runtime?: SandboxRuntime;
59
- /** Backend to run on (`agent-sandbox`, `lambda-microvm`, `e2b`); the deployment's default when omitted. */
108
+ /** Backend to run on (`agent-sandbox`, `lambda-microvm`, `e2b`, `e2b-cluster`, `cube`); the deployment's default when omitted. */
60
109
  provider?: string;
61
110
  /**
62
111
  * Backend to try when `provider` does not deliver. Naming it is asking for
@@ -86,6 +135,14 @@ interface CreateSandboxRequest {
86
135
  snapshotId?: string;
87
136
  cpuSize?: number;
88
137
  memSize?: number;
138
+ /**
139
+ * Seconds until the sandbox times out and `onTimeout` applies. On `cube`
140
+ * they count idleness, not lifetime: every request the sandbox receives
141
+ * starts the count again, so a sandbox in use outlives them. And a `cube`
142
+ * sandbox that was suspended through the API and runs again counts the
143
+ * backend's default idle timeout (15 minutes unless the deployment sets
144
+ * `CUBE_DEFAULT_TIMEOUT_SECONDS`), not these.
145
+ */
89
146
  sandboxTtlSeconds?: number;
90
147
  files?: FileInput[];
91
148
  runtime?: SandboxRuntime;
@@ -95,6 +152,18 @@ interface CreateSandboxRequest {
95
152
  onTimeout?: SandboxOnTimeout;
96
153
  /** Backend to host it; the deployment's default when omitted. */
97
154
  provider?: string;
155
+ /**
156
+ * Seal the sandbox: no port answers a request without a token from
157
+ * `access`. On `e2b` and `e2b-cluster` the agent asks for
158
+ * `access.envdAccessToken` and every other port for
159
+ * `access.trafficAccessToken`; on `cube` there is no envd token and
160
+ * `access.trafficAccessToken` guards every port, the agent included. The
161
+ * API answers 409 on a backend that cannot (`lambda-microvm`,
162
+ * `agent-sandbox`), and 502 when the backend created the sandbox without
163
+ * a token that seals it (it is torn down). `e2b-cluster` and `cube` seal
164
+ * every sandbox whatever this says, `false` included.
165
+ */
166
+ privateTraffic?: boolean;
98
167
  }
99
168
  interface SnapshotRecipe {
100
169
  paths: string[];
@@ -222,6 +291,7 @@ interface SandboxCommands {
222
291
  }
223
292
 
224
293
  declare class Sandbox {
294
+ #private;
225
295
  private client;
226
296
  private auth;
227
297
  readonly sandboxId: string;
@@ -230,15 +300,34 @@ declare class Sandbox {
230
300
  private timeoutMs;
231
301
  private lastInfo?;
232
302
  constructor(client: SandboxClient, sandboxId: string, auth: AuthStrategy, info?: SandboxInfo);
303
+ /** The last descriptor the API answered, without `access`. */
233
304
  get info(): SandboxInfo | undefined;
305
+ /**
306
+ * Direct-access address and credentials, as last answered by create,
307
+ * `getInfo` or `resume`. `extend` and `suspend` do not answer them and do
308
+ * not erase them. `undefined` on a backend without direct access.
309
+ *
310
+ * The tokens are credentials: do not log what this returns.
311
+ */
312
+ get access(): SandboxAccess | undefined;
313
+ private remember;
234
314
  static create(client: SandboxClient, options?: CreateSandboxRequest): Promise<Sandbox>;
235
315
  static connect(client: SandboxClient, sandboxId: string): Promise<Sandbox>;
236
316
  private normalizeLanguage;
237
317
  runCode(script: string, options?: RunCodeOptions): Promise<ExecutionResult>;
238
318
  kill(): Promise<void>;
319
+ /** Reads the sandbox again; the answer carries `access` where the backend has it. */
239
320
  getInfo(): Promise<SandboxInfo>;
321
+ /**
322
+ * Gives the sandbox `ttlSeconds` from now; on `cube`, `ttlSeconds` of
323
+ * idleness, and nothing while the sandbox is suspended.
324
+ */
240
325
  extend(ttlSeconds: number): Promise<SandboxInfo>;
241
326
  suspend(): Promise<SandboxInfo>;
327
+ /**
328
+ * Resumes the sandbox. The answer carries `access` again, including the
329
+ * tokens a backend only hands out at creation, and `this.access` follows.
330
+ */
242
331
  resume(): Promise<SandboxInfo>;
243
332
  /**
244
333
  * Builds a reusable, pre-warmed image from this sandbox. Unlike `suspend`,
@@ -324,6 +413,44 @@ declare class DataTokenAuthStrategy implements AuthStrategy {
324
413
  constructor(dataToken: string);
325
414
  getHeaders(): Headers;
326
415
  }
416
+ declare const SERVICE_TOKEN_HEADER = "x-sandbox-service-token";
417
+ declare const SERVICE_WORKSPACE_HEADER = "x-sandbox-workspace-id";
418
+ /**
419
+ * A service acts in one workspace, named on every request: the API has no
420
+ * operation that spans workspaces for it. A `workspaceId` that is missing,
421
+ * `undefined` or empty is an error, never a wider request.
422
+ */
423
+ interface ServiceTokenAuthOptions {
424
+ /** The service token of this workload. Never a value a sandbox can read. */
425
+ serviceToken: string;
426
+ /** The workspace to act in. */
427
+ workspaceId: string;
428
+ }
429
+ /**
430
+ * Authenticates a workload that has no caller behind it, such as a worker
431
+ * pausing an idle sandbox or a reaper. The API accepts it on its internal
432
+ * address only, and only for the lifecycle of a sandbox (create, list, read,
433
+ * extend, suspend, resume and delete) and for a live snapshot of one (no
434
+ * recipe), reading that snapshot and deleting one. Running commands, files,
435
+ * runs, snapshot recipes and the snapshot listing through the API still need
436
+ * the data token of the workspace.
437
+ *
438
+ * On a backend with direct access, create, read and resume answer `access`
439
+ * to the service as to the owner, and with it the service drives the sandbox
440
+ * itself (commands, files, traffic): that is how agent-api's workloads reach
441
+ * the data plane. Treat the strategy as able to run code in the sandboxes of
442
+ * every workspace it names.
443
+ *
444
+ * A sandbox is reached in the workspace named here and answers 404 in any
445
+ * other, so build one strategy per workspace with `forWorkspace`.
446
+ */
447
+ declare class ServiceTokenAuthStrategy implements AuthStrategy {
448
+ #private;
449
+ constructor(options: ServiceTokenAuthOptions);
450
+ /** The same service acting in `workspaceId`, which must be a workspace id. */
451
+ forWorkspace(workspaceId: string): ServiceTokenAuthStrategy;
452
+ getHeaders(): Headers;
453
+ }
327
454
 
328
455
  declare class FetchError extends Error {
329
456
  readonly url: string;
@@ -420,5 +547,5 @@ declare function parseRunLifecycleEvent(raw: unknown): RunLifecycleEvent | null;
420
547
 
421
548
  declare function sandbox(config: SandboxConfig): SandboxClient;
422
549
 
423
- 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 };
424
- export type { AuthStrategy, CreateRunRequest, CreateSandboxRequest, CreateSnapshotRequest, ExecCommandOptions, ExecCommandResult, ExecutionResult, FileInput, LifecycleTopic, ListSandboxesOptions, RunCodeOptions, RunLifecycleEvent, RunLifecycleEventType, RunLifecycleSource, RunResponse, SandboxCommands, SandboxConfig, SandboxFiles, SandboxInfo, SandboxLifecycleEvent, SandboxLifecycleEventType, SandboxLifecycleSource, SandboxOnTimeout, SandboxRuntime, SandboxState, SnapshotInfo, SnapshotRecipe, Status, StreamCallbacks, StreamEvent };
550
+ 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, SERVICE_TOKEN_HEADER, SERVICE_WORKSPACE_HEADER, Sandbox, SandboxClient, SandboxRun, ServiceTokenAuthStrategy, isRunLifecycleEvent, isSandboxLifecycleEvent, lifecycleSchemaRegistryEnv, lifecycleSchemaSubject, lifecycleTopicEnv, parseRunLifecycleEvent, parseSandboxLifecycleEvent, runLifecycleTopicEnv, sandbox, sandboxLifecycleTopicEnv };
551
+ export type { AuthStrategy, CreateRunRequest, CreateSandboxRequest, CreateSnapshotRequest, ExecCommandOptions, ExecCommandResult, ExecutionResult, FileInput, LifecycleTopic, ListSandboxesOptions, RunCodeOptions, RunLifecycleEvent, RunLifecycleEventType, RunLifecycleSource, RunResponse, SandboxAccess, SandboxCommands, SandboxConfig, SandboxFiles, SandboxInfo, SandboxLifecycleEvent, SandboxLifecycleEventType, SandboxLifecycleSource, SandboxOnTimeout, SandboxRuntime, SandboxState, ServiceTokenAuthOptions, SnapshotInfo, SnapshotRecipe, 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", "agent-sandbox", "e2b"];
4
+ const SANDBOX_RUNTIMES = ["lambda-microvm", "agent-sandbox", "e2b", "e2b-cluster", "cube"];
5
5
 
6
6
  class FetchError extends Error {
7
7
  constructor(message, url, method, status, response) {
@@ -69,6 +69,25 @@ var __publicField$2 = (obj, key, value) => {
69
69
  __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
70
70
  return value;
71
71
  };
72
+ var __accessCheck$1 = (obj, member, msg) => {
73
+ if (!member.has(obj))
74
+ throw TypeError("Cannot " + msg);
75
+ };
76
+ var __privateGet$1 = (obj, member, getter) => {
77
+ __accessCheck$1(obj, member, "read from private field");
78
+ return getter ? getter.call(obj) : member.get(obj);
79
+ };
80
+ var __privateAdd$1 = (obj, member, value) => {
81
+ if (member.has(obj))
82
+ throw TypeError("Cannot add the same private member more than once");
83
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
84
+ };
85
+ var __privateSet$1 = (obj, member, value, setter) => {
86
+ __accessCheck$1(obj, member, "write to private field");
87
+ setter ? setter.call(obj, value) : member.set(obj, value);
88
+ return value;
89
+ };
90
+ var _access;
72
91
  class Sandbox {
73
92
  constructor(client, sandboxId, auth, info) {
74
93
  this.client = client;
@@ -78,8 +97,11 @@ class Sandbox {
78
97
  __publicField$2(this, "commands");
79
98
  __publicField$2(this, "timeoutMs", 3e5);
80
99
  __publicField$2(this, "lastInfo");
100
+ // A `#private` field, unlike `lastInfo`: it holds credentials, and this
101
+ // keeps them out of `JSON.stringify(sandbox)` and of `console.log(sandbox)`.
102
+ __privateAdd$1(this, _access, void 0);
81
103
  this.sandboxId = sandboxId;
82
- this.lastInfo = info;
104
+ this.remember(info);
83
105
  const readFile = async (path, options) => {
84
106
  return await this.client.readFile(sandboxId, path, options);
85
107
  };
@@ -95,9 +117,30 @@ class Sandbox {
95
117
  run: async (command, options) => await this.client.execCommand(sandboxId, command, options)
96
118
  };
97
119
  }
120
+ /** The last descriptor the API answered, without `access`. */
98
121
  get info() {
99
122
  return this.lastInfo;
100
123
  }
124
+ /**
125
+ * Direct-access address and credentials, as last answered by create,
126
+ * `getInfo` or `resume`. `extend` and `suspend` do not answer them and do
127
+ * not erase them. `undefined` on a backend without direct access.
128
+ *
129
+ * The tokens are credentials: do not log what this returns.
130
+ */
131
+ get access() {
132
+ return __privateGet$1(this, _access);
133
+ }
134
+ remember(info) {
135
+ if (!info) {
136
+ return;
137
+ }
138
+ const { access, ...rest } = info;
139
+ this.lastInfo = rest;
140
+ if (access) {
141
+ __privateSet$1(this, _access, access);
142
+ }
143
+ }
101
144
  // Factory methods (static)
102
145
  static async create(client, options = {}) {
103
146
  return await client.createSandbox(options);
@@ -168,21 +211,34 @@ class Sandbox {
168
211
  }
169
212
  }
170
213
  }
214
+ /** Reads the sandbox again; the answer carries `access` where the backend has it. */
171
215
  async getInfo() {
172
- this.lastInfo = await this.client.getSandbox(this.sandboxId);
173
- return this.lastInfo;
216
+ const info = await this.client.getSandbox(this.sandboxId);
217
+ this.remember(info);
218
+ return info;
174
219
  }
220
+ /**
221
+ * Gives the sandbox `ttlSeconds` from now; on `cube`, `ttlSeconds` of
222
+ * idleness, and nothing while the sandbox is suspended.
223
+ */
175
224
  async extend(ttlSeconds) {
176
- this.lastInfo = await this.client.extendSandbox(this.sandboxId, ttlSeconds);
177
- return this.lastInfo;
225
+ const info = await this.client.extendSandbox(this.sandboxId, ttlSeconds);
226
+ this.remember(info);
227
+ return info;
178
228
  }
179
229
  async suspend() {
180
- this.lastInfo = await this.client.suspendSandbox(this.sandboxId);
181
- return this.lastInfo;
230
+ const info = await this.client.suspendSandbox(this.sandboxId);
231
+ this.remember(info);
232
+ return info;
182
233
  }
234
+ /**
235
+ * Resumes the sandbox. The answer carries `access` again, including the
236
+ * tokens a backend only hands out at creation, and `this.access` follows.
237
+ */
183
238
  async resume() {
184
- this.lastInfo = await this.client.resumeSandbox(this.sandboxId);
185
- return this.lastInfo;
239
+ const info = await this.client.resumeSandbox(this.sandboxId);
240
+ this.remember(info);
241
+ return info;
186
242
  }
187
243
  /**
188
244
  * Builds a reusable, pre-warmed image from this sandbox. Unlike `suspend`,
@@ -198,6 +254,7 @@ class Sandbox {
198
254
  this.timeoutMs = ms;
199
255
  }
200
256
  }
257
+ _access = new WeakMap();
201
258
 
202
259
  var __defProp$1 = Object.defineProperty;
203
260
  var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
@@ -617,6 +674,25 @@ class SandboxClient {
617
674
  }
618
675
  }
619
676
 
677
+ var __accessCheck = (obj, member, msg) => {
678
+ if (!member.has(obj))
679
+ throw TypeError("Cannot " + msg);
680
+ };
681
+ var __privateGet = (obj, member, getter) => {
682
+ __accessCheck(obj, member, "read from private field");
683
+ return getter ? getter.call(obj) : member.get(obj);
684
+ };
685
+ var __privateAdd = (obj, member, value) => {
686
+ if (member.has(obj))
687
+ throw TypeError("Cannot add the same private member more than once");
688
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
689
+ };
690
+ var __privateSet = (obj, member, value, setter) => {
691
+ __accessCheck(obj, member, "write to private field");
692
+ setter ? setter.call(obj, value) : member.set(obj, value);
693
+ return value;
694
+ };
695
+ var _serviceToken, _workspaceId;
620
696
  class DataTokenAuthStrategy {
621
697
  constructor(dataToken) {
622
698
  this.dataToken = dataToken;
@@ -627,6 +703,41 @@ class DataTokenAuthStrategy {
627
703
  });
628
704
  }
629
705
  }
706
+ const SERVICE_TOKEN_HEADER = "x-sandbox-service-token";
707
+ const SERVICE_WORKSPACE_HEADER = "x-sandbox-workspace-id";
708
+ function assertWorkspaceId(workspaceId) {
709
+ if (typeof workspaceId !== "string" || workspaceId.trim() === "") {
710
+ throw new Error("ServiceTokenAuthStrategy needs a non-empty workspaceId");
711
+ }
712
+ }
713
+ const _ServiceTokenAuthStrategy = class _ServiceTokenAuthStrategy {
714
+ constructor(options) {
715
+ // Private fields, so the token is not part of what a logger or
716
+ // JSON.stringify prints when handed the strategy or the client holding it.
717
+ __privateAdd(this, _serviceToken, void 0);
718
+ __privateAdd(this, _workspaceId, void 0);
719
+ if (!options.serviceToken) {
720
+ throw new Error("ServiceTokenAuthStrategy needs a service token");
721
+ }
722
+ assertWorkspaceId(options.workspaceId);
723
+ __privateSet(this, _serviceToken, options.serviceToken);
724
+ __privateSet(this, _workspaceId, options.workspaceId);
725
+ }
726
+ /** The same service acting in `workspaceId`, which must be a workspace id. */
727
+ forWorkspace(workspaceId) {
728
+ assertWorkspaceId(workspaceId);
729
+ return new _ServiceTokenAuthStrategy({ serviceToken: __privateGet(this, _serviceToken), workspaceId });
730
+ }
731
+ getHeaders() {
732
+ return new Headers({
733
+ [SERVICE_TOKEN_HEADER]: __privateGet(this, _serviceToken),
734
+ [SERVICE_WORKSPACE_HEADER]: __privateGet(this, _workspaceId)
735
+ });
736
+ }
737
+ };
738
+ _serviceToken = new WeakMap();
739
+ _workspaceId = new WeakMap();
740
+ let ServiceTokenAuthStrategy = _ServiceTokenAuthStrategy;
630
741
 
631
742
  const SANDBOX_LIFECYCLE_TOPIC = "sandbox-lifecycle";
632
743
  const RUN_LIFECYCLE_TOPIC = "run-lifecycle";
@@ -711,4 +822,4 @@ function sandbox(config) {
711
822
  return new SandboxClient(config);
712
823
  }
713
824
 
714
- 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 };
825
+ 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, SERVICE_TOKEN_HEADER, SERVICE_WORKSPACE_HEADER, Sandbox, SandboxClient, SandboxRun, ServiceTokenAuthStrategy, isRunLifecycleEvent, isSandboxLifecycleEvent, lifecycleSchemaRegistryEnv, lifecycleSchemaSubject, lifecycleTopicEnv, parseRunLifecycleEvent, parseSandboxLifecycleEvent, runLifecycleTopicEnv, sandbox, sandboxLifecycleTopicEnv };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@meistrari/sandbox-sdk",
3
- "version": "1.7.0",
3
+ "version": "1.9.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {