@alineo-labs/core 0.1.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 ADDED
@@ -0,0 +1,1252 @@
1
+ import { ExecClient, PtyClient, SSEEventType, SandboxState, SnapshotState } from "@alineo-labs/opensandbox";
2
+ //#region src/ledger.ts
3
+ /** Status of a sandbox session derived from its ledger events. */
4
+ let SandboxStatus = /* @__PURE__ */ function(SandboxStatus) {
5
+ SandboxStatus["Running"] = "running";
6
+ SandboxStatus["Completed"] = "completed";
7
+ return SandboxStatus;
8
+ }({});
9
+ /** Events emitted during execution and stored in the ledger. */
10
+ let LedgerEvent = /* @__PURE__ */ function(LedgerEvent) {
11
+ /** Emitted when a sandbox is created and reaches Running state. */
12
+ LedgerEvent["SandboxCreated"] = "sandbox_created";
13
+ /** Emitted at the start of each exec() or execCode() call. */
14
+ LedgerEvent["ExecStart"] = "exec_start";
15
+ /** Streaming output chunk from exec() or execCode(). */
16
+ LedgerEvent["ExecEvent"] = "exec_event";
17
+ /** Emitted when an exec() or execCode() call completes. */
18
+ LedgerEvent["ExecComplete"] = "exec_complete";
19
+ /** Emitted when checkpoint() captures a snapshot. */
20
+ LedgerEvent["CheckpointCreated"] = "checkpoint_created";
21
+ /** Emitted when a sandbox is closed. */
22
+ LedgerEvent["SandboxClosed"] = "sandbox_closed";
23
+ /** Emitted when pause() freezes the container. */
24
+ LedgerEvent["SandboxPaused"] = "sandbox_paused";
25
+ /** Emitted when resume() restores the container to Running. */
26
+ LedgerEvent["SandboxResumed"] = "sandbox_resumed";
27
+ /** Emitted once when a workflow run starts, before any steps execute. */
28
+ LedgerEvent["RunStarted"] = "run_started";
29
+ /** Emitted at the beginning of each step. */
30
+ LedgerEvent["StepStart"] = "step_start";
31
+ /** Emitted when a step finishes successfully. */
32
+ LedgerEvent["StepComplete"] = "step_complete";
33
+ /** Emitted when a step throws an unrecoverable error. */
34
+ LedgerEvent["StepFailed"] = "step_failed";
35
+ /** Emitted when a step's rollback handler completes during saga compensation. */
36
+ LedgerEvent["StepRolledBack"] = "step_rolled_back";
37
+ /** Emitted after all steps finish without error. */
38
+ LedgerEvent["WorkflowComplete"] = "workflow_complete";
39
+ /** Emitted after rollback completes following a step failure. */
40
+ LedgerEvent["WorkflowFailed"] = "workflow_failed";
41
+ /** Durable resumption point written after each successful step. */
42
+ LedgerEvent["Checkpoint"] = "checkpoint";
43
+ /** Emitted when a sandbox snapshot is captured mid-run. */
44
+ LedgerEvent["Snapshot"] = "snapshot";
45
+ return LedgerEvent;
46
+ }({});
47
+ //#endregion
48
+ //#region src/logger.ts
49
+ let LogLevel = /* @__PURE__ */ function(LogLevel) {
50
+ LogLevel[LogLevel["Debug"] = 0] = "Debug";
51
+ LogLevel[LogLevel["Info"] = 1] = "Info";
52
+ LogLevel[LogLevel["Warn"] = 2] = "Warn";
53
+ LogLevel[LogLevel["Error"] = 3] = "Error";
54
+ LogLevel[LogLevel["Silent"] = 4] = "Silent";
55
+ return LogLevel;
56
+ }({});
57
+ var ConsoleLogger = class {
58
+ minLevel;
59
+ constructor(minLevel = 1) {
60
+ this.minLevel = minLevel;
61
+ }
62
+ log(level, prefix, msg, meta) {
63
+ if (level < this.minLevel) return;
64
+ const out = meta ? `${prefix} ${msg} ${JSON.stringify(meta)}` : `${prefix} ${msg}`;
65
+ if (level >= 3) console.error(out);
66
+ else console.log(out);
67
+ }
68
+ debug(msg, meta) {
69
+ this.log(0, "[DEBUG]", msg, meta);
70
+ }
71
+ info(msg, meta) {
72
+ this.log(1, "[INFO]", msg, meta);
73
+ }
74
+ warn(msg, meta) {
75
+ this.log(2, "[WARN]", msg, meta);
76
+ }
77
+ error(msg, meta) {
78
+ this.log(3, "[ERROR]", msg, meta);
79
+ }
80
+ };
81
+ const noopLogger = {
82
+ debug: () => {},
83
+ info: () => {},
84
+ warn: () => {},
85
+ error: () => {}
86
+ };
87
+ //#endregion
88
+ //#region src/errors.ts
89
+ /** Base class for all alineo workflow runtime errors. */
90
+ var WorkflowError = class extends Error {
91
+ constructor(message) {
92
+ super(message);
93
+ this.name = "WorkflowError";
94
+ }
95
+ };
96
+ /**
97
+ * Thrown for sandbox lifecycle failures — failing to create, boot, or reach
98
+ * `Running` state; being paused when an operation requires a live sandbox;
99
+ * `fork()` being unsupported on this sandbox; or a snapshot operation failing.
100
+ */
101
+ var SandboxError = class extends WorkflowError {
102
+ sandboxId;
103
+ constructor(message, sandboxId) {
104
+ super(message);
105
+ this.sandboxId = sandboxId;
106
+ this.name = "SandboxError";
107
+ }
108
+ };
109
+ /**
110
+ * Thrown when execd inside a sandbox never becomes ready within the retry window.
111
+ * The sandbox is `Running` from the control plane's perspective, but the exec
112
+ * daemon is not accepting connections.
113
+ */
114
+ var ExecConnectionError = class extends WorkflowError {
115
+ sandboxId;
116
+ constructor(sandboxId) {
117
+ super(`execd not ready for sandbox ${sandboxId}`);
118
+ this.sandboxId = sandboxId;
119
+ this.name = "ExecConnectionError";
120
+ }
121
+ };
122
+ /**
123
+ * Thrown when a command exits with a non-zero exit code. Carries the exit
124
+ * code and original command. For `Sandbox.exec()`, only thrown when `strict`
125
+ * is enabled (the default — pass `{ strict: false }` to opt out). For
126
+ * `BashSession.exec()` (a persistent session from `createSession()`), always
127
+ * thrown on non-zero exit; there is no `strict` option for session execs.
128
+ */
129
+ var CommandError = class extends WorkflowError {
130
+ exitCode;
131
+ command;
132
+ sandboxId;
133
+ constructor(exitCode, command, sandboxId) {
134
+ super(`Command exited with code ${exitCode}: ${command}`);
135
+ this.exitCode = exitCode;
136
+ this.command = command;
137
+ this.sandboxId = sandboxId;
138
+ this.name = "CommandError";
139
+ }
140
+ };
141
+ /**
142
+ * Reserved for a per-step timeout mechanism — not currently thrown anywhere
143
+ * in this codebase. `SandboxOptions.timeout`/`step.timeout` in `@alineo-labs/workflow`
144
+ * bound sandbox container lifetime, which is a related but distinct concept.
145
+ */
146
+ var StepTimeoutError = class extends WorkflowError {
147
+ stepId;
148
+ timeoutMs;
149
+ constructor(stepId, timeoutMs) {
150
+ super(`Step "${stepId}" timed out after ${timeoutMs}ms`);
151
+ this.stepId = stepId;
152
+ this.timeoutMs = timeoutMs;
153
+ this.name = "StepTimeoutError";
154
+ }
155
+ };
156
+ //#endregion
157
+ //#region src/exec-handle.ts
158
+ /**
159
+ * Returned by `Sandbox.exec()` and `Sandbox.execCode()`.
160
+ *
161
+ * Implements `PromiseLike<ExecResult>` so `await sb.exec(...)` works naturally.
162
+ * Also exposes `pipe()`, `stdout()`, and `result()` for streaming output.
163
+ *
164
+ * @example
165
+ * ```ts
166
+ * // simple await
167
+ * const { exitCode } = await sb.exec("npm test");
168
+ *
169
+ * // stream to stdout
170
+ * await sb.exec("npm run build").pipe(process.stdout);
171
+ *
172
+ * // async generator
173
+ * for await (const chunk of sb.exec("npm test").stdout()) process.stdout.write(chunk);
174
+ * ```
175
+ */
176
+ var ExecHandle = class {
177
+ _promise;
178
+ _chunks = [];
179
+ _wakeup = null;
180
+ _done = false;
181
+ _err;
182
+ _hasErr = false;
183
+ constructor(driver) {
184
+ if (driver.type === "replay") {
185
+ if (driver.result.stdout) this._chunks.push(driver.result.stdout);
186
+ this._done = true;
187
+ this._promise = Promise.resolve(driver.result);
188
+ } else if (driver.type === "pty") {
189
+ this._promise = this._drainPty(driver);
190
+ this._promise.catch(() => {});
191
+ } else {
192
+ this._promise = this._drain(driver.gen, driver.onDone);
193
+ this._promise.catch(() => {});
194
+ }
195
+ }
196
+ _drainPty(driver) {
197
+ if (driver.seedStdout) this._chunks.push(driver.seedStdout);
198
+ return new Promise((resolve, reject) => {
199
+ driver.attach((chunk) => {
200
+ this._chunks.push(chunk);
201
+ this._notify();
202
+ }, (exitCode) => {
203
+ this._done = true;
204
+ const result = {
205
+ stdout: this._chunks.join(""),
206
+ stderr: "",
207
+ exitCode
208
+ };
209
+ this._notify();
210
+ driver.onDone(result).then(() => resolve(result), (err) => {
211
+ this._err = err;
212
+ this._hasErr = true;
213
+ reject(err);
214
+ });
215
+ }, (err) => {
216
+ this._done = true;
217
+ this._err = err;
218
+ this._hasErr = true;
219
+ this._notify();
220
+ reject(err);
221
+ });
222
+ });
223
+ }
224
+ async _drain(gen, onDone) {
225
+ const stderr = [];
226
+ let exitCode = 0;
227
+ try {
228
+ for await (const ev of gen) {
229
+ if (ev.type === SSEEventType.Stdout && ev.text) {
230
+ this._chunks.push(ev.text);
231
+ this._notify();
232
+ }
233
+ if (ev.type === SSEEventType.Stderr && ev.text) stderr.push(ev.text);
234
+ if (ev.type === SSEEventType.Error && ev.error?.evalue !== void 0) {
235
+ const code = Number(ev.error.evalue);
236
+ if (!isNaN(code)) exitCode = code;
237
+ }
238
+ }
239
+ } catch (err) {
240
+ this._err = err;
241
+ this._hasErr = true;
242
+ throw err;
243
+ } finally {
244
+ this._done = true;
245
+ this._notify();
246
+ }
247
+ const result = {
248
+ stdout: this._chunks.join(""),
249
+ stderr: stderr.join(""),
250
+ exitCode
251
+ };
252
+ await onDone(result);
253
+ return result;
254
+ }
255
+ _notify() {
256
+ const fn = this._wakeup;
257
+ this._wakeup = null;
258
+ fn?.();
259
+ }
260
+ then(onfulfilled, onrejected) {
261
+ return this._promise.then(onfulfilled, onrejected);
262
+ }
263
+ /** Resolve the full result: `{ stdout, stderr, exitCode }`. */
264
+ result() {
265
+ return this._promise;
266
+ }
267
+ /** Async generator yielding stdout chunks as they arrive. */
268
+ async *stdout() {
269
+ let pos = 0;
270
+ while (true) {
271
+ while (pos < this._chunks.length) yield this._chunks[pos++];
272
+ if (this._done) break;
273
+ await new Promise((r) => {
274
+ this._wakeup = r;
275
+ });
276
+ }
277
+ while (pos < this._chunks.length) yield this._chunks[pos++];
278
+ if (this._hasErr) throw this._err;
279
+ }
280
+ /** Pipe stdout to any writable with a `write(chunk: string)` method. */
281
+ async pipe(writable) {
282
+ for await (const chunk of this.stdout()) writable.write(chunk);
283
+ }
284
+ };
285
+ /**
286
+ * Returned by `Sandbox.exec(cmd, { interactive: true })`.
287
+ *
288
+ * Extends `ExecHandle` with the input/control side of a live PTY session:
289
+ * `write()` sends input, `resize()`/`signal()` control the terminal, `close()`
290
+ * ends the session, and `attach()` pumps a real readable/writable pair (e.g.
291
+ * `process.stdin`/`process.stdout`) for full human passthrough.
292
+ *
293
+ * `stdout()`/`pipe()`/`result()`/`await` are inherited unchanged from `ExecHandle`.
294
+ * For a session that had already finished before a checkpoint (replayed, not
295
+ * live), `write()`/`resize()`/`signal()`/`close()` are no-ops — there is
296
+ * nothing left to attach to.
297
+ *
298
+ * @example
299
+ * ```ts
300
+ * const shell = sb.exec("bash", { interactive: true });
301
+ * shell.pipe(process.stdout);
302
+ * shell.write("whoami\n");
303
+ * await shell.close();
304
+ *
305
+ * // or full human passthrough:
306
+ * await sb.exec("bash", { interactive: true }).attach(process.stdin, process.stdout);
307
+ * ```
308
+ */
309
+ var InteractiveExecHandle = class extends ExecHandle {
310
+ _controls;
311
+ constructor(driver, controls) {
312
+ super(driver);
313
+ this._controls = controls;
314
+ }
315
+ /** Send input to the running process. No-op if the session already ended. */
316
+ write(data) {
317
+ this._controls?.write(typeof data === "string" ? data : new TextDecoder().decode(data));
318
+ }
319
+ /** Resize the PTY. No-op if the session already ended. */
320
+ resize(cols, rows) {
321
+ this._controls?.resize(cols, rows);
322
+ }
323
+ /** Send a signal (e.g. `"SIGINT"`) to the running process. No-op if the session already ended. */
324
+ signal(name) {
325
+ this._controls?.signal(name);
326
+ }
327
+ /** Force-end the session. No-op if it already ended on its own. */
328
+ async close() {
329
+ this._controls?.close();
330
+ }
331
+ /**
332
+ * Pump a real readable/writable pair for full terminal passthrough — e.g.
333
+ * `shell.attach(process.stdin, process.stdout)` drops a human straight into
334
+ * the live remote shell. Resolves when the session ends.
335
+ */
336
+ async attach(readable, writable) {
337
+ const onData = (chunk) => this.write(chunk.toString());
338
+ readable.on("data", onData);
339
+ try {
340
+ await this.pipe(writable);
341
+ } finally {
342
+ readable.off("data", onData);
343
+ }
344
+ }
345
+ };
346
+ //#endregion
347
+ //#region src/sandbox/resolve.ts
348
+ /**
349
+ * Resolve an ExecClient for a sandbox. Calls getEndpoint once (each call
350
+ * returns a different ephemeral proxy port) then polls listContexts until
351
+ * execd is ready to accept connections.
352
+ *
353
+ * Defaults give ~80s of total patience (retries=45, capped at 2s/attempt), not the ~11s this
354
+ * had before (retries=15, capped at 1s/attempt). Bumped after a live `alineo fork` failure
355
+ * (issue #32): a child forked while its parent sandbox was busy running a real Chrome session
356
+ * took ~35s just to reach `Running`, then immediately exhausted the old ~11s execd-readiness
357
+ * budget before the exec daemon inside it had actually started accepting connections. An
358
+ * isolated repro of the identical fork (same snapshot, but from an idle parent with no
359
+ * concurrent browser load) reached execd-ready in under 400ms -- the parent's own host-resource
360
+ * contention at fork time, not snapshot size, is what actually eats the budget. This can't be
361
+ * fixed by scheduling around it from here, so it's addressed by simply affording much more
362
+ * patience before giving up.
363
+ */
364
+ async function resolveExecClient(control, sandboxId, useServerProxy, retries = 45, delayMs = 2e3) {
365
+ const ep = await control.getEndpoint(sandboxId, 44772, useServerProxy);
366
+ const client = new ExecClient({
367
+ baseUrl: ep.endpoint.startsWith("http") ? ep.endpoint : `http://${ep.endpoint}`,
368
+ accessToken: ep.headers?.["X-EXECD-ACCESS-TOKEN"] ?? ""
369
+ });
370
+ let delay = Math.min(100, delayMs);
371
+ for (let attempt = 0; attempt <= retries; attempt++) try {
372
+ await client.listContexts();
373
+ return client;
374
+ } catch {
375
+ if (attempt === retries) throw new ExecConnectionError(sandboxId);
376
+ await new Promise((r) => setTimeout(r, delay));
377
+ delay = Math.min(delay * 1.5, delayMs);
378
+ }
379
+ throw new Error("unreachable");
380
+ }
381
+ //#endregion
382
+ //#region src/sandbox/bash-session.ts
383
+ /**
384
+ * A persistent bash session inside a sandbox. CWD and env vars are preserved
385
+ * across `exec()` calls, unlike the stateless `sandbox.exec()`.
386
+ *
387
+ * Create with `sandbox.createSession()`. Always call `close()` when done.
388
+ */
389
+ var BashSession = class {
390
+ /** execd session ID. */
391
+ sessionId;
392
+ _execFn;
393
+ _closeFn;
394
+ _closed = false;
395
+ constructor(sessionId, execFn, closeFn) {
396
+ this.sessionId = sessionId;
397
+ this._execFn = execFn;
398
+ this._closeFn = closeFn;
399
+ }
400
+ /**
401
+ * Run a command in this session. Shell state (CWD, exported env vars) persists
402
+ * between calls.
403
+ *
404
+ * @example
405
+ * ```ts
406
+ * await session.exec("cd /app && export NODE_ENV=test");
407
+ * const { stdout } = await session.exec("node -e 'console.log(process.env.NODE_ENV)'");
408
+ * // stdout === "test\n"
409
+ * ```
410
+ */
411
+ exec(command, opts) {
412
+ return this._execFn(command, opts);
413
+ }
414
+ /** Terminate the shell process and release resources. */
415
+ async close() {
416
+ if (this._closed) return;
417
+ this._closed = true;
418
+ await this._closeFn();
419
+ }
420
+ };
421
+ //#endregion
422
+ //#region src/sandbox/core.ts
423
+ /**
424
+ * Owns all private sandbox state (exec sequencing, ledger queue, pause/close
425
+ * flags) plus the exec-stream methods that are most tightly coupled to it.
426
+ * `Sandbox` (in `sandbox.ts`) extends this and adds the file/lifecycle/
427
+ * observability methods as thin delegators to sibling modules.
428
+ */
429
+ var SandboxCore = class {
430
+ sandboxId;
431
+ name;
432
+ deps;
433
+ /** Cached exec results for replay mode (populated by `Alineo.resume()`). */
434
+ replayCache;
435
+ /** Interactive sessions still open at the last checkpoint (populated by `Alineo.resume()`). */
436
+ pendingInteractive;
437
+ openSessionClosers = /* @__PURE__ */ new Set();
438
+ _execClient = null;
439
+ _seq = 0;
440
+ _closed = false;
441
+ _paused = false;
442
+ /**
443
+ * Serializes every `emit()` call for this sandbox so ledger writes complete in the
444
+ * order they were called, regardless of adapter latency. Needed because several call
445
+ * sites (PTY output chunks, `write()`) fire `emit()` without awaiting it — on a
446
+ * network-bound adapter (e.g. Postgres) two such appends can otherwise land out of
447
+ * order even though they were invoked in the right order.
448
+ */
449
+ _ledgerQueue = Promise.resolve();
450
+ constructor(sandboxId, name, deps, replayCache = /* @__PURE__ */ new Map(), pendingInteractive = /* @__PURE__ */ new Map()) {
451
+ this.sandboxId = sandboxId;
452
+ this.name = name;
453
+ this.deps = deps;
454
+ this.replayCache = replayCache;
455
+ this.pendingInteractive = pendingInteractive;
456
+ }
457
+ isPaused() {
458
+ return this._paused;
459
+ }
460
+ setPaused(paused) {
461
+ this._paused = paused;
462
+ }
463
+ isClosed() {
464
+ return this._closed;
465
+ }
466
+ setClosed(closed) {
467
+ this._closed = closed;
468
+ }
469
+ clearExecClient() {
470
+ this._execClient = null;
471
+ }
472
+ /**
473
+ * Force-cancel any exec streams left dangling by `parseSSE`'s early-return
474
+ * optimization (see `ExecClient.disposeConnections()`). No-op if no exec client
475
+ * was ever resolved — deliberately doesn't call `getExecClient()`, which would
476
+ * lazily resolve a brand-new one against a sandbox that's about to be deleted.
477
+ */
478
+ disposeExecClient() {
479
+ this._execClient?.disposeConnections();
480
+ }
481
+ nextSeq() {
482
+ return ++this._seq;
483
+ }
484
+ async getExecClient() {
485
+ if (this._paused) throw new SandboxError("sandbox is paused — call resume() first", this.sandboxId);
486
+ if (!this._execClient) this._execClient = await resolveExecClient(this.deps.control, this.sandboxId, this.deps.useServerProxy);
487
+ return this._execClient;
488
+ }
489
+ /** Resolve a fresh `PtyClient` for a new interactive session. Reuses `getExecClient()`'s readiness wait. */
490
+ async resolvePtyClient() {
491
+ if (this._paused) throw new SandboxError("sandbox is paused — call resume() first", this.sandboxId);
492
+ await this.getExecClient();
493
+ const ep = await this.deps.control.getEndpoint(this.sandboxId, 44772, this.deps.useServerProxy);
494
+ return new PtyClient({
495
+ baseUrl: ep.endpoint.startsWith("http") ? ep.endpoint : `http://${ep.endpoint}`,
496
+ accessToken: ep.headers?.["X-EXECD-ACCESS-TOKEN"] ?? ""
497
+ });
498
+ }
499
+ async waitForRunning(timeoutMs = 12e4) {
500
+ const deadline = Date.now() + timeoutMs;
501
+ let delay = 100;
502
+ while (Date.now() < deadline) {
503
+ const s = await this.deps.control.getSandbox(this.sandboxId);
504
+ if (s.status.state === SandboxState.Running) return;
505
+ if (s.status.state === SandboxState.Failed || s.status.state === SandboxState.Terminated) throw new SandboxError(`Sandbox entered ${s.status.state}: ${s.status.message ?? ""}`, this.sandboxId);
506
+ await new Promise((r) => setTimeout(r, delay));
507
+ delay = Math.min(delay * 1.5, 1e3);
508
+ }
509
+ throw new SandboxError(`Sandbox did not reach Running within ${timeoutMs}ms`, this.sandboxId);
510
+ }
511
+ async waitForSnapshot(snapshotId, timeoutMs = 12e4) {
512
+ const deadline = Date.now() + timeoutMs;
513
+ let delay = 100;
514
+ while (Date.now() < deadline) {
515
+ const snap = await this.deps.control.getSnapshot(snapshotId);
516
+ if (snap.state === SnapshotState.Ready) return;
517
+ if (snap.state === SnapshotState.Failed) throw new SandboxError(`Snapshot ${snapshotId} failed`, this.sandboxId);
518
+ await new Promise((r) => setTimeout(r, delay));
519
+ delay = Math.min(delay * 1.5, 2e3);
520
+ }
521
+ throw new SandboxError(`Snapshot ${snapshotId} did not become ready within ${timeoutMs}ms`, this.sandboxId);
522
+ }
523
+ emit(event, stepIndex, payload) {
524
+ const entry = {
525
+ ts: Date.now(),
526
+ name: this.name,
527
+ sandboxId: this.sandboxId,
528
+ stepIndex,
529
+ event,
530
+ payload
531
+ };
532
+ const result = this._ledgerQueue.then(() => this.deps.adapter.append(entry));
533
+ this._ledgerQueue = result.catch(() => {});
534
+ return result;
535
+ }
536
+ exec(cmd, opts = {}) {
537
+ if (opts.interactive) return this._execInteractive(cmd, opts);
538
+ const seq = ++this._seq;
539
+ if (this.replayCache.has(seq)) return new ExecHandle({
540
+ type: "replay",
541
+ result: this.replayCache.get(seq)
542
+ });
543
+ const self = this;
544
+ async function* stream() {
545
+ const execClient = await self.getExecClient();
546
+ await self.emit("exec_start", seq, {
547
+ cmd,
548
+ seq
549
+ });
550
+ self.deps.hooks?.onExecStart?.(self.sandboxId, seq, cmd);
551
+ const sh = opts.shell ?? self.deps.shell ?? "/bin/sh";
552
+ const command = `echo ${Buffer.from(cmd).toString("base64")} | base64 -d | ${sh}`;
553
+ for await (const ev of execClient.executeCommand({
554
+ command,
555
+ cwd: opts.cwd,
556
+ envs: opts.env,
557
+ timeout: opts.timeoutMs
558
+ })) {
559
+ await self.emit("exec_event", seq, {
560
+ seq,
561
+ ...ev
562
+ });
563
+ yield ev;
564
+ }
565
+ }
566
+ return new ExecHandle({
567
+ type: "stream",
568
+ gen: stream(),
569
+ onDone: async (result) => {
570
+ await self.emit("exec_complete", seq, {
571
+ exitCode: result.exitCode,
572
+ seq
573
+ });
574
+ self.deps.hooks?.onExecComplete?.(self.sandboxId, seq, result);
575
+ if (opts.strict !== false && result.exitCode !== 0) throw new CommandError(result.exitCode, cmd, self.sandboxId);
576
+ }
577
+ });
578
+ }
579
+ /** Backs `exec(cmd, { interactive: true })` — see that method's docs. */
580
+ _execInteractive(cmd, opts) {
581
+ const seq = ++this._seq;
582
+ if (this.replayCache.has(seq)) return new InteractiveExecHandle({
583
+ type: "replay",
584
+ result: this.replayCache.get(seq)
585
+ });
586
+ const pending = this.pendingInteractive.get(seq);
587
+ const self = this;
588
+ let closer;
589
+ const execStartLogged = self.emit("exec_start", seq, {
590
+ cmd,
591
+ seq,
592
+ interactive: true,
593
+ cwd: pending?.cwd ?? opts.cwd,
594
+ env: pending?.env ?? opts.env
595
+ });
596
+ self.deps.hooks?.onExecStart?.(self.sandboxId, seq, cmd);
597
+ const ptyPromise = (async () => {
598
+ await execStartLogged;
599
+ const pty = await self.resolvePtyClient();
600
+ let onFirstOutput;
601
+ const firstOutput = new Promise((r) => {
602
+ onFirstOutput = r;
603
+ });
604
+ const sessionId = await pty.create({
605
+ cwd: pending?.cwd ?? opts.cwd,
606
+ command: cmd
607
+ });
608
+ await pty.connect(sessionId, (chunk) => {
609
+ onFirstOutput?.();
610
+ onFirstOutput = void 0;
611
+ self.emit("exec_event", seq, {
612
+ seq,
613
+ type: "stdout",
614
+ text: chunk
615
+ });
616
+ push(chunk);
617
+ }, (exitCode) => finish(exitCode));
618
+ closer = async () => {
619
+ if (closer) self.openSessionClosers.delete(closer);
620
+ pty.close();
621
+ };
622
+ self.openSessionClosers.add(closer);
623
+ await Promise.race([firstOutput, new Promise((r) => setTimeout(r, 3e3))]);
624
+ for (const line of pending?.stdin ?? []) {
625
+ pty.write(line);
626
+ await new Promise((r) => setTimeout(r, 50));
627
+ }
628
+ return pty;
629
+ })();
630
+ ptyPromise.catch(() => {});
631
+ let push = () => {};
632
+ let finish = () => {};
633
+ return new InteractiveExecHandle({
634
+ type: "pty",
635
+ seedStdout: pending?.stdout,
636
+ attach: (p, f, fail) => {
637
+ push = p;
638
+ finish = f;
639
+ ptyPromise.catch(fail);
640
+ },
641
+ onDone: async (result) => {
642
+ if (closer) self.openSessionClosers.delete(closer);
643
+ await self.emit("exec_complete", seq, {
644
+ exitCode: result.exitCode,
645
+ seq
646
+ });
647
+ self.deps.hooks?.onExecComplete?.(self.sandboxId, seq, result);
648
+ if (opts.strict !== false && result.exitCode !== 0) throw new CommandError(result.exitCode, cmd, self.sandboxId);
649
+ }
650
+ }, {
651
+ write: (data) => {
652
+ execStartLogged.then(() => self.emit("exec_event", seq, {
653
+ seq,
654
+ type: "stdin",
655
+ text: data
656
+ }));
657
+ ptyPromise.then((pty) => pty.write(data));
658
+ },
659
+ resize: (cols, rows) => {
660
+ ptyPromise.then((pty) => pty.resize(cols, rows));
661
+ },
662
+ signal: (name) => {
663
+ ptyPromise.then((pty) => pty.signal(name));
664
+ },
665
+ close: () => {
666
+ ptyPromise.then((pty) => pty.close());
667
+ }
668
+ });
669
+ }
670
+ /**
671
+ * Create a code execution context for use with `execCode()`.
672
+ *
673
+ * The code interpreter requires a context for every `execCode()` call. Call
674
+ * this once per session (or once per isolated scope), then pass the returned
675
+ * object as `opts.context` to `execCode()`. Variables defined in one call
676
+ * are visible to subsequent calls sharing the same context.
677
+ *
678
+ * @example
679
+ * ```ts
680
+ * const ctx = await sb.createCodeContext(CodeLanguage.Python);
681
+ * await sb.execCode('x = 42', { context: ctx });
682
+ * await sb.execCode('print(x)', { context: ctx }); // prints 42
683
+ * ```
684
+ */
685
+ async createCodeContext(language) {
686
+ return (await this.getExecClient()).createContext(language);
687
+ }
688
+ /**
689
+ * Execute code via the sandbox's code interpreter (Python, JS, etc.).
690
+ *
691
+ * Uses the execd `/code` endpoint for stateful, Jupyter-style execution.
692
+ * Contexts persist across calls — use `opts.context` to target a specific one.
693
+ * Create a context first with `sb.createCodeContext(language)`.
694
+ */
695
+ execCode(code, opts = {}) {
696
+ const seq = ++this._seq;
697
+ if (this.replayCache.has(seq)) return new ExecHandle({
698
+ type: "replay",
699
+ result: this.replayCache.get(seq)
700
+ });
701
+ const self = this;
702
+ async function* stream() {
703
+ const execClient = await self.getExecClient();
704
+ await self.emit("exec_start", seq, {
705
+ code,
706
+ seq
707
+ });
708
+ for await (const ev of execClient.executeCode({
709
+ code,
710
+ context: opts.context
711
+ })) {
712
+ await self.emit("exec_event", seq, {
713
+ seq,
714
+ ...ev
715
+ });
716
+ yield ev;
717
+ }
718
+ }
719
+ return new ExecHandle({
720
+ type: "stream",
721
+ gen: stream(),
722
+ onDone: async (result) => {
723
+ await self.emit("exec_complete", seq, {
724
+ exitCode: result.exitCode,
725
+ seq
726
+ });
727
+ }
728
+ });
729
+ }
730
+ /**
731
+ * Create a persistent bash session that preserves CWD and env vars across
732
+ * multiple `exec()` calls.
733
+ *
734
+ * Always call `session.close()` when done, or the shell process leaks inside
735
+ * the container. `sandbox.close()` also closes all open sessions automatically.
736
+ *
737
+ * @example
738
+ * ```ts
739
+ * const session = await sb.createSession({ cwd: "/app" });
740
+ * try {
741
+ * await session.exec("export DB_URL=postgres://localhost/mydb");
742
+ * await session.exec("npm run migrate").pipe(process.stdout);
743
+ * await session.exec("npm test").pipe(process.stdout);
744
+ * } finally {
745
+ * await session.close();
746
+ * }
747
+ * ```
748
+ */
749
+ async createSession(opts) {
750
+ const ec = await this.getExecClient();
751
+ const sessionId = (await ec.createSession(opts)).session_id;
752
+ const self = this;
753
+ const execInSession = (command, cmdOpts) => {
754
+ const seq = ++self._seq;
755
+ async function* stream() {
756
+ await self.emit("exec_start", seq, {
757
+ cmd: command,
758
+ seq,
759
+ sessionId
760
+ });
761
+ self.deps.hooks?.onExecStart?.(self.sandboxId, seq, command);
762
+ for await (const ev of ec.runInSession(sessionId, {
763
+ command,
764
+ cwd: cmdOpts?.cwd,
765
+ timeout: cmdOpts?.timeoutMs
766
+ })) {
767
+ await self.emit("exec_event", seq, {
768
+ seq,
769
+ ...ev
770
+ });
771
+ yield ev;
772
+ }
773
+ }
774
+ return new ExecHandle({
775
+ type: "stream",
776
+ gen: stream(),
777
+ onDone: async (result) => {
778
+ await self.emit("exec_complete", seq, {
779
+ exitCode: result.exitCode,
780
+ seq
781
+ });
782
+ self.deps.hooks?.onExecComplete?.(self.sandboxId, seq, result);
783
+ if (result.exitCode !== 0) throw new CommandError(result.exitCode, command, self.sandboxId);
784
+ }
785
+ });
786
+ };
787
+ const closeSession = async () => {
788
+ self.openSessionClosers.delete(closeSession);
789
+ await ec.deleteSession(sessionId);
790
+ };
791
+ this.openSessionClosers.add(closeSession);
792
+ return new BashSession(sessionId, execInSession, closeSession);
793
+ }
794
+ };
795
+ //#endregion
796
+ //#region src/sandbox/files.ts
797
+ /** Write a file into the sandbox. */
798
+ async function writeFile(sb, path, content) {
799
+ await (await sb.getExecClient()).uploadFile(path, content);
800
+ }
801
+ /** Read a file from the sandbox as a UTF-8 string. */
802
+ async function readFile(sb, path) {
803
+ const reader = (await (await sb.getExecClient()).downloadFile(path)).getReader();
804
+ const chunks = [];
805
+ while (true) {
806
+ const { done, value } = await reader.read();
807
+ if (done) break;
808
+ if (value) chunks.push(value);
809
+ }
810
+ const total = chunks.reduce((n, c) => n + c.length, 0);
811
+ const merged = new Uint8Array(total);
812
+ let offset = 0;
813
+ for (const chunk of chunks) {
814
+ merged.set(chunk, offset);
815
+ offset += chunk.length;
816
+ }
817
+ return new TextDecoder().decode(merged);
818
+ }
819
+ /** Delete a file from the sandbox. */
820
+ async function deleteFile(sb, path) {
821
+ await (await sb.getExecClient()).deleteFile(path);
822
+ }
823
+ /** Move or rename a file inside the sandbox. */
824
+ async function moveFile(sb, from, to) {
825
+ await (await sb.getExecClient()).moveFile(from, to);
826
+ }
827
+ /** List files in a directory inside the sandbox. */
828
+ async function listDirectory(sb, path, opts = {}) {
829
+ return (await sb.getExecClient()).listDirectory(path, opts.depth);
830
+ }
831
+ /** Search for files matching a glob pattern inside the sandbox. */
832
+ async function searchFiles(sb, pattern, path = "/") {
833
+ return (await sb.getExecClient()).searchFiles(pattern, path);
834
+ }
835
+ /** Create a directory (and parents) inside the sandbox. */
836
+ async function createDirectory(sb, path) {
837
+ await (await sb.getExecClient()).createDirectory(path);
838
+ }
839
+ /** Delete a directory inside the sandbox. */
840
+ async function deleteDirectory(sb, path) {
841
+ await (await sb.getExecClient()).deleteDirectory(path);
842
+ }
843
+ /** Return metadata for a file or directory (size, type, mode, timestamps). */
844
+ async function getFileInfo(sb, path) {
845
+ return (await sb.getExecClient()).getFileInfo(path);
846
+ }
847
+ /**
848
+ * Replace substrings in one or more files inside the sandbox.
849
+ *
850
+ * More efficient than `readFile` → string replace → `writeFile` for targeted edits.
851
+ */
852
+ async function replaceInFiles(sb, replacements) {
853
+ await (await sb.getExecClient()).replaceInFiles(replacements);
854
+ }
855
+ //#endregion
856
+ //#region src/sandbox/lifecycle.ts
857
+ /** Return all checkpoints for this sandbox in creation order. */
858
+ function listCheckpoints(sb) {
859
+ return sb.deps.adapter.listCheckpoints(sb.name, sb.sandboxId);
860
+ }
861
+ /**
862
+ * Freeze the sandbox container. Releases compute on Kubernetes; on Docker it
863
+ * is a cgroup freeze that preserves in-memory state.
864
+ *
865
+ * All pending exec calls will throw `SandboxError` until `resume()` is called.
866
+ * `close()` remains valid on a paused sandbox.
867
+ */
868
+ async function pause(sb) {
869
+ await sb.deps.control.pauseSandbox(sb.sandboxId);
870
+ sb.setPaused(true);
871
+ sb.disposeExecClient();
872
+ sb.clearExecClient();
873
+ await sb.emit("sandbox_paused", -1);
874
+ sb.deps.hooks?.onSandboxPaused?.(sb.sandboxId);
875
+ }
876
+ /**
877
+ * Restore a paused sandbox to Running state. The execd endpoint is not
878
+ * re-resolved here — `pause()` clears the cached client, so it's lazily
879
+ * re-resolved on the next call that needs it (e.g. the next `exec()`).
880
+ *
881
+ * On Docker, this unfreezes the container instantly. On Kubernetes, a new pod
882
+ * is created from the OCI snapshot — in-memory process state is not preserved.
883
+ * Polls until the sandbox reports Running before returning.
884
+ */
885
+ async function resume(sb) {
886
+ await sb.deps.control.resumeSandbox(sb.sandboxId);
887
+ sb.setPaused(false);
888
+ await sb.waitForRunning();
889
+ await sb.emit("sandbox_resumed", -1);
890
+ sb.deps.hooks?.onSandboxResumed?.(sb.sandboxId);
891
+ }
892
+ /**
893
+ * Capture a snapshot of the sandbox's current filesystem state.
894
+ *
895
+ * Writes a `checkpoint_created` event to the ledger with the snapshot ID and
896
+ * returns the snapshot ID. Use `Alineo.resume(sandboxId)` to restore from
897
+ * the latest checkpoint, or pass the returned ID to `Alineo.restoreSnapshot()`.
898
+ */
899
+ async function checkpoint(sb, name) {
900
+ const snap = await sb.deps.control.createSnapshot(sb.sandboxId);
901
+ await sb.waitForSnapshot(snap.id);
902
+ await sb.emit("checkpoint_created", -1, {
903
+ snapshotId: snap.id,
904
+ name
905
+ });
906
+ sb.deps.hooks?.onCheckpoint?.(sb.sandboxId, snap.id, name);
907
+ return snap.id;
908
+ }
909
+ /**
910
+ * Snapshot the current sandbox and return a new independent `Sandbox` from that state.
911
+ *
912
+ * The original sandbox keeps running. Both operate on separate containers restored
913
+ * from the same snapshot. Equivalent to `checkpoint()` followed by `Alineo.restoreSnapshot()`
914
+ * into a new sandbox, but without closing the original.
915
+ *
916
+ * @param runId Override the forked sandbox's run correlation ID instead of inheriting
917
+ * whatever this sandbox's own creation closed over. Needed when forking across a process
918
+ * boundary (e.g. `alineo fork`, which re-`Agent.attach()`es in a brand-new CLI process with
919
+ * no access to the original in-memory closure) — the caller reads the correct value from
920
+ * `process.env.ALINEO_RUN_ID` and passes it explicitly rather than relying on this sandbox's
921
+ * own (possibly unknown) default.
922
+ */
923
+ async function fork(sb, tag, runId) {
924
+ if (!sb.deps.fork) throw new SandboxError("fork() is not supported on this sandbox", sb.sandboxId);
925
+ const snap = await sb.deps.control.createSnapshot(sb.sandboxId);
926
+ await sb.waitForSnapshot(snap.id);
927
+ await sb.emit("checkpoint_created", -1, {
928
+ snapshotId: snap.id,
929
+ name: tag
930
+ });
931
+ sb.deps.hooks?.onCheckpoint?.(sb.sandboxId, snap.id, tag);
932
+ return sb.deps.fork(snap.id, tag, runId);
933
+ }
934
+ /**
935
+ * Delete the sandbox container and release its resources.
936
+ *
937
+ * Always call `close()` when done — even on error — to avoid leaking containers.
938
+ * Idempotent: subsequent calls are no-ops.
939
+ */
940
+ async function close(sb) {
941
+ if (sb.isClosed()) return;
942
+ sb.setClosed(true);
943
+ await Promise.allSettled([...sb.openSessionClosers].map((fn) => fn()));
944
+ sb.openSessionClosers.clear();
945
+ sb.disposeExecClient();
946
+ try {
947
+ await sb.deps.control.deleteSandbox(sb.sandboxId);
948
+ } finally {
949
+ await sb.emit("sandbox_closed", -1);
950
+ sb.deps.hooks?.onSandboxClosed?.(sb.sandboxId);
951
+ sb.deps.onClose?.();
952
+ }
953
+ }
954
+ //#endregion
955
+ //#region src/sandbox/observability.ts
956
+ /** Return current CPU and memory usage for this sandbox. */
957
+ async function metrics(sb) {
958
+ return (await sb.getExecClient()).getMetrics();
959
+ }
960
+ /**
961
+ * Stream real-time CPU and memory metrics from execd via SSE.
962
+ *
963
+ * Holds a long-lived connection — break out of the loop when done to avoid
964
+ * leaking the connection. Takes no arguments; there is no way to cancel it
965
+ * other than breaking out of the `for await` loop.
966
+ */
967
+ async function* watchMetrics(sb) {
968
+ const ec = await sb.getExecClient();
969
+ for await (const ev of ec.watchMetrics()) {
970
+ const m = ev;
971
+ if (typeof m.cpu === "number" && typeof m.memory === "number") yield m;
972
+ }
973
+ }
974
+ /** Return sandbox diagnostic logs (names, sizes, and optional inline content). */
975
+ async function diagnosticLogs(sb) {
976
+ return sb.deps.control.getDiagnosticLogs(sb.sandboxId);
977
+ }
978
+ /** Return sandbox diagnostic events (timestamps, types, and messages). */
979
+ async function diagnosticEvents(sb) {
980
+ return sb.deps.control.getDiagnosticEvents(sb.sandboxId);
981
+ }
982
+ /**
983
+ * Return a proxied URL and auth headers for a port inside the sandbox.
984
+ *
985
+ * Use this to send HTTP requests to a server running inside the sandbox.
986
+ */
987
+ async function proxy(sb, port) {
988
+ const ep = await sb.deps.control.getEndpoint(sb.sandboxId, port, sb.deps.useServerProxy);
989
+ return {
990
+ url: ep.endpoint.startsWith("http") ? ep.endpoint : `http://${ep.endpoint}`,
991
+ headers: ep.headers ?? {}
992
+ };
993
+ }
994
+ //#endregion
995
+ //#region src/sandbox/sandbox.ts
996
+ /**
997
+ * A live sandbox container. Returned by `Alineo.sandbox()` and `Alineo.resume()`.
998
+ *
999
+ * Call `exec()` to run commands, `checkpoint()` to snapshot state, and `close()`
1000
+ * when done. Multiple sandboxes can be held simultaneously — just assign to
1001
+ * different variables.
1002
+ *
1003
+ * @example
1004
+ * ```ts
1005
+ * const sb = await client.sandbox({ image: "node:22", resources: { cpu: "500m", memory: "256Mi" } });
1006
+ * await sb.exec("npm ci");
1007
+ * await sb.checkpoint();
1008
+ * await sb.exec("npm test").pipe(process.stdout);
1009
+ * await sb.close();
1010
+ * ```
1011
+ */
1012
+ var Sandbox = class extends SandboxCore {
1013
+ /** Write a file into the sandbox. */
1014
+ async writeFile(path, content) {
1015
+ return writeFile(this, path, content);
1016
+ }
1017
+ /** Read a file from the sandbox as a UTF-8 string. */
1018
+ async readFile(path) {
1019
+ return readFile(this, path);
1020
+ }
1021
+ /** Delete a file from the sandbox. */
1022
+ async deleteFile(path) {
1023
+ return deleteFile(this, path);
1024
+ }
1025
+ /** Move or rename a file inside the sandbox. */
1026
+ async moveFile(from, to) {
1027
+ return moveFile(this, from, to);
1028
+ }
1029
+ /** List files in a directory inside the sandbox. */
1030
+ async listDirectory(path, opts = {}) {
1031
+ return listDirectory(this, path, opts);
1032
+ }
1033
+ /** Search for files matching a glob pattern inside the sandbox. */
1034
+ async searchFiles(pattern, path = "/") {
1035
+ return searchFiles(this, pattern, path);
1036
+ }
1037
+ /** Create a directory (and parents) inside the sandbox. */
1038
+ async createDirectory(path) {
1039
+ return createDirectory(this, path);
1040
+ }
1041
+ /** Delete a directory inside the sandbox. */
1042
+ async deleteDirectory(path) {
1043
+ return deleteDirectory(this, path);
1044
+ }
1045
+ /** Return metadata for a file or directory (size, type, mode, timestamps). */
1046
+ async getFileInfo(path) {
1047
+ return getFileInfo(this, path);
1048
+ }
1049
+ /**
1050
+ * Replace substrings in one or more files inside the sandbox.
1051
+ *
1052
+ * More efficient than `readFile` → string replace → `writeFile` for targeted edits.
1053
+ *
1054
+ * @example
1055
+ * ```ts
1056
+ * await sb.replaceInFiles([{ path: "/app/config.json", old: "localhost", new: "0.0.0.0" }]);
1057
+ * ```
1058
+ */
1059
+ async replaceInFiles(replacements) {
1060
+ return replaceInFiles(this, replacements);
1061
+ }
1062
+ /**
1063
+ * Copy a file from this sandbox into another sandbox.
1064
+ *
1065
+ * Reads the file as a UTF-8 string and writes it to the same path on the target.
1066
+ * Use this to move results between a fork and its origin, or between parallel sandboxes.
1067
+ *
1068
+ * @example
1069
+ * ```ts
1070
+ * await sb.transfer("/app/output.json", fork);
1071
+ * ```
1072
+ */
1073
+ async transfer(path, target) {
1074
+ const content = await this.readFile(path);
1075
+ await target.writeFile(path, content);
1076
+ }
1077
+ /**
1078
+ * Return a proxied URL and auth headers for a port inside the sandbox.
1079
+ *
1080
+ * Use this to send HTTP requests to a server running inside the sandbox.
1081
+ *
1082
+ * @example
1083
+ * ```ts
1084
+ * await sb.exec("node server.js &");
1085
+ * const { url, headers } = await sb.proxy(3000);
1086
+ * const res = await fetch(`${url}/health`, { headers });
1087
+ * ```
1088
+ */
1089
+ async proxy(port) {
1090
+ return proxy(this, port);
1091
+ }
1092
+ /** Return current CPU and memory usage for this sandbox. */
1093
+ async metrics() {
1094
+ return metrics(this);
1095
+ }
1096
+ /**
1097
+ * Stream real-time CPU and memory metrics from execd via SSE.
1098
+ *
1099
+ * Holds a long-lived connection — break out of the loop when done to avoid
1100
+ * leaking the connection. Takes no arguments; there is no way to cancel it
1101
+ * other than breaking out of the `for await` loop.
1102
+ *
1103
+ * @example
1104
+ * ```ts
1105
+ * for await (const m of sb.watchMetrics()) {
1106
+ * console.log(m.cpu, m.memory);
1107
+ * if (m.cpu > 0.9) break;
1108
+ * }
1109
+ * ```
1110
+ */
1111
+ watchMetrics() {
1112
+ return watchMetrics(this);
1113
+ }
1114
+ /** Return sandbox diagnostic logs (names, sizes, and optional inline content). */
1115
+ async diagnosticLogs() {
1116
+ return diagnosticLogs(this);
1117
+ }
1118
+ /** Return sandbox diagnostic events (timestamps, types, and messages). */
1119
+ async diagnosticEvents() {
1120
+ return diagnosticEvents(this);
1121
+ }
1122
+ /**
1123
+ * Freeze the sandbox container. Releases compute on Kubernetes; on Docker it
1124
+ * is a cgroup freeze that preserves in-memory state.
1125
+ *
1126
+ * All pending exec calls will throw `SandboxError` until `resume()` is called.
1127
+ * `close()` remains valid on a paused sandbox.
1128
+ */
1129
+ async pause() {
1130
+ return pause(this);
1131
+ }
1132
+ /**
1133
+ * Restore a paused sandbox to Running state. The execd endpoint is not
1134
+ * re-resolved here — `pause()` clears the cached client, so it's lazily
1135
+ * re-resolved on the next call that needs it (e.g. the next `exec()`).
1136
+ *
1137
+ * On Docker, this unfreezes the container instantly. On Kubernetes, a new pod
1138
+ * is created from the OCI snapshot — in-memory process state is not preserved.
1139
+ * Polls until the sandbox reports Running before returning.
1140
+ */
1141
+ async resume() {
1142
+ return resume(this);
1143
+ }
1144
+ /** Return all checkpoints for this sandbox in creation order. */
1145
+ listCheckpoints() {
1146
+ return listCheckpoints(this);
1147
+ }
1148
+ /**
1149
+ * Snapshot the current sandbox and return a new independent `Sandbox` from that state.
1150
+ *
1151
+ * The original sandbox keeps running. Both operate on separate containers restored
1152
+ * from the same snapshot. Equivalent to `checkpoint()` followed by `Alineo.restoreSnapshot()`
1153
+ * into a new sandbox, but without closing the original.
1154
+ *
1155
+ * @example
1156
+ * ```ts
1157
+ * await sb.exec("npm ci");
1158
+ * const fork = await sb.fork("after-install");
1159
+ *
1160
+ * await sb.exec("npm test"); // runs on original
1161
+ * await fork.exec("npm run build"); // runs on fork
1162
+ * ```
1163
+ *
1164
+ * @param runId Override the forked sandbox's run-correlation ID (see `SandboxDetails.runId`)
1165
+ * instead of inheriting this sandbox's own default.
1166
+ */
1167
+ async fork(tag, runId) {
1168
+ return fork(this, tag, runId);
1169
+ }
1170
+ /**
1171
+ * Capture a snapshot of the sandbox's current filesystem state.
1172
+ *
1173
+ * Writes a `checkpoint_created` event to the ledger with the snapshot ID and
1174
+ * returns the snapshot ID. Use `Alineo.resume(sandboxId)` to restore from
1175
+ * the latest checkpoint, or pass the returned ID to `Alineo.restoreSnapshot()`.
1176
+ */
1177
+ async checkpoint(name) {
1178
+ return checkpoint(this, name);
1179
+ }
1180
+ /**
1181
+ * Delete the sandbox container and release its resources.
1182
+ *
1183
+ * Always call `close()` when done — even on error — to avoid leaking containers.
1184
+ * Idempotent: subsequent calls are no-ops.
1185
+ */
1186
+ async close() {
1187
+ return close(this);
1188
+ }
1189
+ };
1190
+ //#endregion
1191
+ //#region src/sandbox/hooks.ts
1192
+ /**
1193
+ * Merge multiple `SandboxHooks` into one, so more than one hooks-based adapter
1194
+ * (`otelHooks(tracer)`, a billing hook, etc.) can attach to the same sandbox without
1195
+ * hand-writing a merged object.
1196
+ *
1197
+ * Hooks fire in the order given, synchronously. Each invocation is isolated in its own
1198
+ * try/catch — a throwing hook can't prevent sibling hooks, or the real sandbox operation
1199
+ * that triggered them, from completing.
1200
+ *
1201
+ * @example
1202
+ * ```ts
1203
+ * import { composeHooks } from "@alineo-labs/core";
1204
+ * import { otelHooks } from "@alineo-labs/otel";
1205
+ *
1206
+ * const sb = await client.sandbox({
1207
+ * image: "ubuntu:22.04",
1208
+ * resources: { cpu: "500m", memory: "512Mi" },
1209
+ * hooks: composeHooks([otelHooks(tracer), billingHooks()], {
1210
+ * onHookError: (error, index, method) => console.error(`hook ${index} ${method} failed`, error),
1211
+ * }),
1212
+ * });
1213
+ * ```
1214
+ */
1215
+ function composeHooks(hooks, opts = {}) {
1216
+ const active = hooks.filter((h) => h != null);
1217
+ function call(method, index, fn) {
1218
+ try {
1219
+ fn();
1220
+ } catch (error) {
1221
+ opts.onHookError?.(error, index, method);
1222
+ }
1223
+ }
1224
+ return {
1225
+ onSandboxCreated(sandboxId, name) {
1226
+ active.forEach((h, i) => h.onSandboxCreated && call("onSandboxCreated", i, () => h.onSandboxCreated(sandboxId, name)));
1227
+ },
1228
+ onExecStart(sandboxId, seq, cmd) {
1229
+ active.forEach((h, i) => h.onExecStart && call("onExecStart", i, () => h.onExecStart(sandboxId, seq, cmd)));
1230
+ },
1231
+ onExecComplete(sandboxId, seq, result) {
1232
+ active.forEach((h, i) => h.onExecComplete && call("onExecComplete", i, () => h.onExecComplete(sandboxId, seq, result)));
1233
+ },
1234
+ onCheckpoint(sandboxId, snapshotId, name) {
1235
+ active.forEach((h, i) => h.onCheckpoint && call("onCheckpoint", i, () => h.onCheckpoint(sandboxId, snapshotId, name)));
1236
+ },
1237
+ onSandboxClosed(sandboxId) {
1238
+ active.forEach((h, i) => h.onSandboxClosed && call("onSandboxClosed", i, () => h.onSandboxClosed(sandboxId)));
1239
+ },
1240
+ onSandboxFailed(sandboxId, error) {
1241
+ active.forEach((h, i) => h.onSandboxFailed && call("onSandboxFailed", i, () => h.onSandboxFailed(sandboxId, error)));
1242
+ },
1243
+ onSandboxPaused(sandboxId) {
1244
+ active.forEach((h, i) => h.onSandboxPaused && call("onSandboxPaused", i, () => h.onSandboxPaused(sandboxId)));
1245
+ },
1246
+ onSandboxResumed(sandboxId) {
1247
+ active.forEach((h, i) => h.onSandboxResumed && call("onSandboxResumed", i, () => h.onSandboxResumed(sandboxId)));
1248
+ }
1249
+ };
1250
+ }
1251
+ //#endregion
1252
+ export { BashSession, CommandError, ConsoleLogger, ExecConnectionError, ExecHandle, InteractiveExecHandle, LedgerEvent, LogLevel, Sandbox, SandboxError, SandboxStatus, StepTimeoutError, WorkflowError, composeHooks, noopLogger, resolveExecClient };