@meistrari/sandbox-sdk 1.6.1 → 1.8.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
@@ -254,6 +254,51 @@ 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` today), 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
+ - **Both 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
+ - Without `privateTraffic` there is no `trafficAccessToken` and the sandbox's
295
+ 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
+ - A backend that creates a sandbox asked for with `privateTraffic` without one
299
+ of the tokens that seal it is a 502, and the sandbox is torn down: a sealed
300
+ create never returns an open sandbox. Do not retry it.
301
+
257
302
  ## API Reference
258
303
 
259
304
  ### `sandbox(config)`
@@ -289,6 +334,8 @@ const client = sandbox({
289
334
  | Property | Type | Description |
290
335
  |----------|------|-------------|
291
336
  | `sandboxId` | `string` | Unique sandbox identifier |
337
+ | `info` | `SandboxInfo \| undefined` | Last descriptor the API answered, without `access` |
338
+ | `access` | `SandboxAccess \| undefined` | Direct-access address and tokens; see [Direct Access](#direct-access) |
292
339
  | `files` | `SandboxFiles` | File operations interface |
293
340
  | `commands` | `SandboxCommands` | Command execution interface |
294
341
 
@@ -377,6 +424,41 @@ await sandbox.runCode(code, { onStdout: ({ line }) => console.log(line) })
377
424
  await sandbox.kill()
378
425
  ```
379
426
 
427
+ ## Service token
428
+
429
+ For a workload with no caller behind it (a worker pausing an idle sandbox, a
430
+ reaper). The API accepts it on its internal address only, and only for the
431
+ lifecycle of a sandbox (create, list, read, extend, suspend, resume and
432
+ delete) and for a live snapshot of one (no `recipe`), reading that snapshot
433
+ and deleting one. Commands, files, runs, snapshot recipes and the snapshot
434
+ listing through the API still need the data token of the workspace.
435
+
436
+ That does not keep a service from running code. On a backend with direct
437
+ access (`e2b`), create, `connectToSandbox` and resume give the service the
438
+ sandbox's `access`, as they give the owner, and with it the service runs
439
+ commands, files and traffic against the sandbox directly: that is how
440
+ agent-api drives the data plane. A service token can run code in every
441
+ sandbox of every workspace it names.
442
+
443
+ ```javascript
444
+ import { sandbox, ServiceTokenAuthStrategy } from '@meistrari/sandbox-sdk'
445
+
446
+ const service = new ServiceTokenAuthStrategy({ serviceToken: process.env.SANDBOX_API_SERVICE_TOKEN, workspaceId })
447
+
448
+ // Every call acts in that workspace, the listing included; a sandbox of another one answers 404.
449
+ const client = sandbox({ apiUrl, auth: service })
450
+ const found = await client.listSandboxes({ metadata: { sessionId } })
451
+ const box = await client.connectToSandbox(found[0].sandboxId)
452
+ await box.suspend()
453
+
454
+ // Another workspace, another strategy.
455
+ const other = sandbox({ apiUrl, auth: service.forWorkspace(otherWorkspaceId) })
456
+ ```
457
+
458
+ 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.
459
+
460
+ Never pass the service token into a sandbox (env, files or metadata).
461
+
380
462
  ## Error Handling
381
463
 
382
464
  ```typescript
package/dist/index.cjs CHANGED
@@ -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,30 @@ 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
  }
177
222
  async extend(ttlSeconds) {
178
- this.lastInfo = await this.client.extendSandbox(this.sandboxId, ttlSeconds);
179
- return this.lastInfo;
223
+ const info = await this.client.extendSandbox(this.sandboxId, ttlSeconds);
224
+ this.remember(info);
225
+ return info;
180
226
  }
181
227
  async suspend() {
182
- this.lastInfo = await this.client.suspendSandbox(this.sandboxId);
183
- return this.lastInfo;
228
+ const info = await this.client.suspendSandbox(this.sandboxId);
229
+ this.remember(info);
230
+ return info;
184
231
  }
232
+ /**
233
+ * Resumes the sandbox. The answer carries `access` again, including the
234
+ * tokens a backend only hands out at creation, and `this.access` follows.
235
+ */
185
236
  async resume() {
186
- this.lastInfo = await this.client.resumeSandbox(this.sandboxId);
187
- return this.lastInfo;
237
+ const info = await this.client.resumeSandbox(this.sandboxId);
238
+ this.remember(info);
239
+ return info;
188
240
  }
189
241
  /**
190
242
  * Builds a reusable, pre-warmed image from this sandbox. Unlike `suspend`,
@@ -200,6 +252,7 @@ class Sandbox {
200
252
  this.timeoutMs = ms;
201
253
  }
202
254
  }
255
+ _access = new WeakMap();
203
256
 
204
257
  var __defProp$1 = Object.defineProperty;
205
258
  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 +672,25 @@ class SandboxClient {
619
672
  }
620
673
  }
621
674
 
675
+ var __accessCheck = (obj, member, msg) => {
676
+ if (!member.has(obj))
677
+ throw TypeError("Cannot " + msg);
678
+ };
679
+ var __privateGet = (obj, member, getter) => {
680
+ __accessCheck(obj, member, "read from private field");
681
+ return getter ? getter.call(obj) : member.get(obj);
682
+ };
683
+ var __privateAdd = (obj, member, value) => {
684
+ if (member.has(obj))
685
+ throw TypeError("Cannot add the same private member more than once");
686
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
687
+ };
688
+ var __privateSet = (obj, member, value, setter) => {
689
+ __accessCheck(obj, member, "write to private field");
690
+ setter ? setter.call(obj, value) : member.set(obj, value);
691
+ return value;
692
+ };
693
+ var _serviceToken, _workspaceId;
622
694
  class DataTokenAuthStrategy {
623
695
  constructor(dataToken) {
624
696
  this.dataToken = dataToken;
@@ -629,6 +701,41 @@ class DataTokenAuthStrategy {
629
701
  });
630
702
  }
631
703
  }
704
+ const SERVICE_TOKEN_HEADER = "x-sandbox-service-token";
705
+ const SERVICE_WORKSPACE_HEADER = "x-sandbox-workspace-id";
706
+ function assertWorkspaceId(workspaceId) {
707
+ if (typeof workspaceId !== "string" || workspaceId.trim() === "") {
708
+ throw new Error("ServiceTokenAuthStrategy needs a non-empty workspaceId");
709
+ }
710
+ }
711
+ const _ServiceTokenAuthStrategy = class _ServiceTokenAuthStrategy {
712
+ constructor(options) {
713
+ // Private fields, so the token is not part of what a logger or
714
+ // JSON.stringify prints when handed the strategy or the client holding it.
715
+ __privateAdd(this, _serviceToken, void 0);
716
+ __privateAdd(this, _workspaceId, void 0);
717
+ if (!options.serviceToken) {
718
+ throw new Error("ServiceTokenAuthStrategy needs a service token");
719
+ }
720
+ assertWorkspaceId(options.workspaceId);
721
+ __privateSet(this, _serviceToken, options.serviceToken);
722
+ __privateSet(this, _workspaceId, options.workspaceId);
723
+ }
724
+ /** The same service acting in `workspaceId`, which must be a workspace id. */
725
+ forWorkspace(workspaceId) {
726
+ assertWorkspaceId(workspaceId);
727
+ return new _ServiceTokenAuthStrategy({ serviceToken: __privateGet(this, _serviceToken), workspaceId });
728
+ }
729
+ getHeaders() {
730
+ return new Headers({
731
+ [SERVICE_TOKEN_HEADER]: __privateGet(this, _serviceToken),
732
+ [SERVICE_WORKSPACE_HEADER]: __privateGet(this, _workspaceId)
733
+ });
734
+ }
735
+ };
736
+ _serviceToken = new WeakMap();
737
+ _workspaceId = new WeakMap();
738
+ let ServiceTokenAuthStrategy = _ServiceTokenAuthStrategy;
632
739
 
633
740
  const SANDBOX_LIFECYCLE_TOPIC = "sandbox-lifecycle";
634
741
  const RUN_LIFECYCLE_TOPIC = "run-lifecycle";
@@ -722,9 +829,12 @@ exports.SANDBOX_LIFECYCLE_EVENT_TYPES = SANDBOX_LIFECYCLE_EVENT_TYPES;
722
829
  exports.SANDBOX_LIFECYCLE_ITEM = SANDBOX_LIFECYCLE_ITEM;
723
830
  exports.SANDBOX_LIFECYCLE_TOPIC = SANDBOX_LIFECYCLE_TOPIC;
724
831
  exports.SANDBOX_RUNTIMES = SANDBOX_RUNTIMES;
832
+ exports.SERVICE_TOKEN_HEADER = SERVICE_TOKEN_HEADER;
833
+ exports.SERVICE_WORKSPACE_HEADER = SERVICE_WORKSPACE_HEADER;
725
834
  exports.Sandbox = Sandbox;
726
835
  exports.SandboxClient = SandboxClient;
727
836
  exports.SandboxRun = SandboxRun;
837
+ exports.ServiceTokenAuthStrategy = ServiceTokenAuthStrategy;
728
838
  exports.isRunLifecycleEvent = isRunLifecycleEvent;
729
839
  exports.isSandboxLifecycleEvent = isSandboxLifecycleEvent;
730
840
  exports.lifecycleSchemaRegistryEnv = lifecycleSchemaRegistryEnv;
package/dist/index.d.cts CHANGED
@@ -10,10 +10,43 @@ declare const SANDBOX_RUNTIMES: readonly ["lambda-microvm", "agent-sandbox", "e2
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` today;
21
+ * `lambda-microvm` and `agent-sandbox` never do), and only on create, get and
22
+ * resume. Every field is optional because backends differ.
23
+ */
24
+ interface SandboxAccess {
25
+ /** Sent as `X-Access-Token` to the in-sandbox agent (envd). */
26
+ envdAccessToken?: string;
27
+ /**
28
+ * Sent as `e2b-traffic-access-token` to every other port. Exists only for a
29
+ * sandbox created with `privateTraffic`.
30
+ */
31
+ trafficAccessToken?: string;
32
+ /**
33
+ * Base URL of the backend's sandbox proxy, when one address serves every
34
+ * sandbox and routes by the `E2b-Sandbox-Id` and `E2b-Sandbox-Port` headers.
35
+ */
36
+ sandboxUrl?: string;
37
+ /**
38
+ * Domain the ports are published under, as
39
+ * `<port>-<externalId>.<sandboxDomain>`. Used when `sandboxUrl` is absent.
40
+ */
41
+ sandboxDomain?: string;
42
+ /** Version of the in-sandbox agent. */
43
+ envdVersion?: string;
44
+ }
13
45
  interface SandboxInfo {
14
46
  sandboxId: string;
15
47
  status: Status;
16
48
  provider: string;
49
+ /** The backend's own id for the sandbox; what direct access addresses. */
17
50
  externalId: string;
18
51
  state: SandboxState;
19
52
  image?: string;
@@ -25,6 +58,12 @@ interface SandboxInfo {
25
58
  lastUsedAt: string;
26
59
  expiresAt?: string;
27
60
  errorMessage?: string;
61
+ /**
62
+ * Direct-access address and credentials. Present on what `createSandbox`,
63
+ * `getSandbox` and `resumeSandbox` answer, on a backend with direct access.
64
+ * Never on `listSandboxes`, `extendSandbox` or `suspendSandbox`.
65
+ */
66
+ access?: SandboxAccess;
28
67
  }
29
68
  interface ListSandboxesOptions {
30
69
  metadata?: Record<string, string>;
@@ -95,6 +134,14 @@ interface CreateSandboxRequest {
95
134
  onTimeout?: SandboxOnTimeout;
96
135
  /** Backend to host it; the deployment's default when omitted. */
97
136
  provider?: string;
137
+ /**
138
+ * Seal the sandbox: its agent answers only requests carrying
139
+ * `access.envdAccessToken`, every other port only requests carrying
140
+ * `access.trafficAccessToken`. The API answers 409 on a backend that
141
+ * cannot (`lambda-microvm`, `agent-sandbox`), and 502 when the backend
142
+ * created the sandbox without one of those tokens (it is torn down).
143
+ */
144
+ privateTraffic?: boolean;
98
145
  }
99
146
  interface SnapshotRecipe {
100
147
  paths: string[];
@@ -108,7 +155,8 @@ interface SnapshotRecipe {
108
155
  interface CreateSnapshotRequest {
109
156
  name: string;
110
157
  idempotencyKey: string;
111
- recipe: SnapshotRecipe;
158
+ /** Required by lambda-microvm, which builds an image from it; not used by e2b, which captures the live sandbox. */
159
+ recipe?: SnapshotRecipe;
112
160
  metadata?: Record<string, string>;
113
161
  }
114
162
  interface SnapshotInfo {
@@ -221,6 +269,7 @@ interface SandboxCommands {
221
269
  }
222
270
 
223
271
  declare class Sandbox {
272
+ #private;
224
273
  private client;
225
274
  private auth;
226
275
  readonly sandboxId: string;
@@ -229,15 +278,30 @@ declare class Sandbox {
229
278
  private timeoutMs;
230
279
  private lastInfo?;
231
280
  constructor(client: SandboxClient, sandboxId: string, auth: AuthStrategy, info?: SandboxInfo);
281
+ /** The last descriptor the API answered, without `access`. */
232
282
  get info(): SandboxInfo | undefined;
283
+ /**
284
+ * Direct-access address and credentials, as last answered by create,
285
+ * `getInfo` or `resume`. `extend` and `suspend` do not answer them and do
286
+ * not erase them. `undefined` on a backend without direct access.
287
+ *
288
+ * The tokens are credentials: do not log what this returns.
289
+ */
290
+ get access(): SandboxAccess | undefined;
291
+ private remember;
233
292
  static create(client: SandboxClient, options?: CreateSandboxRequest): Promise<Sandbox>;
234
293
  static connect(client: SandboxClient, sandboxId: string): Promise<Sandbox>;
235
294
  private normalizeLanguage;
236
295
  runCode(script: string, options?: RunCodeOptions): Promise<ExecutionResult>;
237
296
  kill(): Promise<void>;
297
+ /** Reads the sandbox again; the answer carries `access` where the backend has it. */
238
298
  getInfo(): Promise<SandboxInfo>;
239
299
  extend(ttlSeconds: number): Promise<SandboxInfo>;
240
300
  suspend(): Promise<SandboxInfo>;
301
+ /**
302
+ * Resumes the sandbox. The answer carries `access` again, including the
303
+ * tokens a backend only hands out at creation, and `this.access` follows.
304
+ */
241
305
  resume(): Promise<SandboxInfo>;
242
306
  /**
243
307
  * Builds a reusable, pre-warmed image from this sandbox. Unlike `suspend`,
@@ -323,6 +387,44 @@ declare class DataTokenAuthStrategy implements AuthStrategy {
323
387
  constructor(dataToken: string);
324
388
  getHeaders(): Headers;
325
389
  }
390
+ declare const SERVICE_TOKEN_HEADER = "x-sandbox-service-token";
391
+ declare const SERVICE_WORKSPACE_HEADER = "x-sandbox-workspace-id";
392
+ /**
393
+ * A service acts in one workspace, named on every request: the API has no
394
+ * operation that spans workspaces for it. A `workspaceId` that is missing,
395
+ * `undefined` or empty is an error, never a wider request.
396
+ */
397
+ interface ServiceTokenAuthOptions {
398
+ /** The service token of this workload. Never a value a sandbox can read. */
399
+ serviceToken: string;
400
+ /** The workspace to act in. */
401
+ workspaceId: string;
402
+ }
403
+ /**
404
+ * Authenticates a workload that has no caller behind it, such as a worker
405
+ * pausing an idle sandbox or a reaper. The API accepts it on its internal
406
+ * address only, and only for the lifecycle of a sandbox (create, list, read,
407
+ * extend, suspend, resume and delete) and for a live snapshot of one (no
408
+ * recipe), reading that snapshot and deleting one. Running commands, files,
409
+ * runs, snapshot recipes and the snapshot listing through the API still need
410
+ * the data token of the workspace.
411
+ *
412
+ * On a backend with direct access, create, read and resume answer `access`
413
+ * to the service as to the owner, and with it the service drives the sandbox
414
+ * itself (commands, files, traffic): that is how agent-api's workloads reach
415
+ * the data plane. Treat the strategy as able to run code in the sandboxes of
416
+ * every workspace it names.
417
+ *
418
+ * A sandbox is reached in the workspace named here and answers 404 in any
419
+ * other, so build one strategy per workspace with `forWorkspace`.
420
+ */
421
+ declare class ServiceTokenAuthStrategy implements AuthStrategy {
422
+ #private;
423
+ constructor(options: ServiceTokenAuthOptions);
424
+ /** The same service acting in `workspaceId`, which must be a workspace id. */
425
+ forWorkspace(workspaceId: string): ServiceTokenAuthStrategy;
426
+ getHeaders(): Headers;
427
+ }
326
428
 
327
429
  declare class FetchError extends Error {
328
430
  readonly url: string;
@@ -419,5 +521,5 @@ declare function parseRunLifecycleEvent(raw: unknown): RunLifecycleEvent | null;
419
521
 
420
522
  declare function sandbox(config: SandboxConfig): SandboxClient;
421
523
 
422
- export { DataTokenAuthStrategy, FetchError, RUN_LIFECYCLE_EVENT_TYPES, RUN_LIFECYCLE_TERMINAL_TYPES, RUN_LIFECYCLE_TOPIC, SANDBOX_LIFECYCLE_EVENT_TYPES, SANDBOX_LIFECYCLE_ITEM, SANDBOX_LIFECYCLE_TOPIC, SANDBOX_RUNTIMES, Sandbox, SandboxClient, SandboxRun, isRunLifecycleEvent, isSandboxLifecycleEvent, lifecycleSchemaRegistryEnv, lifecycleSchemaSubject, lifecycleTopicEnv, parseRunLifecycleEvent, parseSandboxLifecycleEvent, runLifecycleTopicEnv, sandbox, sandboxLifecycleTopicEnv };
423
- export type { AuthStrategy, CreateRunRequest, CreateSandboxRequest, CreateSnapshotRequest, ExecCommandOptions, ExecCommandResult, ExecutionResult, FileInput, LifecycleTopic, ListSandboxesOptions, RunCodeOptions, RunLifecycleEvent, RunLifecycleEventType, RunLifecycleSource, RunResponse, SandboxCommands, SandboxConfig, SandboxFiles, SandboxInfo, SandboxLifecycleEvent, SandboxLifecycleEventType, SandboxLifecycleSource, SandboxOnTimeout, SandboxRuntime, SandboxState, SnapshotInfo, SnapshotRecipe, Status, StreamCallbacks, StreamEvent };
524
+ 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 };
525
+ 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
@@ -10,10 +10,43 @@ declare const SANDBOX_RUNTIMES: readonly ["lambda-microvm", "agent-sandbox", "e2
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` today;
21
+ * `lambda-microvm` and `agent-sandbox` never do), and only on create, get and
22
+ * resume. Every field is optional because backends differ.
23
+ */
24
+ interface SandboxAccess {
25
+ /** Sent as `X-Access-Token` to the in-sandbox agent (envd). */
26
+ envdAccessToken?: string;
27
+ /**
28
+ * Sent as `e2b-traffic-access-token` to every other port. Exists only for a
29
+ * sandbox created with `privateTraffic`.
30
+ */
31
+ trafficAccessToken?: string;
32
+ /**
33
+ * Base URL of the backend's sandbox proxy, when one address serves every
34
+ * sandbox and routes by the `E2b-Sandbox-Id` and `E2b-Sandbox-Port` headers.
35
+ */
36
+ sandboxUrl?: string;
37
+ /**
38
+ * Domain the ports are published under, as
39
+ * `<port>-<externalId>.<sandboxDomain>`. Used when `sandboxUrl` is absent.
40
+ */
41
+ sandboxDomain?: string;
42
+ /** Version of the in-sandbox agent. */
43
+ envdVersion?: string;
44
+ }
13
45
  interface SandboxInfo {
14
46
  sandboxId: string;
15
47
  status: Status;
16
48
  provider: string;
49
+ /** The backend's own id for the sandbox; what direct access addresses. */
17
50
  externalId: string;
18
51
  state: SandboxState;
19
52
  image?: string;
@@ -25,6 +58,12 @@ interface SandboxInfo {
25
58
  lastUsedAt: string;
26
59
  expiresAt?: string;
27
60
  errorMessage?: string;
61
+ /**
62
+ * Direct-access address and credentials. Present on what `createSandbox`,
63
+ * `getSandbox` and `resumeSandbox` answer, on a backend with direct access.
64
+ * Never on `listSandboxes`, `extendSandbox` or `suspendSandbox`.
65
+ */
66
+ access?: SandboxAccess;
28
67
  }
29
68
  interface ListSandboxesOptions {
30
69
  metadata?: Record<string, string>;
@@ -95,6 +134,14 @@ interface CreateSandboxRequest {
95
134
  onTimeout?: SandboxOnTimeout;
96
135
  /** Backend to host it; the deployment's default when omitted. */
97
136
  provider?: string;
137
+ /**
138
+ * Seal the sandbox: its agent answers only requests carrying
139
+ * `access.envdAccessToken`, every other port only requests carrying
140
+ * `access.trafficAccessToken`. The API answers 409 on a backend that
141
+ * cannot (`lambda-microvm`, `agent-sandbox`), and 502 when the backend
142
+ * created the sandbox without one of those tokens (it is torn down).
143
+ */
144
+ privateTraffic?: boolean;
98
145
  }
99
146
  interface SnapshotRecipe {
100
147
  paths: string[];
@@ -108,7 +155,8 @@ interface SnapshotRecipe {
108
155
  interface CreateSnapshotRequest {
109
156
  name: string;
110
157
  idempotencyKey: string;
111
- recipe: SnapshotRecipe;
158
+ /** Required by lambda-microvm, which builds an image from it; not used by e2b, which captures the live sandbox. */
159
+ recipe?: SnapshotRecipe;
112
160
  metadata?: Record<string, string>;
113
161
  }
114
162
  interface SnapshotInfo {
@@ -221,6 +269,7 @@ interface SandboxCommands {
221
269
  }
222
270
 
223
271
  declare class Sandbox {
272
+ #private;
224
273
  private client;
225
274
  private auth;
226
275
  readonly sandboxId: string;
@@ -229,15 +278,30 @@ declare class Sandbox {
229
278
  private timeoutMs;
230
279
  private lastInfo?;
231
280
  constructor(client: SandboxClient, sandboxId: string, auth: AuthStrategy, info?: SandboxInfo);
281
+ /** The last descriptor the API answered, without `access`. */
232
282
  get info(): SandboxInfo | undefined;
283
+ /**
284
+ * Direct-access address and credentials, as last answered by create,
285
+ * `getInfo` or `resume`. `extend` and `suspend` do not answer them and do
286
+ * not erase them. `undefined` on a backend without direct access.
287
+ *
288
+ * The tokens are credentials: do not log what this returns.
289
+ */
290
+ get access(): SandboxAccess | undefined;
291
+ private remember;
233
292
  static create(client: SandboxClient, options?: CreateSandboxRequest): Promise<Sandbox>;
234
293
  static connect(client: SandboxClient, sandboxId: string): Promise<Sandbox>;
235
294
  private normalizeLanguage;
236
295
  runCode(script: string, options?: RunCodeOptions): Promise<ExecutionResult>;
237
296
  kill(): Promise<void>;
297
+ /** Reads the sandbox again; the answer carries `access` where the backend has it. */
238
298
  getInfo(): Promise<SandboxInfo>;
239
299
  extend(ttlSeconds: number): Promise<SandboxInfo>;
240
300
  suspend(): Promise<SandboxInfo>;
301
+ /**
302
+ * Resumes the sandbox. The answer carries `access` again, including the
303
+ * tokens a backend only hands out at creation, and `this.access` follows.
304
+ */
241
305
  resume(): Promise<SandboxInfo>;
242
306
  /**
243
307
  * Builds a reusable, pre-warmed image from this sandbox. Unlike `suspend`,
@@ -323,6 +387,44 @@ declare class DataTokenAuthStrategy implements AuthStrategy {
323
387
  constructor(dataToken: string);
324
388
  getHeaders(): Headers;
325
389
  }
390
+ declare const SERVICE_TOKEN_HEADER = "x-sandbox-service-token";
391
+ declare const SERVICE_WORKSPACE_HEADER = "x-sandbox-workspace-id";
392
+ /**
393
+ * A service acts in one workspace, named on every request: the API has no
394
+ * operation that spans workspaces for it. A `workspaceId` that is missing,
395
+ * `undefined` or empty is an error, never a wider request.
396
+ */
397
+ interface ServiceTokenAuthOptions {
398
+ /** The service token of this workload. Never a value a sandbox can read. */
399
+ serviceToken: string;
400
+ /** The workspace to act in. */
401
+ workspaceId: string;
402
+ }
403
+ /**
404
+ * Authenticates a workload that has no caller behind it, such as a worker
405
+ * pausing an idle sandbox or a reaper. The API accepts it on its internal
406
+ * address only, and only for the lifecycle of a sandbox (create, list, read,
407
+ * extend, suspend, resume and delete) and for a live snapshot of one (no
408
+ * recipe), reading that snapshot and deleting one. Running commands, files,
409
+ * runs, snapshot recipes and the snapshot listing through the API still need
410
+ * the data token of the workspace.
411
+ *
412
+ * On a backend with direct access, create, read and resume answer `access`
413
+ * to the service as to the owner, and with it the service drives the sandbox
414
+ * itself (commands, files, traffic): that is how agent-api's workloads reach
415
+ * the data plane. Treat the strategy as able to run code in the sandboxes of
416
+ * every workspace it names.
417
+ *
418
+ * A sandbox is reached in the workspace named here and answers 404 in any
419
+ * other, so build one strategy per workspace with `forWorkspace`.
420
+ */
421
+ declare class ServiceTokenAuthStrategy implements AuthStrategy {
422
+ #private;
423
+ constructor(options: ServiceTokenAuthOptions);
424
+ /** The same service acting in `workspaceId`, which must be a workspace id. */
425
+ forWorkspace(workspaceId: string): ServiceTokenAuthStrategy;
426
+ getHeaders(): Headers;
427
+ }
326
428
 
327
429
  declare class FetchError extends Error {
328
430
  readonly url: string;
@@ -419,5 +521,5 @@ declare function parseRunLifecycleEvent(raw: unknown): RunLifecycleEvent | null;
419
521
 
420
522
  declare function sandbox(config: SandboxConfig): SandboxClient;
421
523
 
422
- export { DataTokenAuthStrategy, FetchError, RUN_LIFECYCLE_EVENT_TYPES, RUN_LIFECYCLE_TERMINAL_TYPES, RUN_LIFECYCLE_TOPIC, SANDBOX_LIFECYCLE_EVENT_TYPES, SANDBOX_LIFECYCLE_ITEM, SANDBOX_LIFECYCLE_TOPIC, SANDBOX_RUNTIMES, Sandbox, SandboxClient, SandboxRun, isRunLifecycleEvent, isSandboxLifecycleEvent, lifecycleSchemaRegistryEnv, lifecycleSchemaSubject, lifecycleTopicEnv, parseRunLifecycleEvent, parseSandboxLifecycleEvent, runLifecycleTopicEnv, sandbox, sandboxLifecycleTopicEnv };
423
- export type { AuthStrategy, CreateRunRequest, CreateSandboxRequest, CreateSnapshotRequest, ExecCommandOptions, ExecCommandResult, ExecutionResult, FileInput, LifecycleTopic, ListSandboxesOptions, RunCodeOptions, RunLifecycleEvent, RunLifecycleEventType, RunLifecycleSource, RunResponse, SandboxCommands, SandboxConfig, SandboxFiles, SandboxInfo, SandboxLifecycleEvent, SandboxLifecycleEventType, SandboxLifecycleSource, SandboxOnTimeout, SandboxRuntime, SandboxState, SnapshotInfo, SnapshotRecipe, Status, StreamCallbacks, StreamEvent };
524
+ 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 };
525
+ 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
@@ -10,10 +10,43 @@ declare const SANDBOX_RUNTIMES: readonly ["lambda-microvm", "agent-sandbox", "e2
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` today;
21
+ * `lambda-microvm` and `agent-sandbox` never do), and only on create, get and
22
+ * resume. Every field is optional because backends differ.
23
+ */
24
+ interface SandboxAccess {
25
+ /** Sent as `X-Access-Token` to the in-sandbox agent (envd). */
26
+ envdAccessToken?: string;
27
+ /**
28
+ * Sent as `e2b-traffic-access-token` to every other port. Exists only for a
29
+ * sandbox created with `privateTraffic`.
30
+ */
31
+ trafficAccessToken?: string;
32
+ /**
33
+ * Base URL of the backend's sandbox proxy, when one address serves every
34
+ * sandbox and routes by the `E2b-Sandbox-Id` and `E2b-Sandbox-Port` headers.
35
+ */
36
+ sandboxUrl?: string;
37
+ /**
38
+ * Domain the ports are published under, as
39
+ * `<port>-<externalId>.<sandboxDomain>`. Used when `sandboxUrl` is absent.
40
+ */
41
+ sandboxDomain?: string;
42
+ /** Version of the in-sandbox agent. */
43
+ envdVersion?: string;
44
+ }
13
45
  interface SandboxInfo {
14
46
  sandboxId: string;
15
47
  status: Status;
16
48
  provider: string;
49
+ /** The backend's own id for the sandbox; what direct access addresses. */
17
50
  externalId: string;
18
51
  state: SandboxState;
19
52
  image?: string;
@@ -25,6 +58,12 @@ interface SandboxInfo {
25
58
  lastUsedAt: string;
26
59
  expiresAt?: string;
27
60
  errorMessage?: string;
61
+ /**
62
+ * Direct-access address and credentials. Present on what `createSandbox`,
63
+ * `getSandbox` and `resumeSandbox` answer, on a backend with direct access.
64
+ * Never on `listSandboxes`, `extendSandbox` or `suspendSandbox`.
65
+ */
66
+ access?: SandboxAccess;
28
67
  }
29
68
  interface ListSandboxesOptions {
30
69
  metadata?: Record<string, string>;
@@ -95,6 +134,14 @@ interface CreateSandboxRequest {
95
134
  onTimeout?: SandboxOnTimeout;
96
135
  /** Backend to host it; the deployment's default when omitted. */
97
136
  provider?: string;
137
+ /**
138
+ * Seal the sandbox: its agent answers only requests carrying
139
+ * `access.envdAccessToken`, every other port only requests carrying
140
+ * `access.trafficAccessToken`. The API answers 409 on a backend that
141
+ * cannot (`lambda-microvm`, `agent-sandbox`), and 502 when the backend
142
+ * created the sandbox without one of those tokens (it is torn down).
143
+ */
144
+ privateTraffic?: boolean;
98
145
  }
99
146
  interface SnapshotRecipe {
100
147
  paths: string[];
@@ -108,7 +155,8 @@ interface SnapshotRecipe {
108
155
  interface CreateSnapshotRequest {
109
156
  name: string;
110
157
  idempotencyKey: string;
111
- recipe: SnapshotRecipe;
158
+ /** Required by lambda-microvm, which builds an image from it; not used by e2b, which captures the live sandbox. */
159
+ recipe?: SnapshotRecipe;
112
160
  metadata?: Record<string, string>;
113
161
  }
114
162
  interface SnapshotInfo {
@@ -221,6 +269,7 @@ interface SandboxCommands {
221
269
  }
222
270
 
223
271
  declare class Sandbox {
272
+ #private;
224
273
  private client;
225
274
  private auth;
226
275
  readonly sandboxId: string;
@@ -229,15 +278,30 @@ declare class Sandbox {
229
278
  private timeoutMs;
230
279
  private lastInfo?;
231
280
  constructor(client: SandboxClient, sandboxId: string, auth: AuthStrategy, info?: SandboxInfo);
281
+ /** The last descriptor the API answered, without `access`. */
232
282
  get info(): SandboxInfo | undefined;
283
+ /**
284
+ * Direct-access address and credentials, as last answered by create,
285
+ * `getInfo` or `resume`. `extend` and `suspend` do not answer them and do
286
+ * not erase them. `undefined` on a backend without direct access.
287
+ *
288
+ * The tokens are credentials: do not log what this returns.
289
+ */
290
+ get access(): SandboxAccess | undefined;
291
+ private remember;
233
292
  static create(client: SandboxClient, options?: CreateSandboxRequest): Promise<Sandbox>;
234
293
  static connect(client: SandboxClient, sandboxId: string): Promise<Sandbox>;
235
294
  private normalizeLanguage;
236
295
  runCode(script: string, options?: RunCodeOptions): Promise<ExecutionResult>;
237
296
  kill(): Promise<void>;
297
+ /** Reads the sandbox again; the answer carries `access` where the backend has it. */
238
298
  getInfo(): Promise<SandboxInfo>;
239
299
  extend(ttlSeconds: number): Promise<SandboxInfo>;
240
300
  suspend(): Promise<SandboxInfo>;
301
+ /**
302
+ * Resumes the sandbox. The answer carries `access` again, including the
303
+ * tokens a backend only hands out at creation, and `this.access` follows.
304
+ */
241
305
  resume(): Promise<SandboxInfo>;
242
306
  /**
243
307
  * Builds a reusable, pre-warmed image from this sandbox. Unlike `suspend`,
@@ -323,6 +387,44 @@ declare class DataTokenAuthStrategy implements AuthStrategy {
323
387
  constructor(dataToken: string);
324
388
  getHeaders(): Headers;
325
389
  }
390
+ declare const SERVICE_TOKEN_HEADER = "x-sandbox-service-token";
391
+ declare const SERVICE_WORKSPACE_HEADER = "x-sandbox-workspace-id";
392
+ /**
393
+ * A service acts in one workspace, named on every request: the API has no
394
+ * operation that spans workspaces for it. A `workspaceId` that is missing,
395
+ * `undefined` or empty is an error, never a wider request.
396
+ */
397
+ interface ServiceTokenAuthOptions {
398
+ /** The service token of this workload. Never a value a sandbox can read. */
399
+ serviceToken: string;
400
+ /** The workspace to act in. */
401
+ workspaceId: string;
402
+ }
403
+ /**
404
+ * Authenticates a workload that has no caller behind it, such as a worker
405
+ * pausing an idle sandbox or a reaper. The API accepts it on its internal
406
+ * address only, and only for the lifecycle of a sandbox (create, list, read,
407
+ * extend, suspend, resume and delete) and for a live snapshot of one (no
408
+ * recipe), reading that snapshot and deleting one. Running commands, files,
409
+ * runs, snapshot recipes and the snapshot listing through the API still need
410
+ * the data token of the workspace.
411
+ *
412
+ * On a backend with direct access, create, read and resume answer `access`
413
+ * to the service as to the owner, and with it the service drives the sandbox
414
+ * itself (commands, files, traffic): that is how agent-api's workloads reach
415
+ * the data plane. Treat the strategy as able to run code in the sandboxes of
416
+ * every workspace it names.
417
+ *
418
+ * A sandbox is reached in the workspace named here and answers 404 in any
419
+ * other, so build one strategy per workspace with `forWorkspace`.
420
+ */
421
+ declare class ServiceTokenAuthStrategy implements AuthStrategy {
422
+ #private;
423
+ constructor(options: ServiceTokenAuthOptions);
424
+ /** The same service acting in `workspaceId`, which must be a workspace id. */
425
+ forWorkspace(workspaceId: string): ServiceTokenAuthStrategy;
426
+ getHeaders(): Headers;
427
+ }
326
428
 
327
429
  declare class FetchError extends Error {
328
430
  readonly url: string;
@@ -419,5 +521,5 @@ declare function parseRunLifecycleEvent(raw: unknown): RunLifecycleEvent | null;
419
521
 
420
522
  declare function sandbox(config: SandboxConfig): SandboxClient;
421
523
 
422
- export { DataTokenAuthStrategy, FetchError, RUN_LIFECYCLE_EVENT_TYPES, RUN_LIFECYCLE_TERMINAL_TYPES, RUN_LIFECYCLE_TOPIC, SANDBOX_LIFECYCLE_EVENT_TYPES, SANDBOX_LIFECYCLE_ITEM, SANDBOX_LIFECYCLE_TOPIC, SANDBOX_RUNTIMES, Sandbox, SandboxClient, SandboxRun, isRunLifecycleEvent, isSandboxLifecycleEvent, lifecycleSchemaRegistryEnv, lifecycleSchemaSubject, lifecycleTopicEnv, parseRunLifecycleEvent, parseSandboxLifecycleEvent, runLifecycleTopicEnv, sandbox, sandboxLifecycleTopicEnv };
423
- export type { AuthStrategy, CreateRunRequest, CreateSandboxRequest, CreateSnapshotRequest, ExecCommandOptions, ExecCommandResult, ExecutionResult, FileInput, LifecycleTopic, ListSandboxesOptions, RunCodeOptions, RunLifecycleEvent, RunLifecycleEventType, RunLifecycleSource, RunResponse, SandboxCommands, SandboxConfig, SandboxFiles, SandboxInfo, SandboxLifecycleEvent, SandboxLifecycleEventType, SandboxLifecycleSource, SandboxOnTimeout, SandboxRuntime, SandboxState, SnapshotInfo, SnapshotRecipe, Status, StreamCallbacks, StreamEvent };
524
+ 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 };
525
+ 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
@@ -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,30 @@ 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
  }
175
220
  async extend(ttlSeconds) {
176
- this.lastInfo = await this.client.extendSandbox(this.sandboxId, ttlSeconds);
177
- return this.lastInfo;
221
+ const info = await this.client.extendSandbox(this.sandboxId, ttlSeconds);
222
+ this.remember(info);
223
+ return info;
178
224
  }
179
225
  async suspend() {
180
- this.lastInfo = await this.client.suspendSandbox(this.sandboxId);
181
- return this.lastInfo;
226
+ const info = await this.client.suspendSandbox(this.sandboxId);
227
+ this.remember(info);
228
+ return info;
182
229
  }
230
+ /**
231
+ * Resumes the sandbox. The answer carries `access` again, including the
232
+ * tokens a backend only hands out at creation, and `this.access` follows.
233
+ */
183
234
  async resume() {
184
- this.lastInfo = await this.client.resumeSandbox(this.sandboxId);
185
- return this.lastInfo;
235
+ const info = await this.client.resumeSandbox(this.sandboxId);
236
+ this.remember(info);
237
+ return info;
186
238
  }
187
239
  /**
188
240
  * Builds a reusable, pre-warmed image from this sandbox. Unlike `suspend`,
@@ -198,6 +250,7 @@ class Sandbox {
198
250
  this.timeoutMs = ms;
199
251
  }
200
252
  }
253
+ _access = new WeakMap();
201
254
 
202
255
  var __defProp$1 = Object.defineProperty;
203
256
  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 +670,25 @@ class SandboxClient {
617
670
  }
618
671
  }
619
672
 
673
+ var __accessCheck = (obj, member, msg) => {
674
+ if (!member.has(obj))
675
+ throw TypeError("Cannot " + msg);
676
+ };
677
+ var __privateGet = (obj, member, getter) => {
678
+ __accessCheck(obj, member, "read from private field");
679
+ return getter ? getter.call(obj) : member.get(obj);
680
+ };
681
+ var __privateAdd = (obj, member, value) => {
682
+ if (member.has(obj))
683
+ throw TypeError("Cannot add the same private member more than once");
684
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
685
+ };
686
+ var __privateSet = (obj, member, value, setter) => {
687
+ __accessCheck(obj, member, "write to private field");
688
+ setter ? setter.call(obj, value) : member.set(obj, value);
689
+ return value;
690
+ };
691
+ var _serviceToken, _workspaceId;
620
692
  class DataTokenAuthStrategy {
621
693
  constructor(dataToken) {
622
694
  this.dataToken = dataToken;
@@ -627,6 +699,41 @@ class DataTokenAuthStrategy {
627
699
  });
628
700
  }
629
701
  }
702
+ const SERVICE_TOKEN_HEADER = "x-sandbox-service-token";
703
+ const SERVICE_WORKSPACE_HEADER = "x-sandbox-workspace-id";
704
+ function assertWorkspaceId(workspaceId) {
705
+ if (typeof workspaceId !== "string" || workspaceId.trim() === "") {
706
+ throw new Error("ServiceTokenAuthStrategy needs a non-empty workspaceId");
707
+ }
708
+ }
709
+ const _ServiceTokenAuthStrategy = class _ServiceTokenAuthStrategy {
710
+ constructor(options) {
711
+ // Private fields, so the token is not part of what a logger or
712
+ // JSON.stringify prints when handed the strategy or the client holding it.
713
+ __privateAdd(this, _serviceToken, void 0);
714
+ __privateAdd(this, _workspaceId, void 0);
715
+ if (!options.serviceToken) {
716
+ throw new Error("ServiceTokenAuthStrategy needs a service token");
717
+ }
718
+ assertWorkspaceId(options.workspaceId);
719
+ __privateSet(this, _serviceToken, options.serviceToken);
720
+ __privateSet(this, _workspaceId, options.workspaceId);
721
+ }
722
+ /** The same service acting in `workspaceId`, which must be a workspace id. */
723
+ forWorkspace(workspaceId) {
724
+ assertWorkspaceId(workspaceId);
725
+ return new _ServiceTokenAuthStrategy({ serviceToken: __privateGet(this, _serviceToken), workspaceId });
726
+ }
727
+ getHeaders() {
728
+ return new Headers({
729
+ [SERVICE_TOKEN_HEADER]: __privateGet(this, _serviceToken),
730
+ [SERVICE_WORKSPACE_HEADER]: __privateGet(this, _workspaceId)
731
+ });
732
+ }
733
+ };
734
+ _serviceToken = new WeakMap();
735
+ _workspaceId = new WeakMap();
736
+ let ServiceTokenAuthStrategy = _ServiceTokenAuthStrategy;
630
737
 
631
738
  const SANDBOX_LIFECYCLE_TOPIC = "sandbox-lifecycle";
632
739
  const RUN_LIFECYCLE_TOPIC = "run-lifecycle";
@@ -711,4 +818,4 @@ function sandbox(config) {
711
818
  return new SandboxClient(config);
712
819
  }
713
820
 
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 };
821
+ 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.6.1",
3
+ "version": "1.8.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {