@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.
@@ -0,0 +1,834 @@
1
+ import { ControlClient, DiagnosticEvent, DiagnosticEvent as DiagnosticEvent$1, DiagnosticLog, DiagnosticLog as DiagnosticLog$1, ExecClient, FileInfo, FileInfo as FileInfo$1, Metrics, Metrics as Metrics$1, PtyClient, SSEEvent } from "@alineo-labs/opensandbox";
2
+
3
+ //#region src/ledger.d.ts
4
+ /** Status of a sandbox session derived from its ledger events. */
5
+ declare enum SandboxStatus {
6
+ Running = "running",
7
+ Completed = "completed"
8
+ }
9
+ /** Derived metadata for a sandbox session, computed from its ledger events. */
10
+ interface SandboxDetails {
11
+ /** User-provided name (or auto-generated). */
12
+ name: string;
13
+ sandboxId: string;
14
+ status: SandboxStatus;
15
+ /** Unix timestamp (ms) of the `sandbox_created` event. */
16
+ startedAt: number;
17
+ /** Unix timestamp (ms) of the `sandbox_closed` event, if the session has ended. */
18
+ completedAt?: number;
19
+ /** Number of exec() calls that completed. */
20
+ execCount: number;
21
+ /**
22
+ * Identifies the logical run this sandbox belongs to. Always present — a fresh
23
+ * `crypto.randomUUID()` if the caller didn't supply one via `SandboxOptions.runId`.
24
+ * A resumed, forked, or restored-from-snapshot sandbox always inherits its origin's
25
+ * `runId` rather than getting a new one, so every sandbox descended from the same
26
+ * root call (directly or via `sb.fork()`/`Agent.spawn()`/`alineo fork`) shares it —
27
+ * the mechanism `client.sandboxes.list({ runId })` correlates on.
28
+ */
29
+ runId: string;
30
+ }
31
+ /** Options for filtering session listings. */
32
+ interface ListSandboxOptions {
33
+ status?: SandboxStatus;
34
+ /** Max number of results to return. */
35
+ limit?: number;
36
+ /** Return only sessions that started before this Unix timestamp (ms). */
37
+ before?: number;
38
+ /** Return only sessions belonging to this run — see `SandboxDetails.runId`. */
39
+ runId?: string;
40
+ }
41
+ /** Events emitted during execution and stored in the ledger. */
42
+ declare enum LedgerEvent {
43
+ /** Emitted when a sandbox is created and reaches Running state. */
44
+ SandboxCreated = "sandbox_created",
45
+ /** Emitted at the start of each exec() or execCode() call. */
46
+ ExecStart = "exec_start",
47
+ /** Streaming output chunk from exec() or execCode(). */
48
+ ExecEvent = "exec_event",
49
+ /** Emitted when an exec() or execCode() call completes. */
50
+ ExecComplete = "exec_complete",
51
+ /** Emitted when checkpoint() captures a snapshot. */
52
+ CheckpointCreated = "checkpoint_created",
53
+ /** Emitted when a sandbox is closed. */
54
+ SandboxClosed = "sandbox_closed",
55
+ /** Emitted when pause() freezes the container. */
56
+ SandboxPaused = "sandbox_paused",
57
+ /** Emitted when resume() restores the container to Running. */
58
+ SandboxResumed = "sandbox_resumed",
59
+ /** Emitted once when a workflow run starts, before any steps execute. */
60
+ RunStarted = "run_started",
61
+ /** Emitted at the beginning of each step. */
62
+ StepStart = "step_start",
63
+ /** Emitted when a step finishes successfully. */
64
+ StepComplete = "step_complete",
65
+ /** Emitted when a step throws an unrecoverable error. */
66
+ StepFailed = "step_failed",
67
+ /** Emitted when a step's rollback handler completes during saga compensation. */
68
+ StepRolledBack = "step_rolled_back",
69
+ /** Emitted after all steps finish without error. */
70
+ WorkflowComplete = "workflow_complete",
71
+ /** Emitted after rollback completes following a step failure. */
72
+ WorkflowFailed = "workflow_failed",
73
+ /** Durable resumption point written after each successful step. */
74
+ Checkpoint = "checkpoint",
75
+ /** Emitted when a sandbox snapshot is captured mid-run. */
76
+ Snapshot = "snapshot"
77
+ }
78
+ /** A single event record written to the storage adapter during a session. */
79
+ interface LedgerEntry {
80
+ /** Unix timestamp in milliseconds. */
81
+ ts: number;
82
+ /** Sandbox session name. */
83
+ name: string;
84
+ sandboxId: string;
85
+ /** Zero-based index of the step that produced this event. `-1` for session-level events. */
86
+ stepIndex: number;
87
+ /** Parallel branch index, when this step is inside a `parallel()` block. */
88
+ branch?: number;
89
+ event: LedgerEvent;
90
+ /** Event-specific data (step output, snapshot ID, exec text, etc.). */
91
+ payload?: unknown;
92
+ /** Error message when `event` is `StepFailed` or `WorkflowFailed`. */
93
+ error?: string;
94
+ }
95
+ /** A recorded checkpoint for a sandbox session. */
96
+ interface CheckpointInfo {
97
+ /** OpenSandbox snapshot ID. */
98
+ snapshotId: string;
99
+ /** User-supplied name, if provided when calling `sb.checkpoint(name)`. */
100
+ tag?: string;
101
+ /** Unix timestamp (ms) when the checkpoint was created. */
102
+ createdAt: number;
103
+ }
104
+ /**
105
+ * Persisted record for a named, reusable sandbox environment.
106
+ * Written once when the environment is first built; updated on rebuild.
107
+ */
108
+ interface EnvironmentRecord {
109
+ /** User-provided environment name. */
110
+ name: string;
111
+ /** OpenSandbox snapshot ID to restore from. */
112
+ snapshotId: string;
113
+ /** Raw image URI resolved at build time. */
114
+ image: string;
115
+ /** Unix timestamp (ms) when the environment was last built. */
116
+ builtAt: number;
117
+ }
118
+ /**
119
+ * Persistence interface for session event storage.
120
+ *
121
+ * Implement this interface to plug in any storage backend. alineo ships two
122
+ * official implementations: `@alineo-labs/sqlite` (local dev, zero infra) and
123
+ * `@alineo-labs/postgres` (production).
124
+ *
125
+ * @example
126
+ * ```ts
127
+ * import { SQLiteAdapter } from "@alineo-labs/sqlite";
128
+ * const client = new Alineo({ baseUrl, adapter: new SQLiteAdapter("./alineo.db") });
129
+ * ```
130
+ */
131
+ interface IStorageAdapter {
132
+ /** Run migrations / open connections. Must be called before first use. */
133
+ connect?(): Promise<void>;
134
+ /** Release connections and resources. Call on graceful shutdown. */
135
+ close?(): Promise<void>;
136
+ /** Persist a single ledger event. Called automatically during execution. */
137
+ append(entry: LedgerEntry): Promise<void>;
138
+ /** Return all events for a specific session, in ascending timestamp order. */
139
+ readAll(name: string, sandboxId: string): Promise<LedgerEntry[]>;
140
+ /** Return the most recent checkpoint entry for a session, or `null` if none exists. */
141
+ lastCheckpoint(name: string, sandboxId: string): Promise<LedgerEntry | null>;
142
+ /** Return details for all sessions with a given name, newest first. */
143
+ listSandboxDetails(name: string, opts?: ListSandboxOptions): Promise<SandboxDetails[]>;
144
+ /** Return details for sessions across all names, newest first. */
145
+ listAllSandboxDetails(opts?: ListSandboxOptions): Promise<SandboxDetails[]>;
146
+ /** Return details for a single session, or `null` if not found. */
147
+ getSandboxDetails(name: string, sandboxId: string): Promise<SandboxDetails | null>;
148
+ /** Delete all ledger events for a session. */
149
+ deleteSandbox(name: string, sandboxId: string): Promise<void>;
150
+ /** Return all checkpoints for a session in creation order. */
151
+ listCheckpoints(name: string, sandboxId: string): Promise<CheckpointInfo[]>;
152
+ /** Return the cached record for a named environment, or null if not built yet. */
153
+ getEnvironment(name: string): Promise<EnvironmentRecord | null>;
154
+ /** Upsert an environment record after a successful build. */
155
+ saveEnvironment(record: EnvironmentRecord): Promise<void>;
156
+ /** Remove the record for a named environment. Does not delete the server-side snapshot. */
157
+ deleteEnvironment(name: string): Promise<void>;
158
+ /** Return all environment records, newest first. */
159
+ listEnvironments(): Promise<EnvironmentRecord[]>;
160
+ }
161
+ //#endregion
162
+ //#region src/logger.d.ts
163
+ declare enum LogLevel {
164
+ Debug = 0,
165
+ Info = 1,
166
+ Warn = 2,
167
+ Error = 3,
168
+ Silent = 4
169
+ }
170
+ interface ILogger {
171
+ debug(msg: string, meta?: Record<string, unknown>): void;
172
+ info(msg: string, meta?: Record<string, unknown>): void;
173
+ warn(msg: string, meta?: Record<string, unknown>): void;
174
+ error(msg: string, meta?: Record<string, unknown>): void;
175
+ }
176
+ declare class ConsoleLogger implements ILogger {
177
+ private readonly minLevel;
178
+ constructor(minLevel?: LogLevel);
179
+ private log;
180
+ debug(msg: string, meta?: Record<string, unknown>): void;
181
+ info(msg: string, meta?: Record<string, unknown>): void;
182
+ warn(msg: string, meta?: Record<string, unknown>): void;
183
+ error(msg: string, meta?: Record<string, unknown>): void;
184
+ }
185
+ declare const noopLogger: ILogger;
186
+ //#endregion
187
+ //#region src/exec-handle.d.ts
188
+ interface ExecResult {
189
+ stdout: string;
190
+ stderr: string;
191
+ exitCode: number;
192
+ }
193
+ type ExecDriver = {
194
+ type: "stream";
195
+ gen: AsyncGenerator<SSEEvent>;
196
+ onDone: (r: ExecResult) => Promise<void>;
197
+ } | {
198
+ type: "replay";
199
+ result: ExecResult;
200
+ } | {
201
+ type: "pty"; /** Output already recorded before this handle was created (e.g. resumed from ledger) — shown as scrollback before live output resumes. */
202
+ seedStdout?: string; /** Wire up push-based output/exit/failure callbacks. Called once, synchronously. */
203
+ attach: (push: (chunk: string) => void, finish: (exitCode: number) => void, fail: (err: unknown) => void) => void;
204
+ onDone: (r: ExecResult) => Promise<void>;
205
+ };
206
+ /** Live input/control surface for an `InteractiveExecHandle`. Absent for finished/replayed sessions. */
207
+ interface PtyControls {
208
+ write(data: string): void;
209
+ resize(cols: number, rows: number): void;
210
+ signal(name: string): void;
211
+ close(): void;
212
+ }
213
+ /**
214
+ * Returned by `Sandbox.exec()` and `Sandbox.execCode()`.
215
+ *
216
+ * Implements `PromiseLike<ExecResult>` so `await sb.exec(...)` works naturally.
217
+ * Also exposes `pipe()`, `stdout()`, and `result()` for streaming output.
218
+ *
219
+ * @example
220
+ * ```ts
221
+ * // simple await
222
+ * const { exitCode } = await sb.exec("npm test");
223
+ *
224
+ * // stream to stdout
225
+ * await sb.exec("npm run build").pipe(process.stdout);
226
+ *
227
+ * // async generator
228
+ * for await (const chunk of sb.exec("npm test").stdout()) process.stdout.write(chunk);
229
+ * ```
230
+ */
231
+ declare class ExecHandle implements PromiseLike<ExecResult> {
232
+ private readonly _promise;
233
+ private readonly _chunks;
234
+ private _wakeup;
235
+ private _done;
236
+ private _err;
237
+ private _hasErr;
238
+ constructor(driver: ExecDriver);
239
+ private _drainPty;
240
+ private _drain;
241
+ private _notify;
242
+ then<T, E>(onfulfilled?: ((value: ExecResult) => T | PromiseLike<T>) | null, onrejected?: ((reason: unknown) => E | PromiseLike<E>) | null): Promise<T | E>;
243
+ /** Resolve the full result: `{ stdout, stderr, exitCode }`. */
244
+ result(): Promise<ExecResult>;
245
+ /** Async generator yielding stdout chunks as they arrive. */
246
+ stdout(): AsyncGenerator<string>;
247
+ /** Pipe stdout to any writable with a `write(chunk: string)` method. */
248
+ pipe(writable: {
249
+ write(chunk: string): unknown;
250
+ }): Promise<void>;
251
+ }
252
+ /** Minimal structural readable — matches `process.stdin` without depending on `@types/node`. */
253
+ interface AttachableSource {
254
+ on(event: "data", listener: (chunk: Buffer | string) => void): unknown;
255
+ off(event: "data", listener: (chunk: Buffer | string) => void): unknown;
256
+ }
257
+ /**
258
+ * Returned by `Sandbox.exec(cmd, { interactive: true })`.
259
+ *
260
+ * Extends `ExecHandle` with the input/control side of a live PTY session:
261
+ * `write()` sends input, `resize()`/`signal()` control the terminal, `close()`
262
+ * ends the session, and `attach()` pumps a real readable/writable pair (e.g.
263
+ * `process.stdin`/`process.stdout`) for full human passthrough.
264
+ *
265
+ * `stdout()`/`pipe()`/`result()`/`await` are inherited unchanged from `ExecHandle`.
266
+ * For a session that had already finished before a checkpoint (replayed, not
267
+ * live), `write()`/`resize()`/`signal()`/`close()` are no-ops — there is
268
+ * nothing left to attach to.
269
+ *
270
+ * @example
271
+ * ```ts
272
+ * const shell = sb.exec("bash", { interactive: true });
273
+ * shell.pipe(process.stdout);
274
+ * shell.write("whoami\n");
275
+ * await shell.close();
276
+ *
277
+ * // or full human passthrough:
278
+ * await sb.exec("bash", { interactive: true }).attach(process.stdin, process.stdout);
279
+ * ```
280
+ */
281
+ declare class InteractiveExecHandle extends ExecHandle {
282
+ private readonly _controls?;
283
+ constructor(driver: ExecDriver, controls?: PtyControls);
284
+ /** Send input to the running process. No-op if the session already ended. */
285
+ write(data: string | Uint8Array): void;
286
+ /** Resize the PTY. No-op if the session already ended. */
287
+ resize(cols: number, rows: number): void;
288
+ /** Send a signal (e.g. `"SIGINT"`) to the running process. No-op if the session already ended. */
289
+ signal(name: string): void;
290
+ /** Force-end the session. No-op if it already ended on its own. */
291
+ close(): Promise<void>;
292
+ /**
293
+ * Pump a real readable/writable pair for full terminal passthrough — e.g.
294
+ * `shell.attach(process.stdin, process.stdout)` drops a human straight into
295
+ * the live remote shell. Resolves when the session ends.
296
+ */
297
+ attach(readable: AttachableSource, writable: {
298
+ write(chunk: string): unknown;
299
+ }): Promise<void>;
300
+ }
301
+ //#endregion
302
+ //#region src/sandbox/types.d.ts
303
+ interface ExecOptions {
304
+ /** Working directory inside the sandbox. */
305
+ cwd?: string;
306
+ /** Environment variables to set for this exec. */
307
+ env?: Record<string, string>;
308
+ /** Abort the command after this many milliseconds. */
309
+ timeoutMs?: number;
310
+ /**
311
+ * Throw `CommandError` if the command exits with a non-zero code.
312
+ * Defaults to `true`.
313
+ */
314
+ strict?: boolean;
315
+ /**
316
+ * Path to the shell binary used to execute the command.
317
+ * Overrides the sandbox-level default set in `SandboxOptions.shell`.
318
+ * Defaults to `"/bin/sh"`.
319
+ */
320
+ shell?: string;
321
+ /**
322
+ * Open a live, bidirectional PTY session instead of running `cmd` as a
323
+ * one-shot buffered command. `cmd` is the program to launch (e.g. `"bash"`),
324
+ * not a script blob. Returns an `InteractiveExecHandle` with `write()`,
325
+ * `resize()`, `signal()`, `close()`, and `attach()` in addition to the
326
+ * usual `stdout()`/`pipe()`/`result()`/`await` surface.
327
+ */
328
+ interactive?: boolean;
329
+ }
330
+ /** A session still open at the last checkpoint — reconstructed on resume. See `Alineo.resume()`. */
331
+ interface PendingInteractiveExec {
332
+ cmd: string;
333
+ cwd?: string;
334
+ env?: Record<string, string>;
335
+ /** Recorded stdin, in order — replayed for real against the freshly restored filesystem. */
336
+ stdin: string[];
337
+ /** Recorded stdout — shown as scrollback before live output resumes. */
338
+ stdout: string;
339
+ }
340
+ interface ExecCodeOptions {
341
+ /** Execution context (stateful interpreter session). */
342
+ context?: {
343
+ id: string;
344
+ language: import("@alineo-labs/opensandbox").CodeLanguage;
345
+ };
346
+ }
347
+ /** Lifecycle hooks for observability. Pass via `SandboxDeps.hooks`. */
348
+ interface SandboxHooks {
349
+ onSandboxCreated?(sandboxId: string, name: string): void;
350
+ onExecStart?(sandboxId: string, seq: number, cmd: string): void;
351
+ onExecComplete?(sandboxId: string, seq: number, result: ExecResult): void;
352
+ onCheckpoint?(sandboxId: string, snapshotId: string, name?: string): void;
353
+ onSandboxClosed?(sandboxId: string): void;
354
+ onSandboxFailed?(sandboxId: string, error: Error): void;
355
+ onSandboxPaused?(sandboxId: string): void;
356
+ onSandboxResumed?(sandboxId: string): void;
357
+ }
358
+ /** Internal dependencies injected by `Alineo`. */
359
+ interface SandboxDeps {
360
+ control: ControlClient;
361
+ adapter: IStorageAdapter;
362
+ hooks?: SandboxHooks;
363
+ /** Called when `close()` completes — used by `Alineo` for concurrency accounting. */
364
+ onClose?: () => void;
365
+ /** Default shell for all `exec()` calls on this sandbox. Defaults to `"/bin/sh"`. */
366
+ shell?: string;
367
+ /**
368
+ * Called by `fork()` to create a new Sandbox from a snapshot — injected by `Alineo`.
369
+ * `runId`, if passed, overrides whatever run-correlation ID this closure would otherwise
370
+ * default to (see `fork()`'s own docs in `lifecycle.ts` for why an explicit override is
371
+ * needed across a process boundary).
372
+ */
373
+ fork?: (snapshotId: string, tag?: string, runId?: string) => Promise<Sandbox>;
374
+ /** Route execd and proxy calls through the OpenSandbox server. Required when the server runs in Docker. */
375
+ useServerProxy?: boolean;
376
+ }
377
+ //#endregion
378
+ //#region src/sandbox/internal.d.ts
379
+ /**
380
+ * Narrow surface that `files.ts`/`lifecycle.ts`/`observability.ts` need from
381
+ * `SandboxCore` — deliberately not exported from the package barrel, so it
382
+ * never becomes public API even though it's a real exported interface within
383
+ * the package. `exec()`/`execCode()`/`createSession()` stay on `SandboxCore`
384
+ * directly since they own `_seq`/`replayCache` most directly; splitting them
385
+ * out would just add indirection without reducing coupling.
386
+ */
387
+ interface SandboxInternal {
388
+ readonly sandboxId: string;
389
+ readonly name: string;
390
+ readonly deps: SandboxDeps;
391
+ readonly openSessionClosers: Set<() => Promise<void>>;
392
+ getExecClient(): Promise<ExecClient>;
393
+ emit(event: LedgerEvent, stepIndex: number, payload?: unknown): Promise<void>;
394
+ waitForRunning(timeoutMs?: number): Promise<void>;
395
+ waitForSnapshot(snapshotId: string, timeoutMs?: number): Promise<void>;
396
+ isPaused(): boolean;
397
+ setPaused(paused: boolean): void;
398
+ isClosed(): boolean;
399
+ setClosed(closed: boolean): void;
400
+ clearExecClient(): void;
401
+ disposeExecClient(): void;
402
+ }
403
+ //#endregion
404
+ //#region src/sandbox/bash-session.d.ts
405
+ /**
406
+ * A persistent bash session inside a sandbox. CWD and env vars are preserved
407
+ * across `exec()` calls, unlike the stateless `sandbox.exec()`.
408
+ *
409
+ * Create with `sandbox.createSession()`. Always call `close()` when done.
410
+ */
411
+ declare class BashSession {
412
+ /** execd session ID. */
413
+ readonly sessionId: string;
414
+ private readonly _execFn;
415
+ private readonly _closeFn;
416
+ private _closed;
417
+ constructor(sessionId: string, execFn: (command: string, opts?: {
418
+ cwd?: string;
419
+ timeoutMs?: number;
420
+ }) => ExecHandle, closeFn: () => Promise<void>);
421
+ /**
422
+ * Run a command in this session. Shell state (CWD, exported env vars) persists
423
+ * between calls.
424
+ *
425
+ * @example
426
+ * ```ts
427
+ * await session.exec("cd /app && export NODE_ENV=test");
428
+ * const { stdout } = await session.exec("node -e 'console.log(process.env.NODE_ENV)'");
429
+ * // stdout === "test\n"
430
+ * ```
431
+ */
432
+ exec(command: string, opts?: {
433
+ cwd?: string;
434
+ timeoutMs?: number;
435
+ }): ExecHandle;
436
+ /** Terminate the shell process and release resources. */
437
+ close(): Promise<void>;
438
+ }
439
+ //#endregion
440
+ //#region src/sandbox/core.d.ts
441
+ /**
442
+ * Owns all private sandbox state (exec sequencing, ledger queue, pause/close
443
+ * flags) plus the exec-stream methods that are most tightly coupled to it.
444
+ * `Sandbox` (in `sandbox.ts`) extends this and adds the file/lifecycle/
445
+ * observability methods as thin delegators to sibling modules.
446
+ */
447
+ declare class SandboxCore implements SandboxInternal {
448
+ readonly sandboxId: string;
449
+ readonly name: string;
450
+ readonly deps: SandboxDeps;
451
+ /** Cached exec results for replay mode (populated by `Alineo.resume()`). */
452
+ readonly replayCache: Map<number, ExecResult>;
453
+ /** Interactive sessions still open at the last checkpoint (populated by `Alineo.resume()`). */
454
+ readonly pendingInteractive: Map<number, PendingInteractiveExec>;
455
+ readonly openSessionClosers: Set<() => Promise<void>>;
456
+ private _execClient;
457
+ private _seq;
458
+ private _closed;
459
+ private _paused;
460
+ /**
461
+ * Serializes every `emit()` call for this sandbox so ledger writes complete in the
462
+ * order they were called, regardless of adapter latency. Needed because several call
463
+ * sites (PTY output chunks, `write()`) fire `emit()` without awaiting it — on a
464
+ * network-bound adapter (e.g. Postgres) two such appends can otherwise land out of
465
+ * order even though they were invoked in the right order.
466
+ */
467
+ private _ledgerQueue;
468
+ constructor(sandboxId: string, name: string, deps: SandboxDeps, replayCache?: Map<number, ExecResult>, pendingInteractive?: Map<number, PendingInteractiveExec>);
469
+ isPaused(): boolean;
470
+ setPaused(paused: boolean): void;
471
+ isClosed(): boolean;
472
+ setClosed(closed: boolean): void;
473
+ clearExecClient(): void;
474
+ /**
475
+ * Force-cancel any exec streams left dangling by `parseSSE`'s early-return
476
+ * optimization (see `ExecClient.disposeConnections()`). No-op if no exec client
477
+ * was ever resolved — deliberately doesn't call `getExecClient()`, which would
478
+ * lazily resolve a brand-new one against a sandbox that's about to be deleted.
479
+ */
480
+ disposeExecClient(): void;
481
+ nextSeq(): number;
482
+ getExecClient(): Promise<ExecClient>;
483
+ /** Resolve a fresh `PtyClient` for a new interactive session. Reuses `getExecClient()`'s readiness wait. */
484
+ resolvePtyClient(): Promise<PtyClient>;
485
+ waitForRunning(timeoutMs?: number): Promise<void>;
486
+ waitForSnapshot(snapshotId: string, timeoutMs?: number): Promise<void>;
487
+ emit(event: LedgerEvent, stepIndex: number, payload?: unknown): Promise<void>;
488
+ /**
489
+ * Execute a shell command inside the sandbox.
490
+ *
491
+ * Returns an `ExecHandle` — await it for the result, call `.pipe()` to stream
492
+ * stdout, or use `.stdout()` as an async generator. Live execs are logged to
493
+ * the ledger; replayed execs in a resumed sandbox return cached output
494
+ * instantly without re-running and without emitting new ledger events.
495
+ *
496
+ * Pass `{ interactive: true }` to open a live, bidirectional PTY session
497
+ * instead — `cmd` is the program to launch (e.g. `"bash"`), and the returned
498
+ * `InteractiveExecHandle` adds `write()`/`resize()`/`signal()`/`close()`/`attach()`.
499
+ * If the session was still open at the last checkpoint, resuming replays
500
+ * its recorded stdin for real against the freshly restored filesystem
501
+ * before handing control back live.
502
+ *
503
+ * @example
504
+ * ```ts
505
+ * const { exitCode } = await sb.exec("npm test");
506
+ * await sb.exec("npm run build").pipe(process.stdout);
507
+ *
508
+ * const shell = sb.exec("bash", { interactive: true });
509
+ * shell.pipe(process.stdout);
510
+ * shell.write("whoami\n");
511
+ * await shell.close();
512
+ * ```
513
+ */
514
+ exec(cmd: string, opts?: ExecOptions & {
515
+ interactive?: false;
516
+ }): ExecHandle;
517
+ exec(cmd: string, opts: ExecOptions & {
518
+ interactive: true;
519
+ }): InteractiveExecHandle;
520
+ exec(cmd: string, opts: ExecOptions): ExecHandle | InteractiveExecHandle;
521
+ /** Backs `exec(cmd, { interactive: true })` — see that method's docs. */
522
+ private _execInteractive;
523
+ /**
524
+ * Create a code execution context for use with `execCode()`.
525
+ *
526
+ * The code interpreter requires a context for every `execCode()` call. Call
527
+ * this once per session (or once per isolated scope), then pass the returned
528
+ * object as `opts.context` to `execCode()`. Variables defined in one call
529
+ * are visible to subsequent calls sharing the same context.
530
+ *
531
+ * @example
532
+ * ```ts
533
+ * const ctx = await sb.createCodeContext(CodeLanguage.Python);
534
+ * await sb.execCode('x = 42', { context: ctx });
535
+ * await sb.execCode('print(x)', { context: ctx }); // prints 42
536
+ * ```
537
+ */
538
+ createCodeContext(language: import("@alineo-labs/opensandbox").CodeLanguage): Promise<import("@alineo-labs/opensandbox").CodeContext>;
539
+ /**
540
+ * Execute code via the sandbox's code interpreter (Python, JS, etc.).
541
+ *
542
+ * Uses the execd `/code` endpoint for stateful, Jupyter-style execution.
543
+ * Contexts persist across calls — use `opts.context` to target a specific one.
544
+ * Create a context first with `sb.createCodeContext(language)`.
545
+ */
546
+ execCode(code: string, opts?: ExecCodeOptions): ExecHandle;
547
+ /**
548
+ * Create a persistent bash session that preserves CWD and env vars across
549
+ * multiple `exec()` calls.
550
+ *
551
+ * Always call `session.close()` when done, or the shell process leaks inside
552
+ * the container. `sandbox.close()` also closes all open sessions automatically.
553
+ *
554
+ * @example
555
+ * ```ts
556
+ * const session = await sb.createSession({ cwd: "/app" });
557
+ * try {
558
+ * await session.exec("export DB_URL=postgres://localhost/mydb");
559
+ * await session.exec("npm run migrate").pipe(process.stdout);
560
+ * await session.exec("npm test").pipe(process.stdout);
561
+ * } finally {
562
+ * await session.close();
563
+ * }
564
+ * ```
565
+ */
566
+ createSession(opts?: {
567
+ cwd?: string;
568
+ }): Promise<BashSession>;
569
+ }
570
+ //#endregion
571
+ //#region src/sandbox/sandbox.d.ts
572
+ /**
573
+ * A live sandbox container. Returned by `Alineo.sandbox()` and `Alineo.resume()`.
574
+ *
575
+ * Call `exec()` to run commands, `checkpoint()` to snapshot state, and `close()`
576
+ * when done. Multiple sandboxes can be held simultaneously — just assign to
577
+ * different variables.
578
+ *
579
+ * @example
580
+ * ```ts
581
+ * const sb = await client.sandbox({ image: "node:22", resources: { cpu: "500m", memory: "256Mi" } });
582
+ * await sb.exec("npm ci");
583
+ * await sb.checkpoint();
584
+ * await sb.exec("npm test").pipe(process.stdout);
585
+ * await sb.close();
586
+ * ```
587
+ */
588
+ declare class Sandbox extends SandboxCore {
589
+ /** Write a file into the sandbox. */
590
+ writeFile(path: string, content: string): Promise<void>;
591
+ /** Read a file from the sandbox as a UTF-8 string. */
592
+ readFile(path: string): Promise<string>;
593
+ /** Delete a file from the sandbox. */
594
+ deleteFile(path: string): Promise<void>;
595
+ /** Move or rename a file inside the sandbox. */
596
+ moveFile(from: string, to: string): Promise<void>;
597
+ /** List files in a directory inside the sandbox. */
598
+ listDirectory(path: string, opts?: {
599
+ depth?: number;
600
+ }): Promise<FileInfo$1[]>;
601
+ /** Search for files matching a glob pattern inside the sandbox. */
602
+ searchFiles(pattern: string, path?: string): Promise<string[]>;
603
+ /** Create a directory (and parents) inside the sandbox. */
604
+ createDirectory(path: string): Promise<void>;
605
+ /** Delete a directory inside the sandbox. */
606
+ deleteDirectory(path: string): Promise<void>;
607
+ /** Return metadata for a file or directory (size, type, mode, timestamps). */
608
+ getFileInfo(path: string): Promise<FileInfo$1>;
609
+ /**
610
+ * Replace substrings in one or more files inside the sandbox.
611
+ *
612
+ * More efficient than `readFile` → string replace → `writeFile` for targeted edits.
613
+ *
614
+ * @example
615
+ * ```ts
616
+ * await sb.replaceInFiles([{ path: "/app/config.json", old: "localhost", new: "0.0.0.0" }]);
617
+ * ```
618
+ */
619
+ replaceInFiles(replacements: Array<{
620
+ path: string;
621
+ old: string;
622
+ new: string;
623
+ }>): Promise<void>;
624
+ /**
625
+ * Copy a file from this sandbox into another sandbox.
626
+ *
627
+ * Reads the file as a UTF-8 string and writes it to the same path on the target.
628
+ * Use this to move results between a fork and its origin, or between parallel sandboxes.
629
+ *
630
+ * @example
631
+ * ```ts
632
+ * await sb.transfer("/app/output.json", fork);
633
+ * ```
634
+ */
635
+ transfer(path: string, target: Sandbox): Promise<void>;
636
+ /**
637
+ * Return a proxied URL and auth headers for a port inside the sandbox.
638
+ *
639
+ * Use this to send HTTP requests to a server running inside the sandbox.
640
+ *
641
+ * @example
642
+ * ```ts
643
+ * await sb.exec("node server.js &");
644
+ * const { url, headers } = await sb.proxy(3000);
645
+ * const res = await fetch(`${url}/health`, { headers });
646
+ * ```
647
+ */
648
+ proxy(port: number): Promise<{
649
+ url: string;
650
+ headers: Record<string, string>;
651
+ }>;
652
+ /** Return current CPU and memory usage for this sandbox. */
653
+ metrics(): Promise<Metrics$1>;
654
+ /**
655
+ * Stream real-time CPU and memory metrics from execd via SSE.
656
+ *
657
+ * Holds a long-lived connection — break out of the loop when done to avoid
658
+ * leaking the connection. Takes no arguments; there is no way to cancel it
659
+ * other than breaking out of the `for await` loop.
660
+ *
661
+ * @example
662
+ * ```ts
663
+ * for await (const m of sb.watchMetrics()) {
664
+ * console.log(m.cpu, m.memory);
665
+ * if (m.cpu > 0.9) break;
666
+ * }
667
+ * ```
668
+ */
669
+ watchMetrics(): AsyncGenerator<Metrics$1>;
670
+ /** Return sandbox diagnostic logs (names, sizes, and optional inline content). */
671
+ diagnosticLogs(): Promise<DiagnosticLog$1[]>;
672
+ /** Return sandbox diagnostic events (timestamps, types, and messages). */
673
+ diagnosticEvents(): Promise<DiagnosticEvent$1[]>;
674
+ /**
675
+ * Freeze the sandbox container. Releases compute on Kubernetes; on Docker it
676
+ * is a cgroup freeze that preserves in-memory state.
677
+ *
678
+ * All pending exec calls will throw `SandboxError` until `resume()` is called.
679
+ * `close()` remains valid on a paused sandbox.
680
+ */
681
+ pause(): Promise<void>;
682
+ /**
683
+ * Restore a paused sandbox to Running state. The execd endpoint is not
684
+ * re-resolved here — `pause()` clears the cached client, so it's lazily
685
+ * re-resolved on the next call that needs it (e.g. the next `exec()`).
686
+ *
687
+ * On Docker, this unfreezes the container instantly. On Kubernetes, a new pod
688
+ * is created from the OCI snapshot — in-memory process state is not preserved.
689
+ * Polls until the sandbox reports Running before returning.
690
+ */
691
+ resume(): Promise<void>;
692
+ /** Return all checkpoints for this sandbox in creation order. */
693
+ listCheckpoints(): Promise<CheckpointInfo[]>;
694
+ /**
695
+ * Snapshot the current sandbox and return a new independent `Sandbox` from that state.
696
+ *
697
+ * The original sandbox keeps running. Both operate on separate containers restored
698
+ * from the same snapshot. Equivalent to `checkpoint()` followed by `Alineo.restoreSnapshot()`
699
+ * into a new sandbox, but without closing the original.
700
+ *
701
+ * @example
702
+ * ```ts
703
+ * await sb.exec("npm ci");
704
+ * const fork = await sb.fork("after-install");
705
+ *
706
+ * await sb.exec("npm test"); // runs on original
707
+ * await fork.exec("npm run build"); // runs on fork
708
+ * ```
709
+ *
710
+ * @param runId Override the forked sandbox's run-correlation ID (see `SandboxDetails.runId`)
711
+ * instead of inheriting this sandbox's own default.
712
+ */
713
+ fork(tag?: string, runId?: string): Promise<Sandbox>;
714
+ /**
715
+ * Capture a snapshot of the sandbox's current filesystem state.
716
+ *
717
+ * Writes a `checkpoint_created` event to the ledger with the snapshot ID and
718
+ * returns the snapshot ID. Use `Alineo.resume(sandboxId)` to restore from
719
+ * the latest checkpoint, or pass the returned ID to `Alineo.restoreSnapshot()`.
720
+ */
721
+ checkpoint(name?: string): Promise<string>;
722
+ /**
723
+ * Delete the sandbox container and release its resources.
724
+ *
725
+ * Always call `close()` when done — even on error — to avoid leaking containers.
726
+ * Idempotent: subsequent calls are no-ops.
727
+ */
728
+ close(): Promise<void>;
729
+ }
730
+ //#endregion
731
+ //#region src/sandbox/resolve.d.ts
732
+ /**
733
+ * Resolve an ExecClient for a sandbox. Calls getEndpoint once (each call
734
+ * returns a different ephemeral proxy port) then polls listContexts until
735
+ * execd is ready to accept connections.
736
+ *
737
+ * Defaults give ~80s of total patience (retries=45, capped at 2s/attempt), not the ~11s this
738
+ * had before (retries=15, capped at 1s/attempt). Bumped after a live `alineo fork` failure
739
+ * (issue #32): a child forked while its parent sandbox was busy running a real Chrome session
740
+ * took ~35s just to reach `Running`, then immediately exhausted the old ~11s execd-readiness
741
+ * budget before the exec daemon inside it had actually started accepting connections. An
742
+ * isolated repro of the identical fork (same snapshot, but from an idle parent with no
743
+ * concurrent browser load) reached execd-ready in under 400ms -- the parent's own host-resource
744
+ * contention at fork time, not snapshot size, is what actually eats the budget. This can't be
745
+ * fixed by scheduling around it from here, so it's addressed by simply affording much more
746
+ * patience before giving up.
747
+ */
748
+ declare function resolveExecClient(control: ControlClient, sandboxId: string, useServerProxy?: boolean, retries?: number, delayMs?: number): Promise<ExecClient>;
749
+ //#endregion
750
+ //#region src/sandbox/hooks.d.ts
751
+ interface ComposeHooksOptions {
752
+ /**
753
+ * Called when an individual hook throws. The error is otherwise swallowed — hooks are
754
+ * observability callbacks, so one broken adapter must not break sibling hooks or the
755
+ * sandbox operation that triggered them.
756
+ */
757
+ onHookError?: (error: unknown, hookIndex: number, method: keyof SandboxHooks) => void;
758
+ }
759
+ /**
760
+ * Merge multiple `SandboxHooks` into one, so more than one hooks-based adapter
761
+ * (`otelHooks(tracer)`, a billing hook, etc.) can attach to the same sandbox without
762
+ * hand-writing a merged object.
763
+ *
764
+ * Hooks fire in the order given, synchronously. Each invocation is isolated in its own
765
+ * try/catch — a throwing hook can't prevent sibling hooks, or the real sandbox operation
766
+ * that triggered them, from completing.
767
+ *
768
+ * @example
769
+ * ```ts
770
+ * import { composeHooks } from "@alineo-labs/core";
771
+ * import { otelHooks } from "@alineo-labs/otel";
772
+ *
773
+ * const sb = await client.sandbox({
774
+ * image: "ubuntu:22.04",
775
+ * resources: { cpu: "500m", memory: "512Mi" },
776
+ * hooks: composeHooks([otelHooks(tracer), billingHooks()], {
777
+ * onHookError: (error, index, method) => console.error(`hook ${index} ${method} failed`, error),
778
+ * }),
779
+ * });
780
+ * ```
781
+ */
782
+ declare function composeHooks(hooks: (SandboxHooks | undefined)[], opts?: ComposeHooksOptions): SandboxHooks;
783
+ //#endregion
784
+ //#region src/errors.d.ts
785
+ /** Base class for all alineo workflow runtime errors. */
786
+ declare class WorkflowError extends Error {
787
+ constructor(message: string);
788
+ }
789
+ /**
790
+ * Thrown for sandbox lifecycle failures — failing to create, boot, or reach
791
+ * `Running` state; being paused when an operation requires a live sandbox;
792
+ * `fork()` being unsupported on this sandbox; or a snapshot operation failing.
793
+ */
794
+ declare class SandboxError extends WorkflowError {
795
+ /** The sandbox ID, if one was assigned before the failure. */
796
+ readonly sandboxId?: string | undefined;
797
+ constructor(message: string, /** The sandbox ID, if one was assigned before the failure. */
798
+
799
+ sandboxId?: string | undefined);
800
+ }
801
+ /**
802
+ * Thrown when execd inside a sandbox never becomes ready within the retry window.
803
+ * The sandbox is `Running` from the control plane's perspective, but the exec
804
+ * daemon is not accepting connections.
805
+ */
806
+ declare class ExecConnectionError extends WorkflowError {
807
+ readonly sandboxId: string;
808
+ constructor(sandboxId: string);
809
+ }
810
+ /**
811
+ * Thrown when a command exits with a non-zero exit code. Carries the exit
812
+ * code and original command. For `Sandbox.exec()`, only thrown when `strict`
813
+ * is enabled (the default — pass `{ strict: false }` to opt out). For
814
+ * `BashSession.exec()` (a persistent session from `createSession()`), always
815
+ * thrown on non-zero exit; there is no `strict` option for session execs.
816
+ */
817
+ declare class CommandError extends WorkflowError {
818
+ readonly exitCode: number;
819
+ readonly command: string;
820
+ readonly sandboxId: string;
821
+ constructor(exitCode: number, command: string, sandboxId: string);
822
+ }
823
+ /**
824
+ * Reserved for a per-step timeout mechanism — not currently thrown anywhere
825
+ * in this codebase. `SandboxOptions.timeout`/`step.timeout` in `@alineo-labs/workflow`
826
+ * bound sandbox container lifetime, which is a related but distinct concept.
827
+ */
828
+ declare class StepTimeoutError extends WorkflowError {
829
+ readonly stepId: string;
830
+ readonly timeoutMs: number;
831
+ constructor(stepId: string, timeoutMs: number);
832
+ }
833
+ //#endregion
834
+ export { type AttachableSource, BashSession, type CheckpointInfo, CommandError, type ComposeHooksOptions, ConsoleLogger, type DiagnosticEvent, type DiagnosticLog, type EnvironmentRecord, type ExecCodeOptions, ExecConnectionError, ExecHandle, type ExecOptions, type ExecResult, type FileInfo, type ILogger, type IStorageAdapter, InteractiveExecHandle, type LedgerEntry, LedgerEvent, type ListSandboxOptions, LogLevel, type Metrics, type PendingInteractiveExec, type PtyControls, Sandbox, type SandboxDeps, type SandboxDetails, SandboxError, type SandboxHooks, SandboxStatus, StepTimeoutError, WorkflowError, composeHooks, noopLogger, resolveExecClient };