@alineo-labs/core 0.4.2 → 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.mjs CHANGED
@@ -1,6 +1,12 @@
1
1
  import { ConsoleLogger, LogLevel, noopLogger } from "@alineo-labs/logger";
2
- import { EgressClient, ExecClient, PtyClient, SSEEventType, SandboxState, SnapshotState } from "@alineo-labs/opensandbox";
2
+ import { AlineoError, AlineoError as AlineoError$1, errorCodeOf, errorCodeOf as errorCodeOf$1, isRetryable } from "@alineo-labs/errors";
3
3
  //#region src/ledger.ts
4
+ /**
5
+ * The provider a ledger row belongs to when it records none. Rows written before provider ids
6
+ * existed all came from OpenSandbox, so an absent `provider` means this. Readers apply it on
7
+ * read; nothing in the ledger is migrated.
8
+ */
9
+ const DEFAULT_PROVIDER_ID = "opensandbox";
4
10
  /** Status of a sandbox session derived from its ledger events. */
5
11
  let SandboxStatus = /* @__PURE__ */ function(SandboxStatus) {
6
12
  SandboxStatus["Running"] = "running";
@@ -10,75 +16,77 @@ let SandboxStatus = /* @__PURE__ */ function(SandboxStatus) {
10
16
  /** Events emitted during execution and stored in the ledger. */
11
17
  let LedgerEvent = /* @__PURE__ */ function(LedgerEvent) {
12
18
  /** Emitted when a sandbox is created and reaches Running state. */
13
- LedgerEvent["SandboxCreated"] = "sandbox_created";
19
+ LedgerEvent["SandboxCreated"] = "sandbox.created";
14
20
  /** Emitted at the start of each exec() or execCode() call. */
15
- LedgerEvent["ExecStart"] = "exec_start";
21
+ LedgerEvent["ExecStart"] = "exec.started";
16
22
  /** Streaming output chunk from exec() or execCode(). */
17
- LedgerEvent["ExecEvent"] = "exec_event";
23
+ LedgerEvent["ExecEvent"] = "exec.output";
18
24
  /** Emitted when an exec() or execCode() call completes. */
19
- LedgerEvent["ExecComplete"] = "exec_complete";
25
+ LedgerEvent["ExecComplete"] = "exec.completed";
20
26
  /** Emitted when checkpoint() captures a snapshot. */
21
- LedgerEvent["CheckpointCreated"] = "checkpoint_created";
27
+ LedgerEvent["CheckpointCreated"] = "sandbox.checkpoint_created";
22
28
  /** Emitted when a sandbox is closed. */
23
- LedgerEvent["SandboxClosed"] = "sandbox_closed";
29
+ LedgerEvent["SandboxClosed"] = "sandbox.closed";
24
30
  /** Emitted when pause() freezes the container. */
25
- LedgerEvent["SandboxPaused"] = "sandbox_paused";
31
+ LedgerEvent["SandboxPaused"] = "sandbox.paused";
26
32
  /** Emitted when resume() restores the container to Running. */
27
- LedgerEvent["SandboxResumed"] = "sandbox_resumed";
33
+ LedgerEvent["SandboxResumed"] = "sandbox.resumed";
28
34
  /**
29
35
  * Emitted by `sb.credentials.set()`/`.patch()`. Payload is binding metadata only
30
36
  * (name, host, injection type) — the credential value is never written to the ledger.
31
37
  */
32
- LedgerEvent["CredentialBound"] = "credential_bound";
38
+ LedgerEvent["CredentialBound"] = "credential.bound";
33
39
  /** Emitted by `sb.credentials.remove()`. */
34
- LedgerEvent["CredentialRevoked"] = "credential_revoked";
40
+ LedgerEvent["CredentialRevoked"] = "credential.revoked";
35
41
  /**
36
42
  * Emitted by `sb.egress.patch()`. Payload is `{ rules: NetworkRule[] }` — the exact rules
37
43
  * passed to the sidecar, so `Sandbox.resume()` can fold a still-wanted allowance back into
38
44
  * the resumed sandbox's boot policy (egress policy is sidecar-local and does not survive a
39
45
  * resume). `sb.fork()` does not carry these.
40
46
  */
41
- LedgerEvent["EgressRuleAdded"] = "egress_rule_added";
47
+ LedgerEvent["EgressRuleAdded"] = "egress.rule_added";
42
48
  /** Emitted by `sb.egress.delete()`. Payload is `{ targets: string[] }`. */
43
- LedgerEvent["EgressRuleRemoved"] = "egress_rule_removed";
49
+ LedgerEvent["EgressRuleRemoved"] = "egress.rule_removed";
44
50
  /**
45
51
  * Emitted when the permission gate pauses a tool call for human approval. Payload is
46
52
  * `{ requestId, tool, target }` — metadata only; the raw tool arguments (which can carry
47
53
  * secrets in a bash command or a file write) are never written to the ledger.
48
54
  */
49
- LedgerEvent["PermissionRequested"] = "permission_requested";
55
+ LedgerEvent["PermissionRequested"] = "permission.requested";
50
56
  /**
51
- * Emitted when a `PermissionRequested` is answered — by a caller, a batched
52
- * always/reject decision, a timeout, or a session resume dropping it. Payload is
53
- * `{ requestId, decision }`.
57
+ * Emitted when a `PermissionRequested` reaches a final state — answered by a caller, a
58
+ * batched always/reject decision, a timeout, or a session resume dropping it. Payload is
59
+ * `{ requestId, decision }`. `decision.kind` is one of `PermissionDecision`'s real answers
60
+ * (`once`/`always`/`reject`) for every case except the dropped one, which is `"dropped"` —
61
+ * deliberately not a `PermissionDecision`, because nobody answered it.
54
62
  */
55
- LedgerEvent["PermissionResolved"] = "permission_resolved";
56
- /** Emitted once when a workflow run starts, before any steps execute. */
57
- LedgerEvent["RunStarted"] = "run_started";
58
- /** Emitted at the beginning of each step. */
59
- LedgerEvent["StepStart"] = "step_start";
60
- /** Emitted when a step finishes successfully. */
61
- LedgerEvent["StepComplete"] = "step_complete";
62
- /** Emitted when a step throws an unrecoverable error. */
63
- LedgerEvent["StepFailed"] = "step_failed";
64
- /** Emitted when a step's rollback handler completes during saga compensation. */
65
- LedgerEvent["StepRolledBack"] = "step_rolled_back";
66
- /** Emitted after all steps finish without error. */
67
- LedgerEvent["WorkflowComplete"] = "workflow_complete";
68
- /** Emitted after rollback completes following a step failure. */
69
- LedgerEvent["WorkflowFailed"] = "workflow_failed";
70
- /** Durable resumption point written after each successful step. */
71
- LedgerEvent["Checkpoint"] = "checkpoint";
72
- /** Emitted when a sandbox snapshot is captured mid-run. */
73
- LedgerEvent["Snapshot"] = "snapshot";
63
+ LedgerEvent["PermissionResolved"] = "permission.resolved";
64
+ /**
65
+ * durability-roadmap M3, 3.2: emitted by the agent SDK after a turn-level checkpoint
66
+ * (workspace + session-file tarball, NOT `sb.checkpoint()`'s OpenSandbox snapshot — see
67
+ * `CheckpointCreated` above and `packages/agent/src/checkpoint.ts`'s doc comment for why the
68
+ * two are deliberately separate mechanisms) is captured and durably stored. Payload is
69
+ * `{ turn, snapshotRef, remoteRef?, uploadError? }` — `snapshotRef` is the host file and `remoteRef`
70
+ * the same tarball in object storage, when a store was given and the upload worked. Written only
71
+ * once the tarball is confirmed stored, since a
72
+ * snapshot without this event pointing at it is unreachable garbage. Shares the same
73
+ * `IStorageAdapter`-backed ledger `PermissionRequested`/`PermissionResolved` already use, so
74
+ * a standalone SDK caller and alineod both read it back the same way (`adapter.readAll`).
75
+ */
76
+ LedgerEvent["AgentCheckpointed"] = "agent.checkpointed";
74
77
  return LedgerEvent;
75
78
  }({});
76
79
  //#endregion
77
80
  //#region src/errors.ts
78
- /** Base class for all alineo workflow runtime errors. */
79
- var WorkflowError = class extends Error {
80
- constructor(message) {
81
- super(message);
81
+ /**
82
+ * Base class for all alineo workflow runtime errors.
83
+ *
84
+ * An {@link AlineoError}, so every subclass carries a stable `code`. A subclass that has not
85
+ * been given a more specific code reports `INTERNAL`.
86
+ */
87
+ var WorkflowError = class extends AlineoError$1 {
88
+ constructor(message, code = "INTERNAL", options) {
89
+ super(code, message, options);
82
90
  this.name = "WorkflowError";
83
91
  }
84
92
  };
@@ -89,8 +97,14 @@ var WorkflowError = class extends Error {
89
97
  */
90
98
  var SandboxError = class extends WorkflowError {
91
99
  sandboxId;
92
- constructor(message, sandboxId) {
93
- super(message);
100
+ constructor(message, sandboxId, code = "INTERNAL", options) {
101
+ super(message, code, {
102
+ ...options,
103
+ details: {
104
+ ...sandboxId ? { sandboxId } : {},
105
+ ...options?.details
106
+ }
107
+ });
94
108
  this.sandboxId = sandboxId;
95
109
  this.name = "SandboxError";
96
110
  }
@@ -99,19 +113,59 @@ var SandboxError = class extends WorkflowError {
99
113
  * Thrown when execd inside a sandbox never becomes ready within the retry window.
100
114
  * The sandbox is `Running` from the control plane's perspective, but the exec
101
115
  * daemon is not accepting connections.
116
+ *
117
+ * Code `EXEC_NOT_READY`. The message keeps its original leading text, and adds how long the
118
+ * probe waited and the last error it saw, so a failure on a fresh machine says why.
102
119
  */
103
120
  var ExecConnectionError = class extends WorkflowError {
104
121
  sandboxId;
105
- constructor(sandboxId) {
106
- super(`execd not ready for sandbox ${sandboxId}`);
122
+ constructor(sandboxId, failure = {}) {
123
+ super(describeExecConnectionFailure(sandboxId, failure), "EXEC_NOT_READY", {
124
+ cause: failure.cause,
125
+ details: {
126
+ sandboxId,
127
+ ...failure.attempts !== void 0 ? { attempts: failure.attempts } : {},
128
+ ...failure.waitedMs !== void 0 ? { waitedMs: failure.waitedMs } : {}
129
+ }
130
+ });
107
131
  this.sandboxId = sandboxId;
108
132
  this.name = "ExecConnectionError";
133
+ this.attempts = failure.attempts;
134
+ this.waitedMs = failure.waitedMs;
109
135
  }
136
+ /** How many readiness probes ran before giving up. */
137
+ attempts;
138
+ /** How long the readiness probe waited in total, in milliseconds. */
139
+ waitedMs;
110
140
  };
141
+ function describeExecConnectionFailure(sandboxId, f) {
142
+ let text = `execd not ready for sandbox ${sandboxId}`;
143
+ if (f.attempts !== void 0 && f.waitedMs !== void 0) text += ` after ${f.attempts} attempts over ${(f.waitedMs / 1e3).toFixed(0)}s`;
144
+ const reason = describeCause(f.cause);
145
+ if (reason) text += `. Last error: ${reason}`;
146
+ return text;
147
+ }
148
+ /** Text for a thrown value. Never throws: this runs inside an error constructor. */
149
+ function describeCause(cause) {
150
+ if (cause === void 0) return void 0;
151
+ if (cause instanceof Error) return cause.message;
152
+ if (typeof cause === "string") return cause;
153
+ try {
154
+ return JSON.stringify(cause);
155
+ } catch {
156
+ return;
157
+ }
158
+ }
159
+ function outputTail(output) {
160
+ const text = (output.stderr.trim() || output.stdout.trim()).slice(-2e3);
161
+ return text ? `\n${text}` : "";
162
+ }
111
163
  /**
112
164
  * Thrown when a command exits with a non-zero exit code. Carries the exit
113
- * code and original command. For `SandboxHandle.exec()`, only thrown when `strict`
114
- * is enabled (the default — pass `{ strict: false }` to opt out). For
165
+ * code, the original command, and the command's output: `stderr` and `stdout`
166
+ * hold all of it, and the message ends with the last 2000 characters of `stderr`
167
+ * (or of `stdout` when `stderr` is empty). For `SandboxHandle.exec()`, only thrown
168
+ * when `strict` is enabled (the default — pass `{ strict: false }` to opt out). For
115
169
  * `BashSession.exec()` (a persistent session from `createSession()`), always
116
170
  * thrown on non-zero exit; there is no `strict` option for session execs.
117
171
  */
@@ -119,12 +173,24 @@ var CommandError = class extends WorkflowError {
119
173
  exitCode;
120
174
  command;
121
175
  sandboxId;
122
- constructor(exitCode, command, sandboxId) {
123
- super(`Command exited with code ${exitCode}: ${command}`);
176
+ stdout;
177
+ stderr;
178
+ constructor(exitCode, command, sandboxId, output = {}) {
179
+ const stdout = output.stdout ?? "";
180
+ const stderr = output.stderr ?? "";
181
+ super(`Command exited with code ${exitCode}: ${command}${outputTail({
182
+ stdout,
183
+ stderr
184
+ })}`, "COMMAND_FAILED", { details: {
185
+ exitCode,
186
+ sandboxId
187
+ } });
124
188
  this.exitCode = exitCode;
125
189
  this.command = command;
126
190
  this.sandboxId = sandboxId;
127
191
  this.name = "CommandError";
192
+ this.stdout = stdout;
193
+ this.stderr = stderr;
128
194
  }
129
195
  };
130
196
  /**
@@ -136,7 +202,10 @@ var StepTimeoutError = class extends WorkflowError {
136
202
  stepId;
137
203
  timeoutMs;
138
204
  constructor(stepId, timeoutMs) {
139
- super(`Step "${stepId}" timed out after ${timeoutMs}ms`);
205
+ super(`Step "${stepId}" timed out after ${timeoutMs}ms`, "STEP_TIMEOUT", { details: {
206
+ stepId,
207
+ timeoutMs
208
+ } });
140
209
  this.stepId = stepId;
141
210
  this.timeoutMs = timeoutMs;
142
211
  this.name = "StepTimeoutError";
@@ -158,7 +227,7 @@ async function resolveBoundCredential(name, source, resolver, sandboxId) {
158
227
  }
159
228
  const fromResolver = await resolver?.(name, source ?? { type: "external" });
160
229
  if (fromResolver !== void 0) return fromResolver;
161
- throw new SandboxError(`Cannot resolve credential "${name}" for sandbox ${sandboxId}` + (source?.type === "env" ? ` (env var "${source.varName}" is not set)` : ` (source: ${source?.type ?? "unknown"})`) + ` — pass a resolveCredential callback that returns a value for it.`, sandboxId);
230
+ throw new SandboxError(`Cannot resolve credential "${name}" for sandbox ${sandboxId}` + (source?.type === "env" ? ` (env var "${source.varName}" is not set)` : ` (source: ${source?.type ?? "unknown"})`) + ` — pass a resolveCredential callback that returns a value for it.`, sandboxId, "CREDENTIAL_UNRESOLVED", { details: { credential: name } });
162
231
  }
163
232
  /**
164
233
  * Reconstructs the latest bound/revoked state per credential name from a session's ledger
@@ -169,13 +238,13 @@ async function resolveBoundCredential(name, source, resolver, sandboxId) {
169
238
  */
170
239
  function reconstructBoundCredentials(entries) {
171
240
  const result = /* @__PURE__ */ new Map();
172
- for (const entry of entries) if (entry.event === "credential_bound") {
241
+ for (const entry of entries) if (entry.event === "credential.bound") {
173
242
  const { name, binding, source } = entry.payload;
174
243
  result.set(name, {
175
244
  binding,
176
245
  source
177
246
  });
178
- } else if (entry.event === "credential_revoked") {
247
+ } else if (entry.event === "credential.revoked") {
179
248
  const { name } = entry.payload;
180
249
  result.delete(name);
181
250
  }
@@ -198,13 +267,13 @@ function reconstructBoundCredentials(entries) {
198
267
  function reconstructEgressRules(entries) {
199
268
  const byTarget = /* @__PURE__ */ new Map();
200
269
  const removed = /* @__PURE__ */ new Set();
201
- for (const entry of entries) if (entry.event === "egress_rule_added") {
270
+ for (const entry of entries) if (entry.event === "egress.rule_added") {
202
271
  const { rules } = entry.payload;
203
272
  for (const rule of rules) {
204
273
  byTarget.set(rule.target, rule);
205
274
  removed.delete(rule.target);
206
275
  }
207
- } else if (entry.event === "egress_rule_removed") {
276
+ } else if (entry.event === "egress.rule_removed") {
208
277
  const { targets } = entry.payload;
209
278
  for (const target of targets) {
210
279
  byTarget.delete(target);
@@ -218,6 +287,8 @@ function reconstructEgressRules(entries) {
218
287
  }
219
288
  //#endregion
220
289
  //#region src/exec-handle.ts
290
+ /** The shell convention for "found the command but could not run it". */
291
+ const START_FAILED_EXIT_CODE = 126;
221
292
  /**
222
293
  * Returned by `SandboxHandle.exec()` and `SandboxHandle.execCode()`.
223
294
  *
@@ -252,7 +323,7 @@ var ExecHandle = class {
252
323
  this._promise = this._drainPty(driver);
253
324
  this._promise.catch(() => {});
254
325
  } else {
255
- this._promise = this._drain(driver.gen, driver.onDone);
326
+ this._promise = this._drain(driver.gen, driver.onDone, driver.timeoutMs);
256
327
  this._promise.catch(() => {});
257
328
  }
258
329
  }
@@ -286,19 +357,29 @@ var ExecHandle = class {
286
357
  });
287
358
  });
288
359
  }
289
- async _drain(gen, onDone) {
360
+ async _drain(gen, onDone, timeoutMs) {
290
361
  const stderr = [];
291
362
  let exitCode = 0;
363
+ let signal;
364
+ const startedAt = Date.now();
292
365
  try {
293
366
  for await (const ev of gen) {
294
- if (ev.type === SSEEventType.Stdout && ev.text) {
367
+ if (ev.type === "stdout" && ev.text) {
295
368
  this._chunks.push(ev.text);
296
369
  this._notify();
297
370
  }
298
- if (ev.type === SSEEventType.Stderr && ev.text) stderr.push(ev.text);
299
- if (ev.type === SSEEventType.Error && ev.error?.evalue !== void 0) {
371
+ if (ev.type === "stderr" && ev.text) stderr.push(ev.text);
372
+ if (ev.type === "error" && ev.error?.evalue !== void 0) {
300
373
  const code = Number(ev.error.evalue);
301
374
  if (!isNaN(code)) exitCode = code;
375
+ else {
376
+ exitCode = START_FAILED_EXIT_CODE;
377
+ stderr.push(`${ev.error.evalue}\n`);
378
+ }
379
+ }
380
+ for (const line of ev.error?.traceback ?? []) {
381
+ const match = /^signal: (.+)$/.exec(line);
382
+ if (match) signal = match[1];
302
383
  }
303
384
  }
304
385
  } catch (err) {
@@ -309,10 +390,17 @@ var ExecHandle = class {
309
390
  this._done = true;
310
391
  this._notify();
311
392
  }
393
+ const durationMs = Date.now() - startedAt;
312
394
  const result = {
313
395
  stdout: this._chunks.join(""),
314
396
  stderr: stderr.join(""),
315
- exitCode
397
+ exitCode,
398
+ durationMs,
399
+ ...signal !== void 0 ? {
400
+ killed: true,
401
+ signal,
402
+ timedOut: timeoutMs !== void 0 && durationMs >= timeoutMs - 250
403
+ } : {}
316
404
  };
317
405
  await onDone(result);
318
406
  return result;
@@ -413,39 +501,25 @@ var InteractiveExecHandle = class extends ExecHandle {
413
501
  //#endregion
414
502
  //#region src/sandbox/resolve.ts
415
503
  /**
416
- * Resolve an ExecClient for a sandbox. Calls getEndpoint once (each call
417
- * returns a different ephemeral proxy port) then polls listContexts until
418
- * execd is ready to accept connections.
504
+ * A channel to run commands in a sandbox, from its provider.
419
505
  *
420
- * Defaults give ~80s of total patience (retries=45, capped at 2s/attempt), not the ~11s this
421
- * had before (retries=15, capped at 1s/attempt). Bumped after a live `alineo fork` failure
422
- * (issue #32): a child forked while its parent sandbox was busy running a real Chrome session
423
- * took ~35s just to reach `Running`, then immediately exhausted the old ~11s execd-readiness
424
- * budget before the exec daemon inside it had actually started accepting connections. An
425
- * isolated repro of the identical fork (same snapshot, but from an idle parent with no
426
- * concurrent browser load) reached execd-ready in under 400ms -- the parent's own host-resource
427
- * contention at fork time, not snapshot size, is what actually eats the budget. This can't be
428
- * fixed by scheduling around it from here, so it's addressed by simply affording much more
429
- * patience before giving up.
506
+ * The provider owns the wait: it resolves once the sandbox accepts a connection, and rejects with
507
+ * `EXEC_NOT_READY` when it never does. That failure is re-thrown as `ExecConnectionError`, with
508
+ * the cause, the attempt count, and the wait the provider recorded, because that class is the
509
+ * one callers have been catching and it extends `WorkflowError`.
430
510
  */
431
- async function resolveExecClient(control, sandboxId, useServerProxy, retries = 45, delayMs = 2e3) {
432
- const ep = await control.getEndpoint(sandboxId, 44772, useServerProxy);
433
- const baseUrl = ep.endpoint.startsWith("http") ? ep.endpoint : `http://${ep.endpoint}`;
434
- const token = ep.headers?.["X-EXECD-ACCESS-TOKEN"] ?? "";
435
- const client = new ExecClient({
436
- baseUrl,
437
- accessToken: token
438
- });
439
- let delay = Math.min(100, delayMs);
440
- for (let attempt = 0; attempt <= retries; attempt++) try {
441
- await client.listContexts();
442
- return client;
443
- } catch {
444
- if (attempt === retries) throw new ExecConnectionError(sandboxId);
445
- await new Promise((r) => setTimeout(r, delay));
446
- delay = Math.min(delay * 1.5, delayMs);
511
+ async function resolveExecChannel(provider, sandboxId, options = {}) {
512
+ try {
513
+ return await provider.connectExec(sandboxId, options);
514
+ } catch (err) {
515
+ if (errorCodeOf$1(err) !== "EXEC_NOT_READY") throw err;
516
+ const details = err.details;
517
+ throw new ExecConnectionError(sandboxId, {
518
+ cause: err.cause ?? err,
519
+ attempts: details?.attempts,
520
+ waitedMs: details?.waitedMs
521
+ });
447
522
  }
448
- throw new Error("unreachable");
449
523
  }
450
524
  //#endregion
451
525
  //#region src/sandbox/bash-session.ts
@@ -497,6 +571,10 @@ var BashSession = class {
497
571
  */
498
572
  var SandboxCore = class {
499
573
  sandboxId;
574
+ /** The id of the sandbox provider that owns this sandbox (`"opensandbox"`). */
575
+ get provider() {
576
+ return this.deps.provider.id;
577
+ }
500
578
  name;
501
579
  deps;
502
580
  /** Cached exec results for replay mode (populated by `Sandbox.resume()`). */
@@ -550,56 +628,73 @@ var SandboxCore = class {
550
628
  nextSeq() {
551
629
  return ++this._seq;
552
630
  }
553
- async getExecClient() {
554
- if (this._paused) throw new SandboxError("sandbox is paused — call resume() first", this.sandboxId);
555
- this._execClient ??= await resolveExecClient(this.deps.control, this.sandboxId, this.deps.useServerProxy);
631
+ /**
632
+ * The channel to this sandbox's `execd`, connecting if there is none yet. `signal` stops the
633
+ * wait for a sandbox that is slow to accept a connection. It does not close a channel that was
634
+ * already connected.
635
+ */
636
+ async getExecClient(signal) {
637
+ if (this._paused) throw new SandboxError("sandbox is paused — call resume() first", this.sandboxId, "SANDBOX_PAUSED");
638
+ this._execClient ??= await resolveExecChannel(this.deps.provider, this.sandboxId, { signal });
556
639
  return this._execClient;
557
640
  }
558
- /** Resolve a fresh `PtyClient` for a new interactive session. Reuses `getExecClient()`'s readiness wait. */
641
+ /** Resolve a fresh terminal channel for a new interactive session. Reuses `getExecClient()`'s readiness wait. */
559
642
  async resolvePtyClient() {
560
- if (this._paused) throw new SandboxError("sandbox is paused — call resume() first", this.sandboxId);
643
+ if (this._paused) throw new SandboxError("sandbox is paused — call resume() first", this.sandboxId, "SANDBOX_PAUSED");
561
644
  await this.getExecClient();
562
- const ep = await this.deps.control.getEndpoint(this.sandboxId, 44772, this.deps.useServerProxy);
563
- const baseUrl = ep.endpoint.startsWith("http") ? ep.endpoint : `http://${ep.endpoint}`;
564
- const token = ep.headers?.["X-EXECD-ACCESS-TOKEN"] ?? "";
565
- return new PtyClient({
566
- baseUrl,
567
- accessToken: token
568
- });
645
+ if (!this.deps.provider.connectPty) throw new SandboxError(`The ${this.deps.provider.id} provider has no interactive terminal`, this.sandboxId, "CAPABILITY_UNSUPPORTED", { details: {
646
+ capability: "pty",
647
+ provider: this.deps.provider.id
648
+ } });
649
+ return this.deps.provider.connectPty(this.sandboxId);
569
650
  }
570
651
  async waitForRunning(timeoutMs = 12e4) {
571
652
  const deadline = Date.now() + timeoutMs;
572
653
  let delay = 100;
573
654
  while (Date.now() < deadline) {
574
- const s = await this.deps.control.getSandbox(this.sandboxId);
575
- if (s.status.state === SandboxState.Running) return;
576
- if (s.status.state === SandboxState.Failed || s.status.state === SandboxState.Terminated) throw new SandboxError(`SandboxHandle entered ${s.status.state}: ${s.status.message ?? ""}`, this.sandboxId);
655
+ const s = await this.deps.provider.getSandbox(this.sandboxId);
656
+ if (s.state === "running") return;
657
+ if (s.state === "failed" || s.state === "terminated") throw new SandboxError(`SandboxHandle entered ${s.nativeState ?? s.state}: ${s.message ?? ""}`, this.sandboxId, "SANDBOX_START_FAILED");
577
658
  await new Promise((r) => setTimeout(r, delay));
578
659
  delay = Math.min(delay * 1.5, 1e3);
579
660
  }
580
- throw new SandboxError(`SandboxHandle did not reach Running within ${timeoutMs}ms`, this.sandboxId);
661
+ throw new SandboxError(`SandboxHandle did not reach Running within ${timeoutMs}ms`, this.sandboxId, "SANDBOX_START_TIMEOUT");
581
662
  }
582
663
  async waitForSnapshot(snapshotId, timeoutMs = 12e4) {
583
664
  const deadline = Date.now() + timeoutMs;
584
665
  let delay = 100;
585
666
  while (Date.now() < deadline) {
586
- const snap = await this.deps.control.getSnapshot(snapshotId);
587
- if (snap.state === SnapshotState.Ready) return;
588
- if (snap.state === SnapshotState.Failed) throw new SandboxError(`Snapshot ${snapshotId} failed`, this.sandboxId);
667
+ const snap = await this.deps.provider.getSnapshot(snapshotId);
668
+ if (snap.state === "ready") return;
669
+ if (snap.state === "failed") throw new SandboxError(`Snapshot ${snapshotId} failed`, this.sandboxId, "SNAPSHOT_FAILED");
589
670
  await new Promise((r) => setTimeout(r, delay));
590
671
  delay = Math.min(delay * 1.5, 2e3);
591
672
  }
592
- throw new SandboxError(`Snapshot ${snapshotId} did not become ready within ${timeoutMs}ms`, this.sandboxId);
673
+ throw new SandboxError(`Snapshot ${snapshotId} did not become ready within ${timeoutMs}ms`, this.sandboxId, "SNAPSHOT_TIMEOUT");
593
674
  }
594
675
  emit(event, stepIndex, payload) {
676
+ const ts = Date.now();
595
677
  const entry = {
596
- ts: Date.now(),
678
+ ts,
597
679
  name: this.name,
598
680
  sandboxId: this.sandboxId,
599
681
  stepIndex,
600
682
  event,
601
683
  payload
602
684
  };
685
+ if (this.deps.sink) try {
686
+ this.deps.sink({
687
+ v: 1,
688
+ ts,
689
+ type: event,
690
+ data: {
691
+ sandboxId: this.sandboxId,
692
+ name: this.name,
693
+ stepIndex,
694
+ payload
695
+ }
696
+ });
697
+ } catch {}
603
698
  const result = this._ledgerQueue.then(() => this.deps.adapter.append(entry));
604
699
  this._ledgerQueue = result.catch(() => {});
605
700
  return result;
@@ -614,37 +709,43 @@ var SandboxCore = class {
614
709
  });
615
710
  const self = this;
616
711
  async function* stream() {
617
- const execClient = await self.getExecClient();
618
- await self.emit("exec_start", seq, {
712
+ opts.signal?.throwIfAborted();
713
+ const baseClient = await self.getExecClient(opts.signal);
714
+ await self.emit("exec.started", seq, {
619
715
  cmd,
620
716
  seq
621
717
  });
622
718
  self.deps.hooks?.onExecStart?.(self.sandboxId, seq, cmd);
623
- const sh = opts.shell ?? self.deps.shell ?? "/bin/sh";
624
- const command = `echo ${Buffer.from(cmd).toString("base64")} | base64 -d | ${sh}`;
625
- for await (const ev of execClient.executeCommand({
626
- command,
627
- cwd: opts.cwd,
628
- envs: opts.env,
629
- timeout: opts.timeoutMs
630
- })) {
631
- await self.emit("exec_event", seq, {
632
- seq,
633
- ...ev
634
- });
635
- yield ev;
719
+ const execClient = opts.signal ? baseClient.withSignal(opts.signal) : baseClient;
720
+ const interrupt = () => void baseClient.interruptCommand().catch(() => {});
721
+ opts.signal?.addEventListener("abort", interrupt, { once: true });
722
+ try {
723
+ const sh = opts.shell ?? self.deps.shell ?? "/bin/sh";
724
+ const command = `echo ${Buffer.from(cmd).toString("base64")} | base64 -d | ${sh}`;
725
+ for await (const ev of execClient.executeCommand({
726
+ command,
727
+ cwd: opts.cwd,
728
+ envs: opts.env,
729
+ timeout: opts.timeoutMs
730
+ })) {
731
+ await self.emit("exec.output", seq, {
732
+ seq,
733
+ ...ev
734
+ });
735
+ yield ev;
736
+ }
737
+ } finally {
738
+ opts.signal?.removeEventListener("abort", interrupt);
636
739
  }
637
740
  }
638
741
  return new ExecHandle({
639
742
  type: "stream",
640
743
  gen: stream(),
744
+ timeoutMs: opts.timeoutMs,
641
745
  onDone: async (result) => {
642
- await self.emit("exec_complete", seq, {
643
- exitCode: result.exitCode,
644
- seq
645
- });
746
+ await self.emit("exec.completed", seq, execCompletedPayload(result, seq));
646
747
  self.deps.hooks?.onExecComplete?.(self.sandboxId, seq, result);
647
- if (opts.strict !== false && result.exitCode !== 0) throw new CommandError(result.exitCode, cmd, self.sandboxId);
748
+ if (opts.strict !== false && result.exitCode !== 0) throw new CommandError(result.exitCode, cmd, self.sandboxId, result);
648
749
  }
649
750
  });
650
751
  }
@@ -659,7 +760,7 @@ var SandboxCore = class {
659
760
  const pending = this.pendingInteractive.get(seq);
660
761
  const self = this;
661
762
  let closer;
662
- const execStartLogged = self.emit("exec_start", seq, {
763
+ const execStartLogged = self.emit("exec.started", seq, {
663
764
  cmd,
664
765
  seq,
665
766
  interactive: true,
@@ -681,7 +782,7 @@ var SandboxCore = class {
681
782
  await pty.connect(sessionId, (chunk) => {
682
783
  onFirstOutput?.();
683
784
  onFirstOutput = void 0;
684
- self.emit("exec_event", seq, {
785
+ self.emit("exec.output", seq, {
685
786
  seq,
686
787
  type: "stdout",
687
788
  text: chunk
@@ -715,16 +816,16 @@ var SandboxCore = class {
715
816
  },
716
817
  onDone: async (result) => {
717
818
  if (closer) self.openSessionClosers.delete(closer);
718
- await self.emit("exec_complete", seq, {
819
+ await self.emit("exec.completed", seq, {
719
820
  exitCode: result.exitCode,
720
821
  seq
721
822
  });
722
823
  self.deps.hooks?.onExecComplete?.(self.sandboxId, seq, result);
723
- if (opts.strict !== false && result.exitCode !== 0) throw new CommandError(result.exitCode, cmd, self.sandboxId);
824
+ if (opts.strict !== false && result.exitCode !== 0) throw new CommandError(result.exitCode, cmd, self.sandboxId, result);
724
825
  }
725
826
  }, {
726
827
  write: (data) => {
727
- execStartLogged.then(() => self.emit("exec_event", seq, {
828
+ execStartLogged.then(() => self.emit("exec.output", seq, {
728
829
  seq,
729
830
  type: "stdin",
730
831
  text: data
@@ -785,7 +886,7 @@ var SandboxCore = class {
785
886
  const self = this;
786
887
  async function* stream() {
787
888
  const execClient = await self.getExecClient();
788
- await self.emit("exec_start", seq, {
889
+ await self.emit("exec.started", seq, {
789
890
  code,
790
891
  seq
791
892
  });
@@ -793,7 +894,7 @@ var SandboxCore = class {
793
894
  code,
794
895
  context: opts.context
795
896
  })) {
796
- await self.emit("exec_event", seq, {
897
+ await self.emit("exec.output", seq, {
797
898
  seq,
798
899
  ...ev
799
900
  });
@@ -804,7 +905,7 @@ var SandboxCore = class {
804
905
  type: "stream",
805
906
  gen: stream(),
806
907
  onDone: async (result) => {
807
- await self.emit("exec_complete", seq, {
908
+ await self.emit("exec.completed", seq, {
808
909
  exitCode: result.exitCode,
809
910
  seq
810
911
  });
@@ -837,7 +938,7 @@ var SandboxCore = class {
837
938
  const execInSession = (command, cmdOpts) => {
838
939
  const seq = ++self._seq;
839
940
  async function* stream() {
840
- await self.emit("exec_start", seq, {
941
+ await self.emit("exec.started", seq, {
841
942
  cmd: command,
842
943
  seq,
843
944
  sessionId
@@ -848,7 +949,7 @@ var SandboxCore = class {
848
949
  cwd: cmdOpts?.cwd,
849
950
  timeout: cmdOpts?.timeoutMs
850
951
  })) {
851
- await self.emit("exec_event", seq, {
952
+ await self.emit("exec.output", seq, {
852
953
  seq,
853
954
  ...ev
854
955
  });
@@ -859,12 +960,12 @@ var SandboxCore = class {
859
960
  type: "stream",
860
961
  gen: stream(),
861
962
  onDone: async (result) => {
862
- await self.emit("exec_complete", seq, {
963
+ await self.emit("exec.completed", seq, {
863
964
  exitCode: result.exitCode,
864
965
  seq
865
966
  });
866
967
  self.deps.hooks?.onExecComplete?.(self.sandboxId, seq, result);
867
- if (result.exitCode !== 0) throw new CommandError(result.exitCode, command, self.sandboxId);
968
+ if (result.exitCode !== 0) throw new CommandError(result.exitCode, command, self.sandboxId, result);
868
969
  }
869
970
  });
870
971
  };
@@ -876,14 +977,40 @@ var SandboxCore = class {
876
977
  return new BashSession(sessionId, execInSession, closeSession);
877
978
  }
878
979
  };
980
+ /**
981
+ * What `exec.completed` records. The optional fields appear only when they say something, so a
982
+ * row for an ordinary command is the same as it was before they existed.
983
+ */
984
+ function execCompletedPayload(result, seq) {
985
+ return {
986
+ exitCode: result.exitCode,
987
+ seq,
988
+ ...result.durationMs !== void 0 ? { durationMs: result.durationMs } : {},
989
+ ...result.killed ? {
990
+ killed: true,
991
+ signal: result.signal
992
+ } : {},
993
+ ...result.timedOut ? { timedOut: true } : {}
994
+ };
995
+ }
879
996
  //#endregion
880
997
  //#region src/sandbox/files.ts
881
998
  /** Write a file into the sandbox. */
882
999
  async function writeFile(sb, path, content) {
883
1000
  await (await sb.getExecClient()).uploadFile(path, content);
884
1001
  }
885
- /** Read a file from the sandbox as a UTF-8 string. */
886
- async function readFile(sb, path) {
1002
+ /** Write raw bytes into the sandbox — for binary content (a gzip tarball, an image) that
1003
+ * `writeFile`'s string-typed signature would push a caller toward corrupting via a lossy
1004
+ * decode/re-encode round trip before it ever reaches this function. */
1005
+ async function writeFileBytes(sb, path, bytes) {
1006
+ await (await sb.getExecClient()).uploadFile(path, new Uint8Array(bytes));
1007
+ }
1008
+ /**
1009
+ * Read a file from the sandbox as raw bytes — no `TextDecoder`, so binary content (a gzip
1010
+ * tarball, an image) round-trips intact. `readFile()` below is this plus a UTF-8 decode; a
1011
+ * caller that needs the decode uses that instead, not this one re-encoded.
1012
+ */
1013
+ async function readFileBytes(sb, path) {
887
1014
  const reader = (await (await sb.getExecClient()).downloadFile(path)).getReader();
888
1015
  const chunks = [];
889
1016
  while (true) {
@@ -898,7 +1025,11 @@ async function readFile(sb, path) {
898
1025
  merged.set(chunk, offset);
899
1026
  offset += chunk.length;
900
1027
  }
901
- return new TextDecoder().decode(merged);
1028
+ return merged;
1029
+ }
1030
+ /** Read a file from the sandbox as a UTF-8 string. */
1031
+ async function readFile(sb, path) {
1032
+ return new TextDecoder().decode(await readFileBytes(sb, path));
902
1033
  }
903
1034
  /** Delete a file from the sandbox. */
904
1035
  async function deleteFile(sb, path) {
@@ -937,6 +1068,27 @@ async function replaceInFiles(sb, replacements) {
937
1068
  await (await sb.getExecClient()).replaceInFiles(replacements);
938
1069
  }
939
1070
  //#endregion
1071
+ //#region src/sandbox/capabilities.ts
1072
+ /**
1073
+ * Throw `CAPABILITY_UNSUPPORTED`, naming the capability and the provider, when the provider
1074
+ * declares it cannot do something.
1075
+ *
1076
+ * Only an explicit `false` is a refusal. `"unverified"` (configured, not proven) goes ahead and
1077
+ * may still fail at the call, and a provider with no descriptor, which is what a test double
1078
+ * usually is, is not second-guessed.
1079
+ *
1080
+ * This is the early failure: a spec that needs egress, or a `checkpoint()` on a provider that
1081
+ * cannot snapshot, is refused before anything is created or sent, with a message that names the
1082
+ * missing capability instead of a failure three calls later that reads like a bad spec.
1083
+ */
1084
+ function requireCapability(provider, capability, sandboxId) {
1085
+ if (provider.descriptor?.capabilities?.[capability] !== false) return;
1086
+ throw new SandboxError(`The ${provider.id} provider does not support ${capability}`, sandboxId, "CAPABILITY_UNSUPPORTED", { details: {
1087
+ capability,
1088
+ provider: provider.id
1089
+ } });
1090
+ }
1091
+ //#endregion
940
1092
  //#region src/sandbox/lifecycle.ts
941
1093
  /** Return all checkpoints for this sandbox in creation order. */
942
1094
  function listCheckpoints(sb) {
@@ -950,11 +1102,12 @@ function listCheckpoints(sb) {
950
1102
  * `close()` remains valid on a paused sandbox.
951
1103
  */
952
1104
  async function pause(sb) {
953
- await sb.deps.control.pauseSandbox(sb.sandboxId);
1105
+ requireCapability(sb.deps.provider, "pause", sb.sandboxId);
1106
+ await sb.deps.provider.pauseSandbox(sb.sandboxId);
954
1107
  sb.setPaused(true);
955
1108
  sb.disposeExecClient();
956
1109
  sb.clearExecClient();
957
- await sb.emit("sandbox_paused", -1);
1110
+ await sb.emit("sandbox.paused", -1);
958
1111
  sb.deps.hooks?.onSandboxPaused?.(sb.sandboxId);
959
1112
  }
960
1113
  /**
@@ -967,10 +1120,11 @@ async function pause(sb) {
967
1120
  * Polls until the sandbox reports Running before returning.
968
1121
  */
969
1122
  async function resume(sb) {
970
- await sb.deps.control.resumeSandbox(sb.sandboxId);
1123
+ requireCapability(sb.deps.provider, "pause", sb.sandboxId);
1124
+ await sb.deps.provider.resumeSandbox(sb.sandboxId);
971
1125
  sb.setPaused(false);
972
1126
  await sb.waitForRunning();
973
- await sb.emit("sandbox_resumed", -1);
1127
+ await sb.emit("sandbox.resumed", -1);
974
1128
  sb.deps.hooks?.onSandboxResumed?.(sb.sandboxId);
975
1129
  }
976
1130
  /**
@@ -981,9 +1135,10 @@ async function resume(sb) {
981
1135
  * the latest checkpoint, or pass the returned ID to `Sandbox.restoreSnapshot()`.
982
1136
  */
983
1137
  async function checkpoint(sb, name) {
984
- const snap = await sb.deps.control.createSnapshot(sb.sandboxId);
1138
+ requireCapability(sb.deps.provider, "snapshot", sb.sandboxId);
1139
+ const snap = await sb.deps.provider.createSnapshot(sb.sandboxId);
985
1140
  await sb.waitForSnapshot(snap.id);
986
- await sb.emit("checkpoint_created", -1, {
1141
+ await sb.emit("sandbox.checkpoint_created", -1, {
987
1142
  snapshotId: snap.id,
988
1143
  name
989
1144
  });
@@ -999,7 +1154,7 @@ async function checkpoint(sb, name) {
999
1154
  *
1000
1155
  * @param runId Override the forked sandbox's run correlation ID instead of inheriting
1001
1156
  * whatever this sandbox's own creation closed over. Needed when forking across a process
1002
- * boundary (e.g. `alineo fork`, which re-`Alineo.attach()`es in a brand-new CLI process with
1157
+ * boundary (e.g. `alineo spawn`, which re-`Alineo.attach()`es in a brand-new CLI process with
1003
1158
  * no access to the original in-memory closure) — the caller reads the correct value from
1004
1159
  * `process.env.ALINEO_RUN_ID` and passes it explicitly rather than relying on this sandbox's
1005
1160
  * own (possibly unknown) default.
@@ -1020,10 +1175,11 @@ async function checkpoint(sb, name) {
1020
1175
  * of `opts.resourceId` — pass either, both, or neither.
1021
1176
  */
1022
1177
  async function fork(sb, tag, runId, opts) {
1023
- if (!sb.deps.fork) throw new SandboxError("fork() is not supported on this sandbox", sb.sandboxId);
1024
- const snap = await sb.deps.control.createSnapshot(sb.sandboxId);
1178
+ if (!sb.deps.fork) throw new SandboxError("fork() is not supported on this sandbox", sb.sandboxId, "CAPABILITY_UNSUPPORTED", { details: { capability: "fork" } });
1179
+ requireCapability(sb.deps.provider, "snapshot", sb.sandboxId);
1180
+ const snap = await sb.deps.provider.createSnapshot(sb.sandboxId);
1025
1181
  await sb.waitForSnapshot(snap.id);
1026
- await sb.emit("checkpoint_created", -1, {
1182
+ await sb.emit("sandbox.checkpoint_created", -1, {
1027
1183
  snapshotId: snap.id,
1028
1184
  name: tag
1029
1185
  });
@@ -1059,9 +1215,9 @@ async function close(sb) {
1059
1215
  sb.openSessionClosers.clear();
1060
1216
  sb.disposeExecClient();
1061
1217
  try {
1062
- await sb.deps.control.deleteSandbox(sb.sandboxId);
1218
+ await sb.deps.provider.deleteSandbox(sb.sandboxId);
1063
1219
  } finally {
1064
- await sb.emit("sandbox_closed", -1);
1220
+ await sb.emit("sandbox.closed", -1);
1065
1221
  sb.deps.hooks?.onSandboxClosed?.(sb.sandboxId);
1066
1222
  sb.deps.onClose?.();
1067
1223
  }
@@ -1083,17 +1239,17 @@ async function* watchMetrics(sb) {
1083
1239
  const ec = await sb.getExecClient();
1084
1240
  for await (const ev of ec.watchMetrics()) if (isMetrics(ev)) yield ev;
1085
1241
  }
1086
- /** `ExecClient.watchMetrics()` types every SSE payload as `SSEEvent`; this checks it's actually metrics. */
1242
+ /** `watchMetrics()` types every event payload as an `ExecEvent`; this checks it's actually metrics. */
1087
1243
  function isMetrics(ev) {
1088
1244
  return "cpu" in ev && typeof ev.cpu === "number" && "memory" in ev && typeof ev.memory === "number";
1089
1245
  }
1090
1246
  /** Return sandbox diagnostic logs (names, sizes, and optional inline content). */
1091
1247
  async function diagnosticLogs(sb) {
1092
- return sb.deps.control.getDiagnosticLogs(sb.sandboxId);
1248
+ return sb.deps.provider.getDiagnosticLogs(sb.sandboxId);
1093
1249
  }
1094
1250
  /** Return sandbox diagnostic events (timestamps, types, and messages). */
1095
1251
  async function diagnosticEvents(sb) {
1096
- return sb.deps.control.getDiagnosticEvents(sb.sandboxId);
1252
+ return sb.deps.provider.getDiagnosticEvents(sb.sandboxId);
1097
1253
  }
1098
1254
  /**
1099
1255
  * Return a proxied URL and auth headers for a port inside the sandbox.
@@ -1101,7 +1257,7 @@ async function diagnosticEvents(sb) {
1101
1257
  * Use this to send HTTP requests to a server running inside the sandbox.
1102
1258
  */
1103
1259
  async function proxy(sb, port) {
1104
- const ep = await sb.deps.control.getEndpoint(sb.sandboxId, port, sb.deps.useServerProxy);
1260
+ const ep = await sb.deps.provider.getEndpoint(sb.sandboxId, port);
1105
1261
  return {
1106
1262
  url: ep.endpoint.startsWith("http") ? ep.endpoint : `http://${ep.endpoint}`,
1107
1263
  headers: ep.headers ?? {}
@@ -1111,7 +1267,7 @@ async function proxy(sb, port) {
1111
1267
  //#region src/sandbox/credentials.ts
1112
1268
  function requireBroker(sb) {
1113
1269
  const broker = sb.deps.credentialBroker;
1114
- if (!broker) throw new SandboxError("No CredentialBroker configured — pass credentialProxy: true to client.sandbox() (and ensure the OpenSandbox server has egress.image configured) to use sb.credentials.*", sb.sandboxId);
1270
+ if (!broker) throw new SandboxError("No CredentialBroker configured — pass credentialProxy: true to client.sandbox() (and ensure the OpenSandbox server has egress.image configured) to use sb.credentials.*", sb.sandboxId, "CAPABILITY_UNSUPPORTED", { details: { capability: "credentials" } });
1115
1271
  return broker;
1116
1272
  }
1117
1273
  /**
@@ -1124,7 +1280,7 @@ function requireBroker(sb) {
1124
1280
  */
1125
1281
  async function set(sb, name, value, binding, source) {
1126
1282
  await requireBroker(sb).set(sb.sandboxId, name, value, binding);
1127
- await sb.emit("credential_bound", -1, {
1283
+ await sb.emit("credential.bound", -1, {
1128
1284
  name,
1129
1285
  binding,
1130
1286
  source
@@ -1144,7 +1300,7 @@ async function patch$1(sb, name, changes) {
1144
1300
  binding: changes.binding
1145
1301
  });
1146
1302
  if (changes.binding) {
1147
- await sb.emit("credential_bound", -1, {
1303
+ await sb.emit("credential.bound", -1, {
1148
1304
  name,
1149
1305
  binding: changes.binding,
1150
1306
  source: changes.source
@@ -1155,7 +1311,7 @@ async function patch$1(sb, name, changes) {
1155
1311
  /** Revoke a credential — subsequent matching requests are no longer injected. */
1156
1312
  async function remove$1(sb, name) {
1157
1313
  await requireBroker(sb).remove(sb.sandboxId, name);
1158
- await sb.emit("credential_revoked", -1, { name });
1314
+ await sb.emit("credential.revoked", -1, { name });
1159
1315
  }
1160
1316
  /** List binding metadata (host/injection shape) for this sandbox — never returns values. */
1161
1317
  async function listBindings(sb) {
@@ -1163,8 +1319,15 @@ async function listBindings(sb) {
1163
1319
  }
1164
1320
  //#endregion
1165
1321
  //#region src/sandbox/egress.ts
1322
+ /** The provider's egress control, or a typed error when it has none. */
1166
1323
  function client(sb) {
1167
- return new EgressClient(sb.deps.control, sb.deps.useServerProxy);
1324
+ requireCapability(sb.deps.provider, "egress", sb.sandboxId);
1325
+ const egress = sb.deps.provider.egress;
1326
+ if (!egress) throw new SandboxError(`The ${sb.deps.provider.id} provider cannot change a sandbox's egress rules at runtime`, sb.sandboxId, "CAPABILITY_UNSUPPORTED", { details: {
1327
+ capability: "egress",
1328
+ provider: sb.deps.provider.id
1329
+ } });
1330
+ return egress;
1168
1331
  }
1169
1332
  /**
1170
1333
  * Merge allow/deny rules into this sandbox's live egress policy. An incoming rule replaces
@@ -1178,12 +1341,12 @@ function client(sb) {
1178
1341
  */
1179
1342
  async function patch(sb, rules) {
1180
1343
  await client(sb).patchRules(sb.sandboxId, rules);
1181
- await sb.emit("egress_rule_added", -1, { rules });
1344
+ await sb.emit("egress.rule_added", -1, { rules });
1182
1345
  }
1183
1346
  /** Remove egress rules from this sandbox's live policy, by `target`. Unknown targets are ignored. */
1184
1347
  async function remove(sb, targets) {
1185
1348
  await client(sb).deleteRules(sb.sandboxId, targets);
1186
- await sb.emit("egress_rule_removed", -1, { targets });
1349
+ await sb.emit("egress.rule_removed", -1, { targets });
1187
1350
  }
1188
1351
  /** This sandbox's current egress policy, as the sidecar reports it. */
1189
1352
  async function get(sb) {
@@ -1212,10 +1375,20 @@ var SandboxHandle = class extends SandboxCore {
1212
1375
  async writeFile(path, content) {
1213
1376
  return writeFile(this, path, content);
1214
1377
  }
1378
+ /** Write raw bytes into the sandbox — for binary content `writeFile`'s string-typed
1379
+ * signature isn't safe for (a gzip tarball, an image). */
1380
+ async writeFileBytes(path, bytes) {
1381
+ return writeFileBytes(this, path, bytes);
1382
+ }
1215
1383
  /** Read a file from the sandbox as a UTF-8 string. */
1216
1384
  async readFile(path) {
1217
1385
  return readFile(this, path);
1218
1386
  }
1387
+ /** Read a file from the sandbox as raw bytes — for binary content `readFile`'s UTF-8
1388
+ * decode would corrupt (a gzip tarball, an image). */
1389
+ async readFileBytes(path) {
1390
+ return readFileBytes(this, path);
1391
+ }
1219
1392
  /** Delete a file from the sandbox. */
1220
1393
  async deleteFile(path) {
1221
1394
  return deleteFile(this, path);
@@ -1547,4 +1720,4 @@ function composeHooks(hooks, opts = {}) {
1547
1720
  };
1548
1721
  }
1549
1722
  //#endregion
1550
- export { BashSession, CommandError, ConsoleLogger, ExecConnectionError, ExecHandle, InteractiveExecHandle, LedgerEvent, LogLevel, SandboxError, SandboxHandle, SandboxStatus, StepTimeoutError, WorkflowError, composeHooks, noopLogger, reconstructBoundCredentials, reconstructEgressRules, resolveBoundCredential, resolveExecClient };
1723
+ export { AlineoError, BashSession, CommandError, ConsoleLogger, DEFAULT_PROVIDER_ID, ExecConnectionError, ExecHandle, InteractiveExecHandle, LedgerEvent, LogLevel, SandboxError, SandboxHandle, SandboxStatus, StepTimeoutError, WorkflowError, composeHooks, errorCodeOf, isRetryable, noopLogger, reconstructBoundCredentials, reconstructEgressRules, requireCapability, resolveBoundCredential, resolveExecChannel };