alineo 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/README.md ADDED
@@ -0,0 +1,178 @@
1
+ # alineo
2
+
3
+ Sandboxes as objects. Spawn live containers, run code, checkpoint state — from TypeScript.
4
+
5
+ ```bash
6
+ bun add alineo @alineo-labs/sqlite
7
+ ```
8
+
9
+ **[Full documentation →](https://docs.alineo.tech/docs/core)**
10
+
11
+ ---
12
+
13
+ ## Quickstart
14
+
15
+ ```ts
16
+ import { Alineo } from "alineo";
17
+ import { SQLiteAdapter } from "@alineo-labs/sqlite";
18
+
19
+ const client = new Alineo({
20
+ baseUrl: "http://localhost:8080",
21
+ adapter: new SQLiteAdapter("./ledger.db"),
22
+ });
23
+
24
+ const sb = await client.sandbox({
25
+ image: "ubuntu:22.04",
26
+ resources: { cpu: "500m", memory: "512Mi" },
27
+ });
28
+
29
+ const { stdout } = await sb.exec("node --version");
30
+ console.log(stdout); // v20.x.x
31
+
32
+ await sb.close();
33
+ ```
34
+
35
+ ---
36
+
37
+ ## Core concepts
38
+
39
+ **Sandbox as object** — `client.sandbox()` returns a live `Sandbox`. Call exec, file ops, checkpoint, and fork directly on it. No special API needed for multiple sandboxes — just multiple variables.
40
+
41
+ **ExecHandle** — `sb.exec("cmd")` returns an `ExecHandle` — a `PromiseLike<ExecResult>` with streaming built in.
42
+
43
+ ```ts
44
+ // Await result
45
+ const { stdout, stderr, exitCode } = await sb.exec("npm test");
46
+
47
+ // Stream to a writable
48
+ await sb.exec("npm run build").pipe(process.stdout);
49
+
50
+ // Async iteration
51
+ for await (const chunk of sb.exec("npm run build").stdout()) {
52
+ process.stdout.write(chunk);
53
+ }
54
+ ```
55
+
56
+ **Durable ledger** — every exec is written to the storage adapter. `client.resume(sandboxId)` restores the container and replays cached results from before the last checkpoint.
57
+
58
+ ---
59
+
60
+ ## File operations
61
+
62
+ ```ts
63
+ await sb.writeFile("/app/main.py", "print('hello')");
64
+ const content = await sb.readFile("/app/main.py");
65
+
66
+ await sb.createDirectory("/app/dist");
67
+ const info = await sb.getFileInfo("/app/main.py");
68
+
69
+ // In-place patch
70
+ await sb.replaceInFiles([{ path: "/app/main.py", old: "hello", new: "world" }]);
71
+
72
+ // Search, move, delete
73
+ const files = await sb.searchFiles("*.py", "/app");
74
+ await sb.moveFile("/tmp/out.txt", "/app/out.txt");
75
+ await sb.deleteFile("/app/main.py");
76
+
77
+ // Copy to another sandbox
78
+ await sb.transfer("/app/output.json", anotherSb);
79
+ ```
80
+
81
+ ## Checkpoint and resume
82
+
83
+ ```ts
84
+ const sb = await client.sandbox({
85
+ image: "ubuntu:22.04",
86
+ resources: { cpu: "500m", memory: "512Mi" },
87
+ });
88
+
89
+ await sb.exec("apt-get install -y curl");
90
+ await sb.checkpoint("after-setup");
91
+ await sb.close();
92
+
93
+ // Later — or after a crash
94
+ const restored = await client.resume(sb.sandboxId);
95
+ await restored.exec("curl https://example.com").pipe(process.stdout);
96
+ await restored.close();
97
+ ```
98
+
99
+ ## Environments
100
+
101
+ Define a named environment with a setup recipe. Built once, restored from snapshot on every subsequent call.
102
+
103
+ ```ts
104
+ const env = client.environment("python-data", {
105
+ image: "python:3.11-slim",
106
+ resources: { cpu: "1", memory: "1Gi" },
107
+ setup: async (sb) => {
108
+ await sb.exec("pip install numpy pandas scikit-learn");
109
+ },
110
+ });
111
+
112
+ const sb = await env.sandbox(); // ~2s after first run
113
+ await sb.exec("python3 -c 'import pandas; print(pandas.__version__)'").pipe(process.stdout);
114
+ await sb.close();
115
+ ```
116
+
117
+ ## Forking
118
+
119
+ ```ts
120
+ await sb.exec("npm ci");
121
+ const fork = await sb.fork();
122
+
123
+ await Promise.all([
124
+ sb.exec("npm test").pipe(process.stdout),
125
+ fork.exec("npm run build").pipe(process.stdout),
126
+ ]);
127
+
128
+ await Promise.all([sb.close(), fork.close()]);
129
+ ```
130
+
131
+ ## Error handling
132
+
133
+ ```ts
134
+ import { CommandError } from "alineo";
135
+
136
+ try {
137
+ await sb.exec("exit 1"); // strict: true by default
138
+ } catch (e) {
139
+ if (e instanceof CommandError) {
140
+ console.log(e.exitCode, e.command);
141
+ }
142
+ }
143
+
144
+ // Opt out of strict mode
145
+ const { exitCode } = await sb.exec("exit 1", { strict: false });
146
+ ```
147
+
148
+ ---
149
+
150
+ ## Configuration
151
+
152
+ ```ts
153
+ const client = new Alineo({
154
+ baseUrl: "http://localhost:8080", // OpenSandbox server URL
155
+ apiKey: "", // API key (empty for local dev)
156
+ adapter: new SQLiteAdapter("./alineo.db"),
157
+ maxConcurrency: 4, // cap simultaneous active sandboxes
158
+ useServerProxy: true, // required when server runs in Docker via alineo init
159
+ });
160
+ ```
161
+
162
+ ---
163
+
164
+ ## Local setup
165
+
166
+ Requires a running [OpenSandbox](https://open-sandbox.ai) instance:
167
+
168
+ ```bash
169
+ bunx alineo-cli init # starts OpenSandbox in Docker, recommended
170
+ # or
171
+ uvx opensandbox-server # manual, see docs for ~/.sandbox.toml config
172
+ ```
173
+
174
+ ---
175
+
176
+ ## License
177
+
178
+ Apache 2.0
@@ -0,0 +1,418 @@
1
+ import { BashSession, CheckpointInfo, CommandError, DiagnosticEvent, DiagnosticLog, EnvironmentRecord, EnvironmentRecord as EnvironmentRecord$1, EnvironmentRecord as EnvironmentRecord$2, ExecCodeOptions, ExecConnectionError, ExecHandle, ExecOptions, ExecResult, FileInfo, IStorageAdapter, IStorageAdapter as IStorageAdapter$1, InteractiveExecHandle, LedgerEntry, LedgerEvent, ListSandboxOptions, ListSandboxOptions as ListSandboxOptions$1, Metrics, PendingInteractiveExec, Sandbox, Sandbox as Sandbox$1, SandboxDetails, SandboxDetails as SandboxDetails$1, SandboxError, SandboxHooks, SandboxStatus, StepTimeoutError } from "@alineo-labs/core";
2
+ import { CodeLanguage } from "@alineo-labs/opensandbox";
3
+
4
+ //#region src/types.d.ts
5
+ /**
6
+ * Client-side SDK error carrying an HTTP-style status code, thrown for
7
+ * invariant/state failures such as a sandbox missing from the local ledger
8
+ * (404), a sandbox not in `Running` state (409), or a client-side timeout
9
+ * (408). This does not wrap non-2xx OpenSandbox API responses — those throw
10
+ * `OpenSandboxError` from `@alineo-labs/opensandbox`, which is never rethrown as a
11
+ * `AlineoError`.
12
+ */
13
+ declare class AlineoError extends Error {
14
+ readonly status: number;
15
+ constructor(message: string, status: number);
16
+ }
17
+ /** Options for constructing a {@link Alineo} client. */
18
+ interface AlineoOptions {
19
+ /** Base URL of your OpenSandbox server (e.g. `http://localhost:8080`). */
20
+ baseUrl: string;
21
+ /** OpenSandbox API key. Pass an empty string for local dev with no auth. */
22
+ apiKey?: string;
23
+ /**
24
+ * Storage adapter for persisting sandbox events.
25
+ *
26
+ * Pass `new SQLiteAdapter("./alineo.db")` from `@alineo-labs/sqlite` for local use, or
27
+ * `new PostgresAdapter(connectionString)` from `@alineo-labs/postgres` for production.
28
+ */
29
+ adapter: IStorageAdapter$1;
30
+ /**
31
+ * Maximum number of sandboxes that may be active simultaneously.
32
+ * When at capacity, `sandbox()` awaits until a slot is free.
33
+ * Omit for no limit.
34
+ */
35
+ maxConcurrency?: number;
36
+ /**
37
+ * Route execd and proxy traffic through the OpenSandbox server instead of
38
+ * connecting to sandbox containers directly. Required when the server runs
39
+ * in Docker (e.g. started via `alineo init`). Defaults to `false`.
40
+ */
41
+ useServerProxy?: boolean;
42
+ }
43
+ /** Options for `Alineo.resume()`. */
44
+ interface ResumeOptions {
45
+ /** Resume from the checkpoint with this tag. Defaults to the most recent checkpoint. */
46
+ tag?: string;
47
+ }
48
+ /** Options for `Alineo.sandbox()`. */
49
+ interface SandboxOptions {
50
+ /**
51
+ * Container image to run. Pass a string (`"node:22"`) or a full `ImageSpec`
52
+ * with optional auth (`{ uri: "ghcr.io/org/image", auth: { username, password } }`).
53
+ */
54
+ image: string | {
55
+ uri: string;
56
+ auth?: {
57
+ username: string;
58
+ password: string;
59
+ };
60
+ };
61
+ /** CPU/memory/GPU resource limits. Required by the OpenSandbox server. */
62
+ resources: {
63
+ cpu: string;
64
+ memory: string;
65
+ gpu?: string;
66
+ };
67
+ /** Environment variables set in the container at startup. */
68
+ env?: Record<string, string>;
69
+ /** Arbitrary key-value labels attached to the sandbox. Not ledger-queryable — see `runId`. */
70
+ metadata?: Record<string, string>;
71
+ /**
72
+ * User-provided name for this sandbox run. Used as the ledger key.
73
+ * Defaults to `"sandbox-<first 8 chars of sandboxId>"` if omitted.
74
+ */
75
+ name?: string;
76
+ /**
77
+ * Identifies the logical run this sandbox belongs to — see `SandboxDetails.runId`.
78
+ * Defaults to a fresh `crypto.randomUUID()` if omitted. A resumed, forked, or
79
+ * restored-from-snapshot sandbox always inherits its origin's `runId` rather than getting
80
+ * a new one, so pass this explicitly only when correlating independent top-level sandboxes
81
+ * that don't share a fork/resume relationship (e.g. two agents started separately by the
82
+ * same host script for one logical run).
83
+ */
84
+ runId?: string;
85
+ /** Sandbox lifetime in seconds. Defaults to the OpenSandbox server default. */
86
+ timeout?: number;
87
+ /** Observability hooks (e.g. `otelHooks(tracer)` from `@alineo-labs/otel`). */
88
+ hooks?: SandboxHooks;
89
+ /**
90
+ * Default shell for all `sb.exec()` calls on this sandbox.
91
+ * Pass an absolute path to the shell binary (e.g. `"/bin/bash"`, `"/bin/zsh"`).
92
+ * Defaults to `"/bin/sh"`.
93
+ */
94
+ shell?: string;
95
+ /**
96
+ * Override the container entrypoint. Defaults to `["tail", "-f", "/dev/null"]`
97
+ * which keeps the container alive without a TTY.
98
+ *
99
+ * Set this when using images that need their own init process — for example,
100
+ * `opensandbox/code-interpreter` requires `["/opt/code-interpreter/code-interpreter.sh"]`
101
+ * to start the Jupyter kernel service that `execCode()` depends on.
102
+ */
103
+ entrypoint?: string[];
104
+ }
105
+ //#endregion
106
+ //#region src/environment.d.ts
107
+ interface EnvironmentOptions {
108
+ /**
109
+ * Container image to boot. Same format as `SandboxOptions.image` —
110
+ * a string URI or a full spec with optional auth.
111
+ */
112
+ image: string | {
113
+ uri: string;
114
+ auth?: {
115
+ username: string;
116
+ password: string;
117
+ };
118
+ };
119
+ /** CPU/memory/GPU limits applied to both the build sandbox and each spawned sandbox. */
120
+ resources: {
121
+ cpu: string;
122
+ memory: string;
123
+ gpu?: string;
124
+ };
125
+ /**
126
+ * Setup function run once on a fresh sandbox during the first `env.sandbox()` call
127
+ * (or after `env.rebuild()`). Install packages, copy files, write config — anything
128
+ * that makes the environment ready. The result is snapshotted and reused from then on.
129
+ */
130
+ setup: (sb: Sandbox$1) => Promise<void>;
131
+ /**
132
+ * Default shell for all `exec()` calls — both during setup and in sandboxes spawned
133
+ * from this environment. Pass an absolute path (e.g. `"/bin/bash"`).
134
+ * Defaults to `"/bin/sh"`.
135
+ */
136
+ shell?: string;
137
+ }
138
+ /** Extra options forwarded to each sandbox spawned from an environment. */
139
+ interface EnvironmentSandboxOptions {
140
+ /** Additional environment variables set at container startup. */
141
+ env?: Record<string, string>;
142
+ /** Observability hooks. */
143
+ hooks?: SandboxHooks;
144
+ /**
145
+ * Override the shell for this spawned sandbox only.
146
+ * Falls back to `EnvironmentOptions.shell`, then `"/bin/sh"`.
147
+ */
148
+ shell?: string;
149
+ }
150
+ /**
151
+ * A named, reusable sandbox environment.
152
+ *
153
+ * Created via `client.environment(name, opts)`. The first call to `env.sandbox()`
154
+ * runs the setup recipe, snapshots the result, and caches the snapshot ID in the
155
+ * ledger. Subsequent calls restore from that snapshot — skipping setup entirely.
156
+ *
157
+ * @example
158
+ * ```ts
159
+ * const env = client.environment("python", {
160
+ * image: "debian:bookworm-slim",
161
+ * resources: { cpu: "500m", memory: "512Mi" },
162
+ * setup: async (sb) => {
163
+ * await sb.exec("apt-get update -qq && apt-get install -y python3-pip");
164
+ * await sb.exec("pip install numpy pandas");
165
+ * },
166
+ * });
167
+ *
168
+ * const sb = await env.sandbox();
169
+ * try {
170
+ * await sb.exec("python3 -c 'import pandas; print(pandas.__version__)'").pipe(process.stdout);
171
+ * } finally {
172
+ * await sb.close();
173
+ * }
174
+ * ```
175
+ */
176
+ declare class Environment {
177
+ /** The environment name, as passed to `client.environment()`. */
178
+ readonly name: string;
179
+ private readonly opts;
180
+ private readonly client;
181
+ constructor(/** The environment name, as passed to `client.environment()`. */
182
+
183
+ name: string, opts: EnvironmentOptions, client: Alineo);
184
+ /**
185
+ * Return a sandbox pre-configured with this environment.
186
+ *
187
+ * First call: runs the setup recipe (~30–60 s), snapshots the result.
188
+ * Subsequent calls: restores from snapshot (~2–3 s), no setup re-run.
189
+ * Concurrent first calls share a single build — setup runs exactly once.
190
+ */
191
+ sandbox(extra?: EnvironmentSandboxOptions): Promise<Sandbox$1>;
192
+ /**
193
+ * Force a full rebuild of the environment, regardless of any cached snapshot.
194
+ * Use this after changing the setup recipe.
195
+ */
196
+ rebuild(): Promise<void>;
197
+ /**
198
+ * Return the cached environment record, or `null` if the environment has not
199
+ * been built yet.
200
+ */
201
+ info(): Promise<EnvironmentRecord$2 | null>;
202
+ }
203
+ //#endregion
204
+ //#region src/client.d.ts
205
+ /**
206
+ * Main entry point for alineo. Manages sandbox lifecycle and session history.
207
+ *
208
+ * @example
209
+ * ```ts
210
+ * import { Alineo } from "alineo";
211
+ * import { SQLiteAdapter } from "@alineo-labs/sqlite";
212
+ *
213
+ * const client = new Alineo({
214
+ * baseUrl: "http://localhost:8080",
215
+ * adapter: new SQLiteAdapter("./alineo.db"),
216
+ * });
217
+ *
218
+ * const sb = await client.sandbox({ image: "node:22", resources: { cpu: "500m", memory: "256Mi" } });
219
+ * await sb.exec("npm ci");
220
+ * await sb.checkpoint();
221
+ * await sb.exec("npm test").pipe(process.stdout);
222
+ * await sb.close();
223
+ * ```
224
+ */
225
+ declare class Alineo {
226
+ private readonly _control;
227
+ private readonly _adapter;
228
+ private readonly _maxConcurrency;
229
+ private readonly _useServerProxy;
230
+ private _activeCount;
231
+ private readonly _waiters;
232
+ private _connectPromise;
233
+ private _adapterClosed;
234
+ private readonly _envBuilds;
235
+ constructor(options: AlineoOptions);
236
+ /** Lazily initialises the adapter on first use. Concurrent callers share the same promise. */
237
+ private _ensureConnected;
238
+ /**
239
+ * Create a new sandbox container and return a live `Sandbox` object.
240
+ *
241
+ * Waits until the container reaches `Running` state before returning.
242
+ * Call `sb.close()` when done to release resources (use try/finally).
243
+ *
244
+ * @example
245
+ * ```ts
246
+ * const sb = await client.sandbox({ image: "node:22", resources: { cpu: "500m", memory: "256Mi" } });
247
+ * try {
248
+ * await sb.exec("npm ci");
249
+ * await sb.exec("npm test").pipe(process.stdout);
250
+ * } finally {
251
+ * await sb.close();
252
+ * }
253
+ * ```
254
+ */
255
+ sandbox(opts: SandboxOptions): Promise<Sandbox$1>;
256
+ /**
257
+ * Resume a sandbox session from its last checkpoint.
258
+ *
259
+ * Restores an OpenSandbox container from the snapshot captured by the most
260
+ * recent `sb.checkpoint()` call. Execs that completed before the checkpoint
261
+ * are returned from ledger cache without re-running; subsequent execs run
262
+ * against the restored container.
263
+ *
264
+ * @example
265
+ * ```ts
266
+ * // original session (crashed mid-test)
267
+ * const sb = await client.sandbox({ image: "node:22", name: "ci", resources: { cpu: "500m", memory: "256Mi" } });
268
+ * await sb.exec("npm ci");
269
+ * await sb.checkpoint();
270
+ * await sb.exec("npm test"); // container dies here
271
+ *
272
+ * // resume later
273
+ * const sb2 = await client.resume(originalSessionId);
274
+ * await sb2.exec("npm ci"); // instant — replayed from ledger
275
+ * await sb2.exec("npm test"); // actually runs on restored container
276
+ * await sb2.close();
277
+ * ```
278
+ */
279
+ resume(sandboxId: string, opts?: ResumeOptions): Promise<Sandbox$1>;
280
+ private _resumeSession;
281
+ /**
282
+ * Attach to an already-running sandbox container without creating or restoring anything.
283
+ *
284
+ * Use this to reconnect to a sandbox whose host process has exited but whose container
285
+ * is still running. Unlike `resume()`, no snapshot is involved — the container keeps
286
+ * its current state. The execd endpoint is resolved lazily on first use.
287
+ *
288
+ * @throws `AlineoError` (409) if the sandbox is not in Running state.
289
+ *
290
+ * @param opts.resources CPU/memory/GPU to use if `.fork()` is later called on the
291
+ * returned `Sandbox`. The control API doesn't echo back a running sandbox's own
292
+ * resource limits, so there's no way to discover them automatically here — omit
293
+ * this and `.fork()` will throw. Pass it (e.g. from `alineo.config.json`'s
294
+ * defaults) when the caller needs fork support on a merely-connected sandbox.
295
+ * @param opts.runId Default run-correlation ID for any later `.fork()` call on the
296
+ * returned `Sandbox`. `connect()` has no way to discover the sandbox's original
297
+ * `runId` (no ledger lookup is attempted — the caller may be using a completely
298
+ * different adapter than whatever originally created it, as `alineo fork` does when
299
+ * self-attaching). Omit this and pass `runId` explicitly to `.fork()` itself instead.
300
+ *
301
+ * @example
302
+ * ```ts
303
+ * // In a new process, reconnect to a sandbox started earlier:
304
+ * const sb = await client.connect(savedSandboxId, "my-sandbox");
305
+ * const { stdout } = await sb.exec("cat /results.txt");
306
+ * await sb.close();
307
+ * ```
308
+ */
309
+ connect(sandboxId: string, name: string, opts?: {
310
+ resources?: {
311
+ cpu: string;
312
+ memory: string;
313
+ gpu?: string;
314
+ };
315
+ runId?: string;
316
+ }): Promise<Sandbox$1>;
317
+ /**
318
+ * Create a fresh sandbox from a snapshot ID without exec replay.
319
+ *
320
+ * Unlike `resume()`, this does not replay prior exec results — the new sandbox
321
+ * starts with a clean exec history. Use this when you want to restore a
322
+ * checkpointed environment and run new commands from scratch.
323
+ *
324
+ * @param snapshotId The snapshot ID returned by `sb.checkpoint()`.
325
+ * @param name A name for the new sandbox session in the ledger.
326
+ * @param resources CPU and memory for the restored container.
327
+ * @param runId Run-correlation ID for the restored sandbox — see `SandboxDetails.runId`.
328
+ * Defaults to a fresh `crypto.randomUUID()` if omitted.
329
+ *
330
+ * @example
331
+ * ```ts
332
+ * const snapshotId = await sb.checkpoint();
333
+ * await sb.close();
334
+ *
335
+ * // Later — restore and run fresh commands:
336
+ * const sb2 = await client.restoreSnapshot(snapshotId, "my-sandbox", { cpu: "500m", memory: "256Mi" });
337
+ * await sb2.exec("npm test");
338
+ * await sb2.close();
339
+ * ```
340
+ */
341
+ restoreSnapshot(snapshotId: string, name: string, resources: {
342
+ cpu: string;
343
+ memory: string;
344
+ gpu?: string;
345
+ }, runId?: string): Promise<Sandbox$1>;
346
+ /**
347
+ * Sandbox history management. List, inspect, and delete past sandbox records.
348
+ *
349
+ * @example
350
+ * ```ts
351
+ * const all = await client.sandboxes.list();
352
+ * const details = await client.sandboxes.get("ci", sandboxId);
353
+ * await client.sandboxes.delete("ci", sandboxId);
354
+ * ```
355
+ */
356
+ readonly sandboxes: {
357
+ /** List all sandbox records across all names, newest first. */list: (opts?: ListSandboxOptions$1) => Promise<SandboxDetails$1[]>; /** List sandbox records for a specific name, newest first. */
358
+ listByName: (name: string, opts?: ListSandboxOptions$1) => Promise<SandboxDetails$1[]>; /** Return details for a single sandbox record. Returns `null` if not found. */
359
+ get: (name: string, sandboxId: string) => Promise<SandboxDetails$1 | null>; /** Delete all ledger events for a sandbox. */
360
+ delete: (name: string, sandboxId: string) => Promise<void>;
361
+ };
362
+ /**
363
+ * Define a named, reusable sandbox environment.
364
+ *
365
+ * Returns an `Environment` object — no I/O happens here. The first call to
366
+ * `env.sandbox()` builds the environment (runs setup + snapshots), then caches
367
+ * the snapshot ID in the ledger. Subsequent calls restore from that snapshot.
368
+ *
369
+ * @example
370
+ * ```ts
371
+ * const env = client.environment("python", {
372
+ * image: "debian:bookworm-slim",
373
+ * resources: { cpu: "500m", memory: "512Mi" },
374
+ * setup: async (sb) => {
375
+ * await sb.exec("apt-get update -qq && apt-get install -y python3-pip");
376
+ * await sb.exec("pip install numpy pandas");
377
+ * },
378
+ * });
379
+ *
380
+ * const sb = await env.sandbox();
381
+ * try {
382
+ * await sb.exec("python3 -c 'import pandas; print(pandas.__version__)'").pipe(process.stdout);
383
+ * } finally {
384
+ * await sb.close();
385
+ * }
386
+ * ```
387
+ */
388
+ environment(name: string, opts: EnvironmentOptions): Environment;
389
+ /**
390
+ * Environment management. List and delete cached environment records.
391
+ *
392
+ * @example
393
+ * ```ts
394
+ * const envs = await client.environments.list();
395
+ * await client.environments.delete("python");
396
+ * ```
397
+ */
398
+ readonly environments: {
399
+ /** Return all environment records, newest first. */list: () => Promise<EnvironmentRecord$1[]>; /** Remove the ledger record for a named environment. Does not delete the server-side snapshot. */
400
+ delete: (name: string) => Promise<void>;
401
+ };
402
+ _envInfo(name: string): Promise<EnvironmentRecord$1 | null>;
403
+ _envRebuild(name: string, opts: EnvironmentOptions): Promise<void>;
404
+ _envSandbox(name: string, opts: EnvironmentOptions, extra?: EnvironmentSandboxOptions): Promise<Sandbox$1>;
405
+ _getOrBuildEnvironment(name: string, opts: EnvironmentOptions): Promise<string>;
406
+ _buildEnvironment(name: string, opts: EnvironmentOptions): Promise<string>;
407
+ _createFromSnapshot(snapshotId: string, resources: {
408
+ cpu: string;
409
+ memory: string;
410
+ gpu?: string;
411
+ }, envName: string, envShell?: string, extra?: EnvironmentSandboxOptions): Promise<Sandbox$1>;
412
+ private _forkFromSnapshot;
413
+ private _waitForRunning;
414
+ private _acquireSlot;
415
+ private _releaseSlot;
416
+ }
417
+ //#endregion
418
+ export { Alineo, AlineoError, type AlineoOptions, BashSession, type CheckpointInfo, CodeLanguage, CommandError, type DiagnosticEvent, type DiagnosticLog, Environment, type EnvironmentOptions, type EnvironmentRecord, type EnvironmentSandboxOptions, type ExecCodeOptions, ExecConnectionError, type ExecHandle, type ExecOptions, type ExecResult, type FileInfo, type IStorageAdapter, type InteractiveExecHandle, type LedgerEntry, LedgerEvent, type ListSandboxOptions, type Metrics, type PendingInteractiveExec, type ResumeOptions, Sandbox, type SandboxDetails, SandboxError, type SandboxOptions, SandboxStatus, StepTimeoutError };
package/dist/index.mjs ADDED
@@ -0,0 +1,657 @@
1
+ import { BashSession, CommandError, ExecConnectionError, LedgerEvent, LedgerEvent as LedgerEvent$1, Sandbox, Sandbox as Sandbox$1, SandboxError, SandboxStatus, StepTimeoutError } from "@alineo-labs/core";
2
+ import { CodeLanguage, ControlClient, SandboxState, SnapshotState } from "@alineo-labs/opensandbox";
3
+ //#region src/types.ts
4
+ /**
5
+ * Client-side SDK error carrying an HTTP-style status code, thrown for
6
+ * invariant/state failures such as a sandbox missing from the local ledger
7
+ * (404), a sandbox not in `Running` state (409), or a client-side timeout
8
+ * (408). This does not wrap non-2xx OpenSandbox API responses — those throw
9
+ * `OpenSandboxError` from `@alineo-labs/opensandbox`, which is never rethrown as a
10
+ * `AlineoError`.
11
+ */
12
+ var AlineoError = class extends Error {
13
+ status;
14
+ constructor(message, status) {
15
+ super(message);
16
+ this.status = status;
17
+ this.name = "AlineoError";
18
+ }
19
+ };
20
+ //#endregion
21
+ //#region src/environment.ts
22
+ /**
23
+ * A named, reusable sandbox environment.
24
+ *
25
+ * Created via `client.environment(name, opts)`. The first call to `env.sandbox()`
26
+ * runs the setup recipe, snapshots the result, and caches the snapshot ID in the
27
+ * ledger. Subsequent calls restore from that snapshot — skipping setup entirely.
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * const env = client.environment("python", {
32
+ * image: "debian:bookworm-slim",
33
+ * resources: { cpu: "500m", memory: "512Mi" },
34
+ * setup: async (sb) => {
35
+ * await sb.exec("apt-get update -qq && apt-get install -y python3-pip");
36
+ * await sb.exec("pip install numpy pandas");
37
+ * },
38
+ * });
39
+ *
40
+ * const sb = await env.sandbox();
41
+ * try {
42
+ * await sb.exec("python3 -c 'import pandas; print(pandas.__version__)'").pipe(process.stdout);
43
+ * } finally {
44
+ * await sb.close();
45
+ * }
46
+ * ```
47
+ */
48
+ var Environment = class {
49
+ name;
50
+ opts;
51
+ client;
52
+ constructor(name, opts, client) {
53
+ this.name = name;
54
+ this.opts = opts;
55
+ this.client = client;
56
+ }
57
+ /**
58
+ * Return a sandbox pre-configured with this environment.
59
+ *
60
+ * First call: runs the setup recipe (~30–60 s), snapshots the result.
61
+ * Subsequent calls: restores from snapshot (~2–3 s), no setup re-run.
62
+ * Concurrent first calls share a single build — setup runs exactly once.
63
+ */
64
+ sandbox(extra) {
65
+ return this.client._envSandbox(this.name, this.opts, extra);
66
+ }
67
+ /**
68
+ * Force a full rebuild of the environment, regardless of any cached snapshot.
69
+ * Use this after changing the setup recipe.
70
+ */
71
+ rebuild() {
72
+ return this.client._envRebuild(this.name, this.opts);
73
+ }
74
+ /**
75
+ * Return the cached environment record, or `null` if the environment has not
76
+ * been built yet.
77
+ */
78
+ info() {
79
+ return this.client._envInfo(this.name);
80
+ }
81
+ };
82
+ //#endregion
83
+ //#region src/client.ts
84
+ /**
85
+ * Main entry point for alineo. Manages sandbox lifecycle and session history.
86
+ *
87
+ * @example
88
+ * ```ts
89
+ * import { Alineo } from "alineo";
90
+ * import { SQLiteAdapter } from "@alineo-labs/sqlite";
91
+ *
92
+ * const client = new Alineo({
93
+ * baseUrl: "http://localhost:8080",
94
+ * adapter: new SQLiteAdapter("./alineo.db"),
95
+ * });
96
+ *
97
+ * const sb = await client.sandbox({ image: "node:22", resources: { cpu: "500m", memory: "256Mi" } });
98
+ * await sb.exec("npm ci");
99
+ * await sb.checkpoint();
100
+ * await sb.exec("npm test").pipe(process.stdout);
101
+ * await sb.close();
102
+ * ```
103
+ */
104
+ var Alineo = class {
105
+ _control;
106
+ _adapter;
107
+ _maxConcurrency;
108
+ _useServerProxy;
109
+ _activeCount = 0;
110
+ _waiters = [];
111
+ _connectPromise = null;
112
+ _adapterClosed = false;
113
+ _envBuilds = /* @__PURE__ */ new Map();
114
+ constructor(options) {
115
+ this._control = new ControlClient({
116
+ baseUrl: options.baseUrl,
117
+ apiKey: options.apiKey ?? ""
118
+ });
119
+ this._adapter = options.adapter;
120
+ this._maxConcurrency = options.maxConcurrency;
121
+ this._useServerProxy = options.useServerProxy ?? false;
122
+ process.setMaxListeners(process.getMaxListeners() + 1);
123
+ process.on("beforeExit", () => {
124
+ if (!this._adapterClosed) {
125
+ this._adapterClosed = true;
126
+ this._adapter.close?.();
127
+ }
128
+ });
129
+ }
130
+ /** Lazily initialises the adapter on first use. Concurrent callers share the same promise. */
131
+ _ensureConnected() {
132
+ this._connectPromise ??= this._adapter.connect?.() ?? Promise.resolve();
133
+ return this._connectPromise;
134
+ }
135
+ /**
136
+ * Create a new sandbox container and return a live `Sandbox` object.
137
+ *
138
+ * Waits until the container reaches `Running` state before returning.
139
+ * Call `sb.close()` when done to release resources (use try/finally).
140
+ *
141
+ * @example
142
+ * ```ts
143
+ * const sb = await client.sandbox({ image: "node:22", resources: { cpu: "500m", memory: "256Mi" } });
144
+ * try {
145
+ * await sb.exec("npm ci");
146
+ * await sb.exec("npm test").pipe(process.stdout);
147
+ * } finally {
148
+ * await sb.close();
149
+ * }
150
+ * ```
151
+ */
152
+ async sandbox(opts) {
153
+ await this._ensureConnected();
154
+ await this._acquireSlot();
155
+ const image = typeof opts.image === "string" ? { uri: opts.image } : opts.image;
156
+ const runId = opts.runId ?? crypto.randomUUID();
157
+ let sandboxId;
158
+ try {
159
+ sandboxId = (await this._control.createSandbox({
160
+ image,
161
+ env: opts.env,
162
+ metadata: {
163
+ ...opts.metadata,
164
+ runId
165
+ },
166
+ entrypoint: opts.entrypoint ?? [
167
+ "tail",
168
+ "-f",
169
+ "/dev/null"
170
+ ],
171
+ resourceLimits: opts.resources,
172
+ timeout: opts.timeout
173
+ })).id;
174
+ await this._waitForRunning(sandboxId);
175
+ const name = opts.name ?? `sandbox-${sandboxId.slice(0, 8)}`;
176
+ await this._adapter.append({
177
+ ts: Date.now(),
178
+ name,
179
+ sandboxId,
180
+ stepIndex: -1,
181
+ event: LedgerEvent$1.SandboxCreated,
182
+ payload: {
183
+ sandboxId,
184
+ resources: opts.resources,
185
+ runId
186
+ }
187
+ });
188
+ const sb = new Sandbox$1(sandboxId, name, {
189
+ control: this._control,
190
+ adapter: this._adapter,
191
+ hooks: opts.hooks,
192
+ onClose: () => this._releaseSlot(),
193
+ shell: opts.shell,
194
+ fork: (snapshotId, tag, overrideRunId) => this._forkFromSnapshot(snapshotId, name, opts.resources, opts.shell, overrideRunId ?? runId),
195
+ useServerProxy: this._useServerProxy
196
+ });
197
+ opts.hooks?.onSandboxCreated?.(sandboxId, name);
198
+ return sb;
199
+ } catch (err) {
200
+ this._releaseSlot();
201
+ throw err;
202
+ }
203
+ }
204
+ /**
205
+ * Resume a sandbox session from its last checkpoint.
206
+ *
207
+ * Restores an OpenSandbox container from the snapshot captured by the most
208
+ * recent `sb.checkpoint()` call. Execs that completed before the checkpoint
209
+ * are returned from ledger cache without re-running; subsequent execs run
210
+ * against the restored container.
211
+ *
212
+ * @example
213
+ * ```ts
214
+ * // original session (crashed mid-test)
215
+ * const sb = await client.sandbox({ image: "node:22", name: "ci", resources: { cpu: "500m", memory: "256Mi" } });
216
+ * await sb.exec("npm ci");
217
+ * await sb.checkpoint();
218
+ * await sb.exec("npm test"); // container dies here
219
+ *
220
+ * // resume later
221
+ * const sb2 = await client.resume(originalSessionId);
222
+ * await sb2.exec("npm ci"); // instant — replayed from ledger
223
+ * await sb2.exec("npm test"); // actually runs on restored container
224
+ * await sb2.close();
225
+ * ```
226
+ */
227
+ async resume(sandboxId, opts) {
228
+ await this._ensureConnected();
229
+ const session = (await this._adapter.listAllSandboxDetails()).find((s) => s.sandboxId === sandboxId);
230
+ if (!session) throw new AlineoError(`Session ${sandboxId} not found`, 404);
231
+ return this._resumeSession(session.name, sandboxId, opts?.tag);
232
+ }
233
+ async _resumeSession(name, sandboxId, tag) {
234
+ const entries = await this._adapter.readAll(name, sandboxId);
235
+ let checkpointIdx;
236
+ if (tag) {
237
+ checkpointIdx = entries.findIndex((e) => e.event === LedgerEvent$1.CheckpointCreated && e.payload?.name === tag);
238
+ if (checkpointIdx === -1) throw new AlineoError(`No checkpoint with tag '${tag}' found for session ${sandboxId}`, 404);
239
+ } else {
240
+ checkpointIdx = entries.map((e) => e.event).lastIndexOf(LedgerEvent$1.CheckpointCreated);
241
+ if (checkpointIdx === -1) throw new AlineoError(`No checkpoint found for session ${sandboxId}`, 404);
242
+ }
243
+ const { snapshotId } = entries[checkpointIdx].payload;
244
+ const createdEntry = entries.find((e) => e.event === LedgerEvent$1.SandboxCreated);
245
+ const resources = (createdEntry?.payload)?.resources;
246
+ const runId = (createdEntry?.payload)?.runId ?? crypto.randomUUID();
247
+ const replayCache = /* @__PURE__ */ new Map();
248
+ const pendingStdout = /* @__PURE__ */ new Map();
249
+ const pendingStderr = /* @__PURE__ */ new Map();
250
+ const pendingStdin = /* @__PURE__ */ new Map();
251
+ const interactiveMeta = /* @__PURE__ */ new Map();
252
+ for (const entry of entries.slice(0, checkpointIdx)) if (entry.event === LedgerEvent$1.ExecStart) {
253
+ const { seq, cmd, interactive, cwd, env } = entry.payload;
254
+ pendingStdout.set(seq, []);
255
+ pendingStderr.set(seq, []);
256
+ if (interactive) {
257
+ pendingStdin.set(seq, []);
258
+ interactiveMeta.set(seq, {
259
+ cmd,
260
+ cwd,
261
+ env
262
+ });
263
+ }
264
+ } else if (entry.event === LedgerEvent$1.ExecEvent) {
265
+ const { seq, type, text } = entry.payload;
266
+ if (text) {
267
+ if (type === "stdout") pendingStdout.get(seq)?.push(text);
268
+ else if (type === "stderr") pendingStderr.get(seq)?.push(text);
269
+ else if (type === "stdin") pendingStdin.get(seq)?.push(text);
270
+ }
271
+ } else if (entry.event === LedgerEvent$1.ExecComplete) {
272
+ const { seq, exitCode } = entry.payload;
273
+ replayCache.set(seq, {
274
+ stdout: (pendingStdout.get(seq) ?? []).join(""),
275
+ stderr: (pendingStderr.get(seq) ?? []).join(""),
276
+ exitCode
277
+ });
278
+ }
279
+ const pendingInteractive = /* @__PURE__ */ new Map();
280
+ for (const [seq, meta] of interactiveMeta) {
281
+ if (replayCache.has(seq)) continue;
282
+ pendingInteractive.set(seq, {
283
+ ...meta,
284
+ stdin: pendingStdin.get(seq) ?? [],
285
+ stdout: (pendingStdout.get(seq) ?? []).join("")
286
+ });
287
+ }
288
+ await this._acquireSlot();
289
+ try {
290
+ const newSessionId = (await this._control.createSandbox({
291
+ snapshotId,
292
+ resourceLimits: resources,
293
+ metadata: { runId }
294
+ })).id;
295
+ await this._waitForRunning(newSessionId);
296
+ await this._adapter.append({
297
+ ts: Date.now(),
298
+ name,
299
+ sandboxId: newSessionId,
300
+ stepIndex: -1,
301
+ event: LedgerEvent$1.SandboxCreated,
302
+ payload: {
303
+ sandboxId: newSessionId,
304
+ resumedFrom: sandboxId,
305
+ snapshotId,
306
+ runId
307
+ }
308
+ });
309
+ return new Sandbox$1(newSessionId, name, {
310
+ control: this._control,
311
+ adapter: this._adapter,
312
+ onClose: () => this._releaseSlot(),
313
+ fork: resources?.cpu && resources?.memory ? (snapshotId, tag, overrideRunId) => this._forkFromSnapshot(snapshotId, name, resources, void 0, overrideRunId ?? runId) : void 0,
314
+ useServerProxy: this._useServerProxy
315
+ }, replayCache, pendingInteractive);
316
+ } catch (err) {
317
+ this._releaseSlot();
318
+ throw err;
319
+ }
320
+ }
321
+ /**
322
+ * Attach to an already-running sandbox container without creating or restoring anything.
323
+ *
324
+ * Use this to reconnect to a sandbox whose host process has exited but whose container
325
+ * is still running. Unlike `resume()`, no snapshot is involved — the container keeps
326
+ * its current state. The execd endpoint is resolved lazily on first use.
327
+ *
328
+ * @throws `AlineoError` (409) if the sandbox is not in Running state.
329
+ *
330
+ * @param opts.resources CPU/memory/GPU to use if `.fork()` is later called on the
331
+ * returned `Sandbox`. The control API doesn't echo back a running sandbox's own
332
+ * resource limits, so there's no way to discover them automatically here — omit
333
+ * this and `.fork()` will throw. Pass it (e.g. from `alineo.config.json`'s
334
+ * defaults) when the caller needs fork support on a merely-connected sandbox.
335
+ * @param opts.runId Default run-correlation ID for any later `.fork()` call on the
336
+ * returned `Sandbox`. `connect()` has no way to discover the sandbox's original
337
+ * `runId` (no ledger lookup is attempted — the caller may be using a completely
338
+ * different adapter than whatever originally created it, as `alineo fork` does when
339
+ * self-attaching). Omit this and pass `runId` explicitly to `.fork()` itself instead.
340
+ *
341
+ * @example
342
+ * ```ts
343
+ * // In a new process, reconnect to a sandbox started earlier:
344
+ * const sb = await client.connect(savedSandboxId, "my-sandbox");
345
+ * const { stdout } = await sb.exec("cat /results.txt");
346
+ * await sb.close();
347
+ * ```
348
+ */
349
+ async connect(sandboxId, name, opts) {
350
+ await this._ensureConnected();
351
+ const info = await this._control.getSandbox(sandboxId);
352
+ if (info.status.state !== SandboxState.Running) throw new AlineoError(`Sandbox ${sandboxId} is ${info.status.state} — can only connect to Running sandboxes`, 409);
353
+ await this._acquireSlot();
354
+ const resources = opts?.resources;
355
+ return new Sandbox$1(sandboxId, name, {
356
+ control: this._control,
357
+ adapter: this._adapter,
358
+ onClose: () => this._releaseSlot(),
359
+ fork: resources ? (snapshotId, tag, overrideRunId) => this._forkFromSnapshot(snapshotId, name, resources, void 0, overrideRunId ?? opts?.runId) : void 0,
360
+ useServerProxy: this._useServerProxy
361
+ });
362
+ }
363
+ /**
364
+ * Create a fresh sandbox from a snapshot ID without exec replay.
365
+ *
366
+ * Unlike `resume()`, this does not replay prior exec results — the new sandbox
367
+ * starts with a clean exec history. Use this when you want to restore a
368
+ * checkpointed environment and run new commands from scratch.
369
+ *
370
+ * @param snapshotId The snapshot ID returned by `sb.checkpoint()`.
371
+ * @param name A name for the new sandbox session in the ledger.
372
+ * @param resources CPU and memory for the restored container.
373
+ * @param runId Run-correlation ID for the restored sandbox — see `SandboxDetails.runId`.
374
+ * Defaults to a fresh `crypto.randomUUID()` if omitted.
375
+ *
376
+ * @example
377
+ * ```ts
378
+ * const snapshotId = await sb.checkpoint();
379
+ * await sb.close();
380
+ *
381
+ * // Later — restore and run fresh commands:
382
+ * const sb2 = await client.restoreSnapshot(snapshotId, "my-sandbox", { cpu: "500m", memory: "256Mi" });
383
+ * await sb2.exec("npm test");
384
+ * await sb2.close();
385
+ * ```
386
+ */
387
+ async restoreSnapshot(snapshotId, name, resources, runId) {
388
+ await this._ensureConnected();
389
+ await this._acquireSlot();
390
+ try {
391
+ const finalRunId = runId ?? crypto.randomUUID();
392
+ const newId = (await this._control.createSandbox({
393
+ snapshotId,
394
+ resourceLimits: resources,
395
+ metadata: { runId: finalRunId }
396
+ })).id;
397
+ await this._waitForRunning(newId);
398
+ await this._adapter.append({
399
+ ts: Date.now(),
400
+ name,
401
+ sandboxId: newId,
402
+ stepIndex: -1,
403
+ event: LedgerEvent$1.SandboxCreated,
404
+ payload: {
405
+ sandboxId: newId,
406
+ fromSnapshot: snapshotId,
407
+ runId: finalRunId
408
+ }
409
+ });
410
+ return new Sandbox$1(newId, name, {
411
+ control: this._control,
412
+ adapter: this._adapter,
413
+ onClose: () => this._releaseSlot(),
414
+ fork: (snapshotId, tag, overrideRunId) => this._forkFromSnapshot(snapshotId, name, resources, void 0, overrideRunId ?? finalRunId),
415
+ useServerProxy: this._useServerProxy
416
+ });
417
+ } catch (err) {
418
+ this._releaseSlot();
419
+ throw err;
420
+ }
421
+ }
422
+ /**
423
+ * Sandbox history management. List, inspect, and delete past sandbox records.
424
+ *
425
+ * @example
426
+ * ```ts
427
+ * const all = await client.sandboxes.list();
428
+ * const details = await client.sandboxes.get("ci", sandboxId);
429
+ * await client.sandboxes.delete("ci", sandboxId);
430
+ * ```
431
+ */
432
+ sandboxes = {
433
+ /** List all sandbox records across all names, newest first. */
434
+ list: async (opts) => {
435
+ await this._ensureConnected();
436
+ return this._adapter.listAllSandboxDetails(opts);
437
+ },
438
+ /** List sandbox records for a specific name, newest first. */
439
+ listByName: async (name, opts) => {
440
+ await this._ensureConnected();
441
+ return this._adapter.listSandboxDetails(name, opts);
442
+ },
443
+ /** Return details for a single sandbox record. Returns `null` if not found. */
444
+ get: async (name, sandboxId) => {
445
+ await this._ensureConnected();
446
+ return this._adapter.getSandboxDetails(name, sandboxId);
447
+ },
448
+ /** Delete all ledger events for a sandbox. */
449
+ delete: async (name, sandboxId) => {
450
+ await this._ensureConnected();
451
+ return this._adapter.deleteSandbox(name, sandboxId);
452
+ }
453
+ };
454
+ /**
455
+ * Define a named, reusable sandbox environment.
456
+ *
457
+ * Returns an `Environment` object — no I/O happens here. The first call to
458
+ * `env.sandbox()` builds the environment (runs setup + snapshots), then caches
459
+ * the snapshot ID in the ledger. Subsequent calls restore from that snapshot.
460
+ *
461
+ * @example
462
+ * ```ts
463
+ * const env = client.environment("python", {
464
+ * image: "debian:bookworm-slim",
465
+ * resources: { cpu: "500m", memory: "512Mi" },
466
+ * setup: async (sb) => {
467
+ * await sb.exec("apt-get update -qq && apt-get install -y python3-pip");
468
+ * await sb.exec("pip install numpy pandas");
469
+ * },
470
+ * });
471
+ *
472
+ * const sb = await env.sandbox();
473
+ * try {
474
+ * await sb.exec("python3 -c 'import pandas; print(pandas.__version__)'").pipe(process.stdout);
475
+ * } finally {
476
+ * await sb.close();
477
+ * }
478
+ * ```
479
+ */
480
+ environment(name, opts) {
481
+ return new Environment(name, opts, this);
482
+ }
483
+ /**
484
+ * Environment management. List and delete cached environment records.
485
+ *
486
+ * @example
487
+ * ```ts
488
+ * const envs = await client.environments.list();
489
+ * await client.environments.delete("python");
490
+ * ```
491
+ */
492
+ environments = {
493
+ /** Return all environment records, newest first. */
494
+ list: async () => {
495
+ await this._ensureConnected();
496
+ return this._adapter.listEnvironments();
497
+ },
498
+ /** Remove the ledger record for a named environment. Does not delete the server-side snapshot. */
499
+ delete: async (name) => {
500
+ await this._ensureConnected();
501
+ return this._adapter.deleteEnvironment(name);
502
+ }
503
+ };
504
+ async _envInfo(name) {
505
+ await this._ensureConnected();
506
+ return this._adapter.getEnvironment(name);
507
+ }
508
+ async _envRebuild(name, opts) {
509
+ await this._ensureConnected();
510
+ await this._buildEnvironment(name, opts);
511
+ }
512
+ async _envSandbox(name, opts, extra) {
513
+ await this._ensureConnected();
514
+ const record = await this._adapter.getEnvironment(name);
515
+ if (record) {
516
+ if ((await this._control.getSnapshot(record.snapshotId).catch(() => null))?.state === SnapshotState.Ready) return this._createFromSnapshot(record.snapshotId, opts.resources, name, opts.shell, extra);
517
+ }
518
+ const snapshotId = await this._getOrBuildEnvironment(name, opts);
519
+ return this._createFromSnapshot(snapshotId, opts.resources, name, opts.shell, extra);
520
+ }
521
+ _getOrBuildEnvironment(name, opts) {
522
+ const inflight = this._envBuilds.get(name);
523
+ if (inflight) return inflight;
524
+ const build = this._buildEnvironment(name, opts).finally(() => this._envBuilds.delete(name));
525
+ this._envBuilds.set(name, build);
526
+ return build;
527
+ }
528
+ async _buildEnvironment(name, opts) {
529
+ const image = typeof opts.image === "string" ? opts.image : opts.image.uri;
530
+ const buildName = `env-${name}-build`;
531
+ const sb = await this.sandbox({
532
+ image: opts.image,
533
+ resources: opts.resources,
534
+ name: buildName,
535
+ shell: opts.shell
536
+ });
537
+ try {
538
+ await opts.setup(sb);
539
+ await sb.checkpoint(`env:${name}`);
540
+ } finally {
541
+ await sb.close();
542
+ }
543
+ const checkpoint = await this._adapter.lastCheckpoint(buildName, sb.sandboxId);
544
+ if (!checkpoint) throw new AlineoError(`Environment build for '${name}' produced no checkpoint`, 500);
545
+ const { snapshotId } = checkpoint.payload;
546
+ await this._adapter.saveEnvironment({
547
+ name,
548
+ snapshotId,
549
+ image,
550
+ builtAt: Date.now()
551
+ });
552
+ return snapshotId;
553
+ }
554
+ async _createFromSnapshot(snapshotId, resources, envName, envShell, extra) {
555
+ await this._acquireSlot();
556
+ try {
557
+ const runId = crypto.randomUUID();
558
+ const newId = (await this._control.createSandbox({
559
+ snapshotId,
560
+ resourceLimits: resources,
561
+ env: extra?.env,
562
+ metadata: { runId }
563
+ })).id;
564
+ await this._waitForRunning(newId);
565
+ const sessionName = `env-${envName}-${newId.slice(0, 8)}`;
566
+ await this._adapter.append({
567
+ ts: Date.now(),
568
+ name: sessionName,
569
+ sandboxId: newId,
570
+ stepIndex: -1,
571
+ event: LedgerEvent$1.SandboxCreated,
572
+ payload: {
573
+ sandboxId: newId,
574
+ fromEnvironment: envName,
575
+ snapshotId,
576
+ runId
577
+ }
578
+ });
579
+ const sb = new Sandbox$1(newId, sessionName, {
580
+ control: this._control,
581
+ adapter: this._adapter,
582
+ hooks: extra?.hooks,
583
+ onClose: () => this._releaseSlot(),
584
+ shell: extra?.shell ?? envShell,
585
+ fork: (snapshotId, tag, overrideRunId) => this._forkFromSnapshot(snapshotId, sessionName, resources, extra?.shell ?? envShell, overrideRunId ?? runId),
586
+ useServerProxy: this._useServerProxy
587
+ });
588
+ extra?.hooks?.onSandboxCreated?.(newId, sessionName);
589
+ return sb;
590
+ } catch (err) {
591
+ this._releaseSlot();
592
+ throw err;
593
+ }
594
+ }
595
+ async _forkFromSnapshot(snapshotId, parentName, resources, shell, runId) {
596
+ await this._acquireSlot();
597
+ try {
598
+ const finalRunId = runId ?? crypto.randomUUID();
599
+ const newId = (await this._control.createSandbox({
600
+ snapshotId,
601
+ resourceLimits: resources,
602
+ metadata: { runId: finalRunId }
603
+ })).id;
604
+ await this._waitForRunning(newId);
605
+ const sessionName = `fork-${parentName}-${newId.slice(0, 8)}`;
606
+ await this._adapter.append({
607
+ ts: Date.now(),
608
+ name: sessionName,
609
+ sandboxId: newId,
610
+ stepIndex: -1,
611
+ event: LedgerEvent$1.SandboxCreated,
612
+ payload: {
613
+ sandboxId: newId,
614
+ forkedFrom: snapshotId,
615
+ runId: finalRunId
616
+ }
617
+ });
618
+ return new Sandbox$1(newId, sessionName, {
619
+ control: this._control,
620
+ adapter: this._adapter,
621
+ onClose: () => this._releaseSlot(),
622
+ shell,
623
+ fork: (sid, tag, overrideRunId) => this._forkFromSnapshot(sid, sessionName, resources, shell, overrideRunId ?? finalRunId),
624
+ useServerProxy: this._useServerProxy
625
+ });
626
+ } catch (err) {
627
+ this._releaseSlot();
628
+ throw err;
629
+ }
630
+ }
631
+ async _waitForRunning(sandboxId, timeoutMs = 12e4) {
632
+ const deadline = Date.now() + timeoutMs;
633
+ let delay = 100;
634
+ while (Date.now() < deadline) {
635
+ const s = await this._control.getSandbox(sandboxId);
636
+ if (s.status.state === SandboxState.Running) return;
637
+ if (s.status.state === SandboxState.Failed || s.status.state === SandboxState.Terminated) throw new AlineoError(`Sandbox ${sandboxId} entered state ${s.status.state}: ${s.status.message ?? ""}`, 500);
638
+ await new Promise((r) => setTimeout(r, delay));
639
+ delay = Math.min(delay * 1.5, 1e3);
640
+ }
641
+ throw new AlineoError(`Sandbox ${sandboxId} did not reach Running within ${timeoutMs}ms`, 408);
642
+ }
643
+ async _acquireSlot() {
644
+ if (!this._maxConcurrency || this._activeCount < this._maxConcurrency) {
645
+ this._activeCount++;
646
+ return;
647
+ }
648
+ await new Promise((resolve) => this._waiters.push(resolve));
649
+ this._activeCount++;
650
+ }
651
+ _releaseSlot() {
652
+ this._activeCount--;
653
+ this._waiters.shift()?.();
654
+ }
655
+ };
656
+ //#endregion
657
+ export { Alineo, AlineoError, BashSession, CodeLanguage, CommandError, Environment, ExecConnectionError, LedgerEvent, Sandbox, SandboxError, SandboxStatus, StepTimeoutError };
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "alineo",
3
+ "version": "0.1.0",
4
+ "license": "Apache-2.0",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/DrejT/alineo.git",
8
+ "directory": "packages/sdks/typescript"
9
+ },
10
+ "files": [
11
+ "dist"
12
+ ],
13
+ "type": "module",
14
+ "main": "./src/index.ts",
15
+ "types": "./src/index.ts",
16
+ "exports": {
17
+ ".": {
18
+ "import": "./dist/index.mjs",
19
+ "types": "./src/index.ts"
20
+ }
21
+ },
22
+ "publishConfig": {
23
+ "access": "public",
24
+ "provenance": true
25
+ },
26
+ "scripts": {
27
+ "build": "tsdown",
28
+ "test": "vitest run",
29
+ "test:watch": "vitest"
30
+ },
31
+ "dependencies": {
32
+ "@alineo-labs/core": "0.1.0",
33
+ "@alineo-labs/opensandbox": "0.1.0"
34
+ },
35
+ "devDependencies": {
36
+ "bun-types": "1.3.14",
37
+ "tsdown": "0.22.3",
38
+ "typescript": "6.0.3",
39
+ "vitest": "4.1.9"
40
+ }
41
+ }