@alineo-labs/sandbox 0.4.3 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { BashSession, CheckpointInfo, CommandError, CredentialBinding, CredentialBroker, CredentialBroker as CredentialBroker$1, CredentialResolver, DiagnosticEvent, DiagnosticLog, EnvironmentRecord, EnvironmentRecord as EnvironmentRecord$1, EnvironmentRecord as EnvironmentRecord$2, ExecCodeOptions, ExecConnectionError, ExecHandle, ExecOptions, ExecResult, FileInfo, IStorageAdapter, IStorageAdapter as IStorageAdapter$1, InteractiveExecHandle, LedgerEntry, LedgerEvent, ListSandboxOptions, ListSandboxOptions as ListSandboxOptions$1, Metrics, PendingInteractiveExec, SandboxDetails, SandboxDetails as SandboxDetails$1, SandboxError, SandboxHandle, SandboxHandle as SandboxHandle$1, SandboxHooks, SandboxStatus, StepTimeoutError } from "@alineo-labs/core";
2
- import { CodeLanguage, CredentialProxyConfig, NetworkPolicy, NetworkPolicy as NetworkPolicy$1, NetworkRule } from "@alineo-labs/opensandbox";
3
2
  import { OpenSandboxCredentialBroker } from "@alineo-labs/vault";
3
+ import { AlineoError, AlineoError as AlineoError$1, AlineoErrorOptions, ErrorCode, ErrorCode as ErrorCode$1, errorCodeOf, isAlineoError, isRetryable } from "@alineo-labs/errors";
4
+ import { CodeLanguage, CredentialProxyConfig, NetworkPolicy, NetworkPolicy as NetworkPolicy$1, NetworkRule, SandboxProvider } from "@alineo-labs/provider";
5
+ import { LedgerEnvelope } from "@alineo-labs/schema/types";
4
6
  //#region src/types.d.ts
5
7
  /**
6
8
  * Client-side SDK error carrying an HTTP-style status code, thrown for
@@ -10,16 +12,24 @@ import { OpenSandboxCredentialBroker } from "@alineo-labs/vault";
10
12
  * `OpenSandboxError` from `@alineo-labs/opensandbox`, which is never rethrown as a
11
13
  * `SandboxClientError`.
12
14
  */
13
- export declare class SandboxClientError extends Error {
15
+ export declare class SandboxClientError extends AlineoError$1 {
14
16
  readonly status: number;
15
- constructor(message: string, status: number);
17
+ constructor(message: string, status: number, code?: ErrorCode$1, options?: AlineoErrorOptions);
16
18
  }
17
19
  /** Options for constructing a {@link Sandbox} client. */
18
20
  interface SandboxClientOptions {
19
- /** Base URL of your OpenSandbox server (e.g. `http://localhost:8080`). */
20
- baseUrl: string;
21
+ /**
22
+ * Base URL of your OpenSandbox server (e.g. `http://localhost:8080`). Required unless
23
+ * `provider` is given.
24
+ */
25
+ baseUrl?: string;
21
26
  /** OpenSandbox API key. Pass an empty string for local dev with no auth. */
22
27
  apiKey?: string;
28
+ /**
29
+ * The sandbox provider to run on. Leave it out to use OpenSandbox at `baseUrl`, which is what
30
+ * `apiKey` and `useServerProxy` configure. They do not apply to a provider you pass.
31
+ */
32
+ provider?: SandboxProvider;
23
33
  /**
24
34
  * Storage adapter for persisting sandbox events.
25
35
  *
@@ -27,6 +37,18 @@ interface SandboxClientOptions {
27
37
  * `new PostgresAdapter(connectionString)` from `@alineo-labs/postgres` for production.
28
38
  */
29
39
  adapter: IStorageAdapter$1;
40
+ /**
41
+ * Receives a `LedgerEnvelope` for every event any sandbox from this client emits, beside
42
+ * the ledger write.
43
+ *
44
+ * Synchronous and must not throw — it runs on the write path of a sandbox operation, so an
45
+ * async sink would become backpressure and a throwing one would fail the very operation
46
+ * being recorded. A sink that needs IO buffers internally and flushes on its own schedule.
47
+ *
48
+ * @internal The ledger is the system of record and a sink is an export path; the public
49
+ * shape of this belongs with the work that owns export.
50
+ */
51
+ sink?: (envelope: LedgerEnvelope) => void;
30
52
  /**
31
53
  * Maximum number of sandboxes that may be active simultaneously.
32
54
  * When at capacity, `sandbox()` awaits until a slot is free.
@@ -43,7 +65,7 @@ interface SandboxClientOptions {
43
65
  * Broker for `sb.credentials.*` — registers credentials with, and resolves endpoints
44
66
  * against, whatever backend actually injects them. Defaults to
45
67
  * `OpenSandboxCredentialBroker` (from `@alineo-labs/vault`), wired to this client's own
46
- * `ControlClient`/`useServerProxy`, if omitted. Only relevant for sandboxes created with
68
+ * provider and `useServerProxy`, if omitted. Only relevant for sandboxes created with
47
69
  * `credentialProxy: true`.
48
70
  */
49
71
  credentialBroker?: CredentialBroker$1;
@@ -278,17 +300,31 @@ export declare class Environment {
278
300
  * ```
279
301
  */
280
302
  export declare class Sandbox {
281
- private readonly _control;
303
+ private readonly _provider;
282
304
  private readonly _adapter;
305
+ private readonly _sink;
283
306
  private readonly _credentialBroker;
284
307
  private readonly _maxConcurrency;
285
- private readonly _useServerProxy;
286
308
  private _activeCount;
287
309
  private readonly _waiters;
288
310
  private _connectPromise;
289
311
  private _adapterClosed;
290
312
  private readonly _envBuilds;
313
+ /**
314
+ * The five `sandbox.created` writes below do not go through `SandboxCore.emit()` — the
315
+ * handle does not exist yet when they happen. This is their shared funnel, so a sink is
316
+ * attached to all five or none, rather than to four of them.
317
+ *
318
+ * The sink runs before the append for the same reason it does in `emit()`: an exporter
319
+ * must not delay, or fail, the write it is exporting.
320
+ */
321
+ private _append;
291
322
  constructor(options: SandboxClientOptions);
323
+ /**
324
+ * The sandbox provider this client runs on. For a caller that needs something the client
325
+ * does not wrap, such as listing sandboxes the ledger never recorded.
326
+ */
327
+ get provider(): SandboxProvider;
292
328
  /** Lazily initialises the adapter on first use. Concurrent callers share the same promise. */
293
329
  private _ensureConnected;
294
330
  /**
@@ -351,7 +387,7 @@ export declare class Sandbox {
351
387
  * @param opts.runId Default run-correlation ID for any later `.fork()` call on the
352
388
  * returned `SandboxHandle`. `connect()` has no way to discover the sandbox's original
353
389
  * `runId` (no ledger lookup is attempted — the caller may be using a completely
354
- * different adapter than whatever originally created it, as `alineo fork` does when
390
+ * different adapter than whatever originally created it, as `alineo spawn` does when
355
391
  * self-attaching). Omit this and pass `runId` explicitly to `.fork()` itself instead.
356
392
  *
357
393
  * @example
@@ -508,4 +544,32 @@ export declare class Sandbox {
508
544
  private _releaseSlot;
509
545
  }
510
546
  //#endregion
511
- export { BashSession, type CheckpointInfo, CodeLanguage, CommandError, type CredentialBinding, type CredentialBroker, type CredentialProxyConfig, type DiagnosticEvent, type DiagnosticLog, type EnvironmentOptions, type EnvironmentRecord, type EnvironmentSandboxOptions, type ExecCodeOptions, ExecConnectionError, type ExecHandle, type ExecOptions, type ExecResult, type FileInfo, type IStorageAdapter, type InteractiveExecHandle, type LedgerEntry, LedgerEvent, type ListSandboxOptions, type Metrics, type NetworkPolicy, type NetworkRule, OpenSandboxCredentialBroker, type PendingInteractiveExec, type ResumeOptions, type SandboxClientOptions, type SandboxDetails, SandboxError, SandboxHandle, type SandboxOptions, SandboxStatus, StepTimeoutError };
547
+ //#region src/provider-config.d.ts
548
+ /**
549
+ * The part of `alineo.config.json` that picks a provider and says where it is. Structural, so
550
+ * the SDK needs no dependency on the package that loads the file.
551
+ */
552
+ interface ProviderConfig {
553
+ /** Which provider. Absent means `"opensandbox"`. */
554
+ provider?: string;
555
+ /** OpenSandbox server URL. */
556
+ serverUrl: string;
557
+ apiKey?: string;
558
+ useServerProxy?: boolean;
559
+ }
560
+ /** The provider ids `providerFromConfig` can build. */
561
+ export declare const KNOWN_PROVIDERS: readonly ["opensandbox"];
562
+ /**
563
+ * Build the provider a config names.
564
+ *
565
+ * An id this build does not know is refused here, naming the ids it does know. Guessing
566
+ * OpenSandbox instead would run someone's agents on the wrong substrate without a word.
567
+ */
568
+ export declare function providerFromConfig(config: ProviderConfig): SandboxProvider;
569
+ /**
570
+ * A {@link Sandbox} client for the provider a config names. Every CLI command and the agent
571
+ * runtime build their client through this, so the provider is chosen in one place.
572
+ */
573
+ export declare function clientFromConfig(config: ProviderConfig, options: Omit<SandboxClientOptions, "provider" | "baseUrl" | "apiKey" | "useServerProxy">): Sandbox;
574
+ //#endregion
575
+ export { AlineoError, BashSession, type CheckpointInfo, CodeLanguage, CommandError, type CredentialBinding, type CredentialBroker, type CredentialProxyConfig, type DiagnosticEvent, type DiagnosticLog, type EnvironmentOptions, type EnvironmentRecord, type EnvironmentSandboxOptions, type ErrorCode, type ExecCodeOptions, ExecConnectionError, type ExecHandle, type ExecOptions, type ExecResult, type FileInfo, type IStorageAdapter, type InteractiveExecHandle, type LedgerEntry, LedgerEvent, type ListSandboxOptions, type Metrics, type NetworkPolicy, type NetworkRule, OpenSandboxCredentialBroker, type PendingInteractiveExec, type ProviderConfig, type ResumeOptions, type SandboxClientOptions, type SandboxDetails, SandboxError, SandboxHandle, type SandboxOptions, SandboxStatus, StepTimeoutError, errorCodeOf, isAlineoError, isRetryable };
package/dist/index.mjs CHANGED
@@ -1,6 +1,8 @@
1
- import { BashSession, CommandError, ExecConnectionError, LedgerEvent, LedgerEvent as LedgerEvent$1, SandboxError, SandboxHandle, SandboxHandle as SandboxHandle$1, SandboxStatus, StepTimeoutError, reconstructBoundCredentials, reconstructEgressRules, resolveBoundCredential } from "@alineo-labs/core";
2
- import { CodeLanguage, ControlClient, SandboxState, SnapshotState, isValidEgressTarget } from "@alineo-labs/opensandbox";
1
+ import { BashSession, CommandError, DEFAULT_PROVIDER_ID, ExecConnectionError, LedgerEvent, LedgerEvent as LedgerEvent$1, SandboxError, SandboxHandle, SandboxHandle as SandboxHandle$1, SandboxStatus, StepTimeoutError, reconstructBoundCredentials, reconstructEgressRules, requireCapability, resolveBoundCredential } from "@alineo-labs/core";
2
+ import { OpenSandboxProvider, isValidEgressTarget } from "@alineo-labs/opensandbox";
3
3
  import { OpenSandboxCredentialBroker, OpenSandboxCredentialBroker as OpenSandboxCredentialBroker$1 } from "@alineo-labs/vault";
4
+ import { AlineoError, AlineoError as AlineoError$1, errorCodeOf, isAlineoError, isRetryable } from "@alineo-labs/errors";
5
+ import { CodeLanguage } from "@alineo-labs/provider";
4
6
  //#region src/types.ts
5
7
  /**
6
8
  * Client-side SDK error carrying an HTTP-style status code, thrown for
@@ -10,14 +12,30 @@ import { OpenSandboxCredentialBroker, OpenSandboxCredentialBroker as OpenSandbox
10
12
  * `OpenSandboxError` from `@alineo-labs/opensandbox`, which is never rethrown as a
11
13
  * `SandboxClientError`.
12
14
  */
13
- var SandboxClientError = class extends Error {
15
+ var SandboxClientError = class extends AlineoError$1 {
14
16
  status;
15
- constructor(message, status) {
16
- super(message);
17
+ constructor(message, status, code = codeForStatus(status), options) {
18
+ super(code, message, {
19
+ ...options,
20
+ details: {
21
+ status,
22
+ ...options?.details
23
+ }
24
+ });
17
25
  this.status = status;
18
26
  this.name = "SandboxClientError";
19
27
  }
20
28
  };
29
+ /**
30
+ * The code for a status when the throw site did not choose one. Call sites that know better
31
+ * (a missing session, a sandbox that is not Running) pass their own.
32
+ */
33
+ function codeForStatus(status) {
34
+ if (status === 408) return "SANDBOX_START_TIMEOUT";
35
+ if (status === 404) return "SESSION_NOT_FOUND";
36
+ if (status === 400) return "INVALID_ARGUMENT";
37
+ return "INTERNAL";
38
+ }
21
39
  //#endregion
22
40
  //#region src/environment.ts
23
41
  /**
@@ -111,25 +129,65 @@ function assertValidNetworkPolicy(policy) {
111
129
  * ```
112
130
  */
113
131
  var Sandbox = class {
114
- _control;
132
+ _provider;
115
133
  _adapter;
134
+ _sink;
116
135
  _credentialBroker;
117
136
  _maxConcurrency;
118
- _useServerProxy;
119
137
  _activeCount = 0;
120
138
  _waiters = [];
121
139
  _connectPromise = null;
122
140
  _adapterClosed = false;
123
141
  _envBuilds = /* @__PURE__ */ new Map();
142
+ /**
143
+ * The five `sandbox.created` writes below do not go through `SandboxCore.emit()` — the
144
+ * handle does not exist yet when they happen. This is their shared funnel, so a sink is
145
+ * attached to all five or none, rather than to four of them.
146
+ *
147
+ * The sink runs before the append for the same reason it does in `emit()`: an exporter
148
+ * must not delay, or fail, the write it is exporting.
149
+ */
150
+ async _append(entry) {
151
+ if (entry.event === LedgerEvent$1.SandboxCreated) {
152
+ const payload = entry.payload ?? {};
153
+ if (payload.provider === void 0) entry = {
154
+ ...entry,
155
+ payload: {
156
+ ...payload,
157
+ provider: this._provider.id
158
+ }
159
+ };
160
+ }
161
+ if (this._sink) try {
162
+ this._sink({
163
+ v: 1,
164
+ ts: entry.ts,
165
+ type: entry.event,
166
+ ...typeof entry.payload?.runId === "string" ? { runId: entry.payload.runId } : {},
167
+ data: {
168
+ sandboxId: entry.sandboxId,
169
+ name: entry.name,
170
+ stepIndex: entry.stepIndex,
171
+ payload: entry.payload
172
+ }
173
+ });
174
+ } catch {}
175
+ await this._adapter.append(entry);
176
+ }
124
177
  constructor(options) {
125
- this._control = new ControlClient({
126
- baseUrl: options.baseUrl,
127
- apiKey: options.apiKey ?? ""
128
- });
178
+ if (options.provider) this._provider = options.provider;
179
+ else {
180
+ if (!options.baseUrl) throw new SandboxClientError("Sandbox needs a `provider`, or a `baseUrl` for the OpenSandbox server", 400, "INVALID_ARGUMENT");
181
+ this._provider = new OpenSandboxProvider({
182
+ baseUrl: options.baseUrl,
183
+ apiKey: options.apiKey ?? "",
184
+ useServerProxy: options.useServerProxy ?? false
185
+ });
186
+ }
129
187
  this._adapter = options.adapter;
188
+ this._sink = options.sink;
130
189
  this._maxConcurrency = options.maxConcurrency;
131
- this._useServerProxy = options.useServerProxy ?? false;
132
- this._credentialBroker = options.credentialBroker ?? new OpenSandboxCredentialBroker$1(this._control, this._useServerProxy);
190
+ this._credentialBroker = options.credentialBroker ?? new OpenSandboxCredentialBroker$1(this._provider, options.useServerProxy ?? false);
133
191
  process.setMaxListeners(process.getMaxListeners() + 1);
134
192
  process.on("beforeExit", () => {
135
193
  if (!this._adapterClosed) {
@@ -138,6 +196,13 @@ var Sandbox = class {
138
196
  }
139
197
  });
140
198
  }
199
+ /**
200
+ * The sandbox provider this client runs on. For a caller that needs something the client
201
+ * does not wrap, such as listing sandboxes the ledger never recorded.
202
+ */
203
+ get provider() {
204
+ return this._provider;
205
+ }
141
206
  /** Lazily initialises the adapter on first use. Concurrent callers share the same promise. */
142
207
  _ensureConnected() {
143
208
  this._connectPromise ??= this._adapter.connect?.() ?? Promise.resolve();
@@ -162,6 +227,8 @@ var Sandbox = class {
162
227
  */
163
228
  async sandbox(opts) {
164
229
  assertValidNetworkPolicy(opts.networkPolicy);
230
+ if (opts.networkPolicy?.egress?.length) requireCapability(this._provider, "egress");
231
+ if (opts.credentialProxy) requireCapability(this._provider, "credentials");
165
232
  await this._ensureConnected();
166
233
  await this._acquireSlot();
167
234
  const image = typeof opts.image === "string" ? { uri: opts.image } : opts.image;
@@ -170,7 +237,7 @@ var Sandbox = class {
170
237
  const teamId = opts.teamId;
171
238
  let sandboxId;
172
239
  try {
173
- sandboxId = (await this._control.createSandbox({
240
+ sandboxId = (await this._provider.createSandbox({
174
241
  image,
175
242
  env: opts.env,
176
243
  metadata: {
@@ -189,7 +256,7 @@ var Sandbox = class {
189
256
  })).id;
190
257
  await this._waitForRunning(sandboxId);
191
258
  const name = opts.name ?? `sandbox-${sandboxId.slice(0, 8)}`;
192
- await this._adapter.append({
259
+ await this._append({
193
260
  ts: Date.now(),
194
261
  name,
195
262
  sandboxId,
@@ -206,16 +273,16 @@ var Sandbox = class {
206
273
  }
207
274
  });
208
275
  const sb = new SandboxHandle$1(sandboxId, name, {
209
- control: this._control,
276
+ provider: this._provider,
210
277
  adapter: this._adapter,
278
+ sink: this._sink,
211
279
  credentialBroker: this._credentialBroker,
212
280
  hooks: opts.hooks,
213
281
  onClose: () => {
214
282
  this._releaseSlot();
215
283
  },
216
284
  shell: opts.shell,
217
- fork: (snapshotId, tag, overrideRunId, forkOpts) => this._forkFromSnapshot(snapshotId, name, opts.resources, opts.shell, overrideRunId ?? runId, sandboxId, resourceId, teamId, forkOpts),
218
- useServerProxy: this._useServerProxy
285
+ fork: (snapshotId, tag, overrideRunId, forkOpts) => this._forkFromSnapshot(snapshotId, name, opts.resources, opts.shell, overrideRunId ?? runId, sandboxId, resourceId, teamId, forkOpts)
219
286
  });
220
287
  opts.hooks?.onSandboxCreated?.(sandboxId, name);
221
288
  return sb;
@@ -255,13 +322,19 @@ var Sandbox = class {
255
322
  }
256
323
  async _resumeSession(name, sandboxId, tag, resolveCredential) {
257
324
  const entries = await this._adapter.readAll(name, sandboxId);
325
+ const owner = (entries.find((e) => e.event === LedgerEvent$1.SandboxCreated)?.payload)?.provider ?? DEFAULT_PROVIDER_ID;
326
+ if (owner !== this._provider.id) throw new SandboxClientError(`Session ${sandboxId} was created on the "${owner}" provider, but this client is configured for "${this._provider.id}".`, 409, "PROVIDER_MISMATCH", { details: {
327
+ sandboxId,
328
+ provider: owner,
329
+ configured: this._provider.id
330
+ } });
258
331
  let checkpointIdx;
259
332
  if (tag) {
260
333
  checkpointIdx = entries.findIndex((e) => e.event === LedgerEvent$1.CheckpointCreated && e.payload?.name === tag);
261
- if (checkpointIdx === -1) throw new SandboxClientError(`No checkpoint with tag '${tag}' found for session ${sandboxId}`, 404);
334
+ if (checkpointIdx === -1) throw new SandboxClientError(`No checkpoint with tag '${tag}' found for session ${sandboxId}`, 404, "CHECKPOINT_NOT_FOUND");
262
335
  } else {
263
336
  checkpointIdx = entries.map((e) => e.event).lastIndexOf(LedgerEvent$1.CheckpointCreated);
264
- if (checkpointIdx === -1) throw new SandboxClientError(`No checkpoint found for session ${sandboxId}`, 404);
337
+ if (checkpointIdx === -1) throw new SandboxClientError(`No checkpoint found for session ${sandboxId}`, 404, "CHECKPOINT_NOT_FOUND");
265
338
  }
266
339
  const { snapshotId } = entries[checkpointIdx].payload;
267
340
  const createdPayload = entries.find((e) => e.event === LedgerEvent$1.SandboxCreated)?.payload;
@@ -323,7 +396,7 @@ var Sandbox = class {
323
396
  }
324
397
  await this._acquireSlot();
325
398
  try {
326
- const newSessionId = (await this._control.createSandbox({
399
+ const newSessionId = (await this._provider.createSandbox({
327
400
  snapshotId,
328
401
  resourceLimits: resources,
329
402
  metadata: { runId },
@@ -331,7 +404,7 @@ var Sandbox = class {
331
404
  credentialProxy: credentialProxy ? { enabled: true } : void 0
332
405
  })).id;
333
406
  await this._waitForRunning(newSessionId);
334
- await this._adapter.append({
407
+ await this._append({
335
408
  ts: Date.now(),
336
409
  name,
337
410
  sandboxId: newSessionId,
@@ -349,14 +422,14 @@ var Sandbox = class {
349
422
  }
350
423
  });
351
424
  const sb = new SandboxHandle$1(newSessionId, name, {
352
- control: this._control,
425
+ provider: this._provider,
353
426
  adapter: this._adapter,
427
+ sink: this._sink,
354
428
  credentialBroker: this._credentialBroker,
355
429
  onClose: () => {
356
430
  this._releaseSlot();
357
431
  },
358
- fork: resources?.cpu && resources.memory ? (snapshotId, tag, overrideRunId, forkOpts) => this._forkFromSnapshot(snapshotId, name, resources, void 0, overrideRunId ?? runId, newSessionId, resourceId, teamId, forkOpts) : void 0,
359
- useServerProxy: this._useServerProxy
432
+ fork: resources?.cpu && resources.memory ? (snapshotId, tag, overrideRunId, forkOpts) => this._forkFromSnapshot(snapshotId, name, resources, void 0, overrideRunId ?? runId, newSessionId, resourceId, teamId, forkOpts) : void 0
360
433
  }, replayCache, pendingInteractive);
361
434
  for (const [credName, { binding, source }] of boundCredentials) {
362
435
  const value = await resolveBoundCredential(credName, source, resolveCredential, newSessionId);
@@ -385,7 +458,7 @@ var Sandbox = class {
385
458
  * @param opts.runId Default run-correlation ID for any later `.fork()` call on the
386
459
  * returned `SandboxHandle`. `connect()` has no way to discover the sandbox's original
387
460
  * `runId` (no ledger lookup is attempted — the caller may be using a completely
388
- * different adapter than whatever originally created it, as `alineo fork` does when
461
+ * different adapter than whatever originally created it, as `alineo spawn` does when
389
462
  * self-attaching). Omit this and pass `runId` explicitly to `.fork()` itself instead.
390
463
  *
391
464
  * @example
@@ -398,20 +471,24 @@ var Sandbox = class {
398
471
  */
399
472
  async connect(sandboxId, name, opts) {
400
473
  await this._ensureConnected();
401
- const state = (await this._control.getSandbox(sandboxId)).status.state;
402
- const paused = state === SandboxState.Paused;
403
- if (state !== SandboxState.Running && !(paused && opts?.allowPaused)) throw new SandboxClientError(`SandboxHandle ${sandboxId} is ${state} — can only connect to Running sandboxes` + (paused ? " (pass allowPaused to connect to a Paused one)" : ""), 409);
474
+ const info = await this._provider.getSandbox(sandboxId);
475
+ const state = info.nativeState ?? info.state;
476
+ const paused = info.state === "paused";
477
+ if (info.state !== "running" && !(paused && opts?.allowPaused)) throw new SandboxClientError(`SandboxHandle ${sandboxId} is ${state} — can only connect to Running sandboxes` + (paused ? " (pass allowPaused to connect to a Paused one)" : ""), 409, paused ? "SANDBOX_PAUSED" : "SANDBOX_NOT_RUNNING", { details: {
478
+ sandboxId,
479
+ state
480
+ } });
404
481
  await this._acquireSlot();
405
482
  const resources = opts?.resources;
406
483
  const handle = new SandboxHandle$1(sandboxId, name, {
407
- control: this._control,
484
+ provider: this._provider,
408
485
  adapter: this._adapter,
486
+ sink: this._sink,
409
487
  credentialBroker: this._credentialBroker,
410
488
  onClose: () => {
411
489
  this._releaseSlot();
412
490
  },
413
- fork: resources ? (snapshotId, tag, overrideRunId, forkOpts) => this._forkFromSnapshot(snapshotId, name, resources, void 0, overrideRunId ?? opts?.runId, sandboxId, opts?.resourceId, opts?.teamId, forkOpts) : void 0,
414
- useServerProxy: this._useServerProxy
491
+ fork: resources ? (snapshotId, tag, overrideRunId, forkOpts) => this._forkFromSnapshot(snapshotId, name, resources, void 0, overrideRunId ?? opts?.runId, sandboxId, opts?.resourceId, opts?.teamId, forkOpts) : void 0
415
492
  });
416
493
  if (paused) handle.setPaused(true);
417
494
  return handle;
@@ -446,7 +523,7 @@ var Sandbox = class {
446
523
  await this._acquireSlot();
447
524
  try {
448
525
  const finalRunId = runId ?? crypto.randomUUID();
449
- const newId = (await this._control.createSandbox({
526
+ const newId = (await this._provider.createSandbox({
450
527
  snapshotId,
451
528
  env: opts?.env,
452
529
  resourceLimits: resources,
@@ -455,7 +532,7 @@ var Sandbox = class {
455
532
  credentialProxy: opts?.credentialProxy ? { enabled: true } : void 0
456
533
  })).id;
457
534
  await this._waitForRunning(newId);
458
- await this._adapter.append({
535
+ await this._append({
459
536
  ts: Date.now(),
460
537
  name,
461
538
  sandboxId: newId,
@@ -472,14 +549,14 @@ var Sandbox = class {
472
549
  }
473
550
  });
474
551
  return new SandboxHandle$1(newId, name, {
475
- control: this._control,
552
+ provider: this._provider,
476
553
  adapter: this._adapter,
554
+ sink: this._sink,
477
555
  credentialBroker: this._credentialBroker,
478
556
  onClose: () => {
479
557
  this._releaseSlot();
480
558
  },
481
- fork: (snapshotId, tag, overrideRunId, forkOpts) => this._forkFromSnapshot(snapshotId, name, resources, void 0, overrideRunId ?? finalRunId, newId, opts?.resourceId, opts?.teamId, forkOpts),
482
- useServerProxy: this._useServerProxy
559
+ fork: (snapshotId, tag, overrideRunId, forkOpts) => this._forkFromSnapshot(snapshotId, name, resources, void 0, overrideRunId ?? finalRunId, newId, opts?.resourceId, opts?.teamId, forkOpts)
483
560
  });
484
561
  } catch (err) {
485
562
  this._releaseSlot();
@@ -580,7 +657,9 @@ var Sandbox = class {
580
657
  await this._ensureConnected();
581
658
  const record = await this._adapter.getEnvironment(name);
582
659
  if (record) {
583
- if ((await this._control.getSnapshot(record.snapshotId).catch(() => null))?.state === SnapshotState.Ready) return this._createFromSnapshot(record.snapshotId, opts.resources, name, opts.shell, extra);
660
+ if ((await this._provider.getSnapshot(record.snapshotId).catch(() => null))?.state === "ready") try {
661
+ return await this._createFromSnapshot(record.snapshotId, opts.resources, name, opts.shell, extra);
662
+ } catch {}
584
663
  }
585
664
  const snapshotId = await this._getOrBuildEnvironment(name, opts);
586
665
  return this._createFromSnapshot(snapshotId, opts.resources, name, opts.shell, extra);
@@ -622,7 +701,7 @@ var Sandbox = class {
622
701
  await this._acquireSlot();
623
702
  try {
624
703
  const runId = crypto.randomUUID();
625
- const newId = (await this._control.createSandbox({
704
+ const newId = (await this._provider.createSandbox({
626
705
  snapshotId,
627
706
  resourceLimits: resources,
628
707
  env: extra?.env,
@@ -632,7 +711,7 @@ var Sandbox = class {
632
711
  const sessionName = `env-${envName}-${newId.slice(0, 8)}`;
633
712
  const resourceId = extra?.resourceId;
634
713
  const teamId = extra?.teamId;
635
- await this._adapter.append({
714
+ await this._append({
636
715
  ts: Date.now(),
637
716
  name: sessionName,
638
717
  sandboxId: newId,
@@ -648,16 +727,16 @@ var Sandbox = class {
648
727
  }
649
728
  });
650
729
  const sb = new SandboxHandle$1(newId, sessionName, {
651
- control: this._control,
730
+ provider: this._provider,
652
731
  adapter: this._adapter,
732
+ sink: this._sink,
653
733
  credentialBroker: this._credentialBroker,
654
734
  hooks: extra?.hooks,
655
735
  onClose: () => {
656
736
  this._releaseSlot();
657
737
  },
658
738
  shell: extra?.shell ?? envShell,
659
- fork: (snapshotId, tag, overrideRunId, forkOpts) => this._forkFromSnapshot(snapshotId, sessionName, resources, extra?.shell ?? envShell, overrideRunId ?? runId, newId, resourceId, teamId, forkOpts),
660
- useServerProxy: this._useServerProxy
739
+ fork: (snapshotId, tag, overrideRunId, forkOpts) => this._forkFromSnapshot(snapshotId, sessionName, resources, extra?.shell ?? envShell, overrideRunId ?? runId, newId, resourceId, teamId, forkOpts)
661
740
  });
662
741
  extra?.hooks?.onSandboxCreated?.(newId, sessionName);
663
742
  return sb;
@@ -672,7 +751,7 @@ var Sandbox = class {
672
751
  const finalRunId = runId ?? crypto.randomUUID();
673
752
  const finalResourceId = forkOpts?.resourceId ?? resourceId;
674
753
  const finalTeamId = forkOpts?.teamId ?? teamId;
675
- const newId = (await this._control.createSandbox({
754
+ const newId = (await this._provider.createSandbox({
676
755
  snapshotId,
677
756
  resourceLimits: resources,
678
757
  metadata: { runId: finalRunId },
@@ -681,7 +760,7 @@ var Sandbox = class {
681
760
  })).id;
682
761
  await this._waitForRunning(newId);
683
762
  const sessionName = `fork-${parentName}-${newId.slice(0, 8)}`;
684
- await this._adapter.append({
763
+ await this._append({
685
764
  ts: Date.now(),
686
765
  name: sessionName,
687
766
  sandboxId: newId,
@@ -699,15 +778,15 @@ var Sandbox = class {
699
778
  }
700
779
  });
701
780
  return new SandboxHandle$1(newId, sessionName, {
702
- control: this._control,
781
+ provider: this._provider,
703
782
  adapter: this._adapter,
783
+ sink: this._sink,
704
784
  credentialBroker: this._credentialBroker,
705
785
  onClose: () => {
706
786
  this._releaseSlot();
707
787
  },
708
788
  shell,
709
- fork: (sid, tag, overrideRunId, nextForkOpts) => this._forkFromSnapshot(sid, sessionName, resources, shell, overrideRunId ?? finalRunId, newId, finalResourceId, finalTeamId, nextForkOpts),
710
- useServerProxy: this._useServerProxy
789
+ fork: (sid, tag, overrideRunId, nextForkOpts) => this._forkFromSnapshot(sid, sessionName, resources, shell, overrideRunId ?? finalRunId, newId, finalResourceId, finalTeamId, nextForkOpts)
711
790
  });
712
791
  } catch (err) {
713
792
  this._releaseSlot();
@@ -718,13 +797,19 @@ var Sandbox = class {
718
797
  const deadline = Date.now() + timeoutMs;
719
798
  let delay = 100;
720
799
  while (Date.now() < deadline) {
721
- const s = await this._control.getSandbox(sandboxId);
722
- if (s.status.state === SandboxState.Running) return;
723
- if (s.status.state === SandboxState.Failed || s.status.state === SandboxState.Terminated) throw new SandboxClientError(`SandboxHandle ${sandboxId} entered state ${s.status.state}: ${s.status.message ?? ""}`, 500);
800
+ const s = await this._provider.getSandbox(sandboxId);
801
+ if (s.state === "running") return;
802
+ if (s.state === "failed" || s.state === "terminated") throw new SandboxClientError(`SandboxHandle ${sandboxId} entered state ${s.nativeState ?? s.state}: ${s.message ?? ""}`, 500, "SANDBOX_START_FAILED", { details: {
803
+ sandboxId,
804
+ state: s.nativeState ?? s.state
805
+ } });
724
806
  await new Promise((r) => setTimeout(r, delay));
725
807
  delay = Math.min(delay * 1.5, 1e3);
726
808
  }
727
- throw new SandboxClientError(`SandboxHandle ${sandboxId} did not reach Running within ${timeoutMs}ms`, 408);
809
+ throw new SandboxClientError(`SandboxHandle ${sandboxId} did not reach Running within ${timeoutMs}ms`, 408, "SANDBOX_START_TIMEOUT", { details: {
810
+ sandboxId,
811
+ timeoutMs
812
+ } });
728
813
  }
729
814
  async _acquireSlot() {
730
815
  if (!this._maxConcurrency || this._activeCount < this._maxConcurrency) {
@@ -740,4 +825,36 @@ var Sandbox = class {
740
825
  }
741
826
  };
742
827
  //#endregion
743
- export { BashSession, CodeLanguage, CommandError, Environment, ExecConnectionError, LedgerEvent, OpenSandboxCredentialBroker, Sandbox, SandboxClientError, SandboxError, SandboxHandle, SandboxStatus, StepTimeoutError };
828
+ //#region src/provider-config.ts
829
+ /** The provider ids `providerFromConfig` can build. */
830
+ const KNOWN_PROVIDERS = ["opensandbox"];
831
+ /**
832
+ * Build the provider a config names.
833
+ *
834
+ * An id this build does not know is refused here, naming the ids it does know. Guessing
835
+ * OpenSandbox instead would run someone's agents on the wrong substrate without a word.
836
+ */
837
+ function providerFromConfig(config) {
838
+ const id = config.provider ?? "opensandbox";
839
+ switch (id) {
840
+ case "opensandbox": return new OpenSandboxProvider({
841
+ baseUrl: config.serverUrl,
842
+ apiKey: config.apiKey ?? "",
843
+ useServerProxy: config.useServerProxy ?? false
844
+ });
845
+ default: throw new SandboxClientError(`Unknown sandbox provider "${id}". Known providers: ${KNOWN_PROVIDERS.join(", ")}.`, 400, "INVALID_ARGUMENT");
846
+ }
847
+ }
848
+ /**
849
+ * A {@link Sandbox} client for the provider a config names. Every CLI command and the agent
850
+ * runtime build their client through this, so the provider is chosen in one place.
851
+ */
852
+ function clientFromConfig(config, options) {
853
+ return new Sandbox({
854
+ ...options,
855
+ provider: providerFromConfig(config),
856
+ useServerProxy: config.useServerProxy ?? false
857
+ });
858
+ }
859
+ //#endregion
860
+ export { AlineoError, BashSession, CodeLanguage, CommandError, Environment, ExecConnectionError, KNOWN_PROVIDERS, LedgerEvent, OpenSandboxCredentialBroker, Sandbox, SandboxClientError, SandboxError, SandboxHandle, SandboxStatus, StepTimeoutError, clientFromConfig, errorCodeOf, isAlineoError, isRetryable, providerFromConfig };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alineo-labs/sandbox",
3
- "version": "0.4.3",
3
+ "version": "0.6.0",
4
4
  "license": "Apache-2.0",
5
5
  "repository": {
6
6
  "type": "git",
@@ -29,9 +29,12 @@
29
29
  "test:watch": "vitest"
30
30
  },
31
31
  "dependencies": {
32
- "@alineo-labs/core": "0.4.2",
33
- "@alineo-labs/opensandbox": "0.3.1",
34
- "@alineo-labs/vault": "0.3.2"
32
+ "@alineo-labs/core": "0.6.0",
33
+ "@alineo-labs/errors": "0.1.0",
34
+ "@alineo-labs/opensandbox": "0.4.0",
35
+ "@alineo-labs/provider": "0.1.0",
36
+ "@alineo-labs/schema": "0.3.0",
37
+ "@alineo-labs/vault": "0.4.0"
35
38
  },
36
39
  "devDependencies": {
37
40
  "bun-types": "1.4.2",