@chimp-labs/keel-ai-kit 0.0.0-stage → 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,1000 @@
1
+ import { Context, Duration, Effect, Exit, Layer, Option, Redacted, Schema, Scope, Stream, } from "effect";
2
+ import { randomUUID } from "node:crypto";
3
+ import { KeelBindSym, KeelDefaultLayerSym, KeelEnsureSym, KeelErrorMetaSym, KeelInfraSym, KeelKindSym, KeelMetaSym, ObjectStore, SecretStore, } from "@chimp-labs/keel";
4
+ import { joinPosixPath, normalizePosixPath } from "./internal/posix-path.js";
5
+ // ---------------------------------------------------------------------------
6
+ // Typed Errors
7
+ // ---------------------------------------------------------------------------
8
+ export class SandboxError extends Schema.TaggedError()("SandboxError", {
9
+ sandbox: Schema.String,
10
+ instanceId: Schema.optional(Schema.String),
11
+ cause: Schema.Unknown,
12
+ }) {
13
+ static [KeelErrorMetaSym] = {
14
+ category: "internal",
15
+ httpStatus: 500,
16
+ retryable: true,
17
+ };
18
+ }
19
+ export class SandboxNotFoundError extends Schema.TaggedError()("SandboxNotFoundError", {
20
+ sandbox: Schema.String,
21
+ instanceId: Schema.String,
22
+ }) {
23
+ static [KeelErrorMetaSym] = {
24
+ category: "not_found",
25
+ httpStatus: 404,
26
+ retryable: false,
27
+ };
28
+ }
29
+ export class SandboxTimeoutError extends Schema.TaggedError()("SandboxTimeoutError", {
30
+ sandbox: Schema.String,
31
+ instanceId: Schema.String,
32
+ command: Schema.String,
33
+ timeoutMs: Schema.Number,
34
+ }) {
35
+ static [KeelErrorMetaSym] = {
36
+ category: "timeout",
37
+ httpStatus: 504,
38
+ retryable: true,
39
+ };
40
+ }
41
+ export class SandboxExecError extends Schema.TaggedError()("SandboxExecError", {
42
+ sandbox: Schema.String,
43
+ instanceId: Schema.String,
44
+ command: Schema.String,
45
+ exitCode: Schema.Int,
46
+ stdout: Schema.String,
47
+ stderr: Schema.String,
48
+ }) {
49
+ static [KeelErrorMetaSym] = {
50
+ category: "internal",
51
+ httpStatus: 500,
52
+ retryable: false,
53
+ };
54
+ }
55
+ export class SandboxFileNotFoundError extends Schema.TaggedError()("SandboxFileNotFoundError", {
56
+ sandbox: Schema.String,
57
+ instanceId: Schema.String,
58
+ path: Schema.String,
59
+ }) {
60
+ static [KeelErrorMetaSym] = {
61
+ category: "not_found",
62
+ httpStatus: 404,
63
+ retryable: false,
64
+ };
65
+ }
66
+ export class SandboxUnsupportedCapabilityError extends Schema.TaggedError()("SandboxUnsupportedCapabilityError", {
67
+ sandbox: Schema.String,
68
+ provider: Schema.String,
69
+ requirement: Schema.String,
70
+ message: Schema.String,
71
+ }) {
72
+ static [KeelErrorMetaSym] = {
73
+ category: "invalid",
74
+ httpStatus: 400,
75
+ retryable: false,
76
+ };
77
+ }
78
+ const ISOLATION_RANK = {
79
+ process: 1,
80
+ container: 2,
81
+ gvisor: 3,
82
+ microvm: 4,
83
+ };
84
+ // ---------------------------------------------------------------------------
85
+ // Descriptor Factory: `class CodeSandbox extends Sandbox("code-runner", { ... }) {}`
86
+ // ---------------------------------------------------------------------------
87
+ const defaultSandboxLayer = () => SandboxMemoryLive();
88
+ export const Sandbox = (sandboxName, config) => {
89
+ const workdir = config.workdir ?? "/workspace";
90
+ const timeout = config.timeout ?? "5 minutes";
91
+ const network = config.network ?? "none";
92
+ const allowedDomains = [...(config.allowedDomains ?? [])];
93
+ const env = { ...(config.env ?? {}) };
94
+ const secrets = [...(config.secrets ?? [])];
95
+ const secretNames = secrets.map((s) => s.secretName);
96
+ const requireNativeSnapshot = config.requireNativeSnapshot ?? false;
97
+ const requireMemoryPause = config.requireMemoryPause ?? false;
98
+ const SandboxClass = class {
99
+ static sandboxName = sandboxName;
100
+ static image = config.image;
101
+ static workdir = workdir;
102
+ static timeout = timeout;
103
+ static idleTimeout = config.idleTimeout;
104
+ static cpu = config.cpu;
105
+ static memoryMb = config.memoryMb;
106
+ static network = network;
107
+ static allowedDomains = allowedDomains;
108
+ static isolation = config.isolation;
109
+ static gpu = config.gpu;
110
+ static requireNativeSnapshot = requireNativeSnapshot;
111
+ static requireMemoryPause = requireMemoryPause;
112
+ static env = env;
113
+ static secrets = secrets;
114
+ static snapshotBucket = config.snapshotBucket;
115
+ static [KeelKindSym] = "sandbox";
116
+ static [KeelMetaSym] = {
117
+ kind: "sandbox",
118
+ name: sandboxName,
119
+ image: config.image,
120
+ network,
121
+ ...(config.isolation !== undefined ? { isolation: config.isolation } : {}),
122
+ ...(config.gpu !== undefined ? { gpu: config.gpu } : {}),
123
+ secrets: secretNames,
124
+ ...(config.snapshotBucket !== undefined
125
+ ? { snapshotBucket: config.snapshotBucket.bucketName }
126
+ : {}),
127
+ };
128
+ static [KeelInfraSym] = () => ({
129
+ children: [
130
+ ...secrets,
131
+ ...(config.snapshotBucket !== undefined ? [config.snapshotBucket] : []),
132
+ ],
133
+ });
134
+ static [KeelDefaultLayerSym] = defaultSandboxLayer;
135
+ static [KeelEnsureSym] = () => verifySandboxCapabilities(SandboxClass);
136
+ static [KeelBindSym] = (runner) => bindSandbox(runner, SandboxClass);
137
+ };
138
+ return SandboxClass;
139
+ };
140
+ export class SandboxRuntime extends Context.Service()("@chimp-labs/keel/SandboxRuntime") {
141
+ }
142
+ // ---------------------------------------------------------------------------
143
+ // Capability Validation (Fail-Fast Security & Hardware Enforcement)
144
+ // ---------------------------------------------------------------------------
145
+ export const checkSandboxCapabilitySupport = (sandbox, caps) => {
146
+ if (sandbox.isolation !== undefined &&
147
+ ISOLATION_RANK[caps.maxIsolation] < ISOLATION_RANK[sandbox.isolation]) {
148
+ return new SandboxUnsupportedCapabilityError({
149
+ sandbox: sandbox.sandboxName,
150
+ provider: caps.provider,
151
+ requirement: `isolation:${sandbox.isolation}`,
152
+ message: `Sandbox "${sandbox.sandboxName}" requires at least "${sandbox.isolation}" isolation, but provider "${caps.provider}" only supports up to "${caps.maxIsolation}"`,
153
+ });
154
+ }
155
+ if (sandbox.gpu !== undefined && sandbox.gpu !== false) {
156
+ const gpuOk = caps.gpu === true ||
157
+ (Array.isArray(caps.gpu) &&
158
+ (sandbox.gpu === true
159
+ ? caps.gpu.length > 0
160
+ : caps.gpu.includes(sandbox.gpu)));
161
+ if (!gpuOk) {
162
+ return new SandboxUnsupportedCapabilityError({
163
+ sandbox: sandbox.sandboxName,
164
+ provider: caps.provider,
165
+ requirement: `gpu:${String(sandbox.gpu)}`,
166
+ message: `Sandbox "${sandbox.sandboxName}" requires GPU (${String(sandbox.gpu)}), which is not supported by provider "${caps.provider}"`,
167
+ });
168
+ }
169
+ }
170
+ if (sandbox.network === "restricted" && !caps.egressFirewall) {
171
+ return new SandboxUnsupportedCapabilityError({
172
+ sandbox: sandbox.sandboxName,
173
+ provider: caps.provider,
174
+ requirement: "egressFirewall",
175
+ message: `Sandbox "${sandbox.sandboxName}" declares network="restricted" with allowedDomains, but provider "${caps.provider}" does not support an egress firewall`,
176
+ });
177
+ }
178
+ if (sandbox.requireNativeSnapshot && !caps.nativeSnapshot) {
179
+ return new SandboxUnsupportedCapabilityError({
180
+ sandbox: sandbox.sandboxName,
181
+ provider: caps.provider,
182
+ requirement: "nativeSnapshot",
183
+ message: `Sandbox "${sandbox.sandboxName}" requires nativeSnapshot, which is not supported by provider "${caps.provider}"`,
184
+ });
185
+ }
186
+ if (sandbox.requireMemoryPause && !caps.memoryPause) {
187
+ return new SandboxUnsupportedCapabilityError({
188
+ sandbox: sandbox.sandboxName,
189
+ provider: caps.provider,
190
+ requirement: "memoryPause",
191
+ message: `Sandbox "${sandbox.sandboxName}" requires memoryPause, which is not supported by provider "${caps.provider}"`,
192
+ });
193
+ }
194
+ return undefined;
195
+ };
196
+ /**
197
+ * Verifies that the active `SandboxRuntime` satisfies all isolation, GPU,
198
+ * network firewall, snapshot, and pause requirements declared on `sandbox`.
199
+ * Fails fast with `SandboxUnsupportedCapabilityError`.
200
+ */
201
+ export const verifySandboxCapabilities = (sandbox) => Effect.gen(function* () {
202
+ const runtime = yield* SandboxRuntime;
203
+ const caps = runtime.capabilitiesFor(sandbox.sandboxName);
204
+ const err = checkSandboxCapabilitySupport(sandbox, caps);
205
+ if (err)
206
+ return yield* err;
207
+ return caps;
208
+ });
209
+ const toMillis = (input) => Math.max(1, Math.floor(Duration.toMillis(Duration.fromInputUnsafe(input))));
210
+ const resolveCreateRequest = (sandbox, options) => Effect.gen(function* () {
211
+ const mergedEnv = {
212
+ ...sandbox.env,
213
+ ...(options?.env ?? {}),
214
+ };
215
+ if (sandbox.secrets.length > 0) {
216
+ const storeOpt = yield* Effect.serviceOption(SecretStore);
217
+ if (Option.isSome(storeOpt)) {
218
+ const store = storeOpt.value;
219
+ for (const sec of sandbox.secrets) {
220
+ const val = yield* store.get(sec.secretName);
221
+ mergedEnv[sec.secretName] = Redacted.value(val);
222
+ }
223
+ }
224
+ }
225
+ return {
226
+ sandboxName: sandbox.sandboxName,
227
+ image: sandbox.image,
228
+ workdir: sandbox.workdir,
229
+ timeoutMs: toMillis(options?.timeout ?? sandbox.timeout),
230
+ ...(options?.idleTimeout !== undefined || sandbox.idleTimeout !== undefined
231
+ ? {
232
+ idleTimeoutMs: toMillis(options?.idleTimeout ?? sandbox.idleTimeout),
233
+ }
234
+ : {}),
235
+ ...(sandbox.cpu !== undefined ? { cpu: sandbox.cpu } : {}),
236
+ ...(sandbox.memoryMb !== undefined ? { memoryMb: sandbox.memoryMb } : {}),
237
+ network: sandbox.network,
238
+ allowedDomains: sandbox.allowedDomains,
239
+ ...(sandbox.isolation !== undefined ? { isolation: sandbox.isolation } : {}),
240
+ ...(sandbox.gpu !== undefined ? { gpu: sandbox.gpu } : {}),
241
+ env: mergedEnv,
242
+ ...(options?.metadata !== undefined ? { metadata: options.metadata } : {}),
243
+ };
244
+ });
245
+ /**
246
+ * Acquires a scoped sandbox instance backed by the active `SandboxRuntime`.
247
+ * Automatically verifies capabilities, resolves declared `secrets`, and
248
+ * destroys the sandbox when the enclosing `Scope` closes.
249
+ */
250
+ export const acquireSandbox = (sandbox, options) => Effect.gen(function* () {
251
+ const runtime = yield* SandboxRuntime;
252
+ yield* verifySandboxCapabilities(sandbox);
253
+ const req = yield* resolveCreateRequest(sandbox, options);
254
+ return yield* Effect.acquireRelease(runtime.create(req), (handle) => runtime.destroy(handle).pipe(Effect.ignore));
255
+ });
256
+ /**
257
+ * Runs `fn` inside a freshly created sandbox that is guaranteed to be
258
+ * destroyed when `fn` completes, fails, or is interrupted.
259
+ */
260
+ export const withSandbox = (sandbox, fn, options) => Effect.scoped(Effect.flatMap(acquireSandbox(sandbox, options), (handle) => fn(handle)));
261
+ export const sandboxExec = (handle, command, options) => Effect.flatMap(SandboxRuntime, (rt) => rt.exec(handle, command, options));
262
+ export const sandboxExecOrFail = (handle, command, options) => Effect.gen(function* () {
263
+ const res = yield* sandboxExec(handle, command, options);
264
+ if (res.exitCode !== 0) {
265
+ return yield* new SandboxExecError({
266
+ sandbox: handle.sandboxName,
267
+ instanceId: handle.id,
268
+ command: typeof command === "string" ? command : command.join(" "),
269
+ exitCode: res.exitCode,
270
+ stdout: res.stdout,
271
+ stderr: res.stderr,
272
+ });
273
+ }
274
+ return res;
275
+ });
276
+ export const sandboxExecStream = (handle, command, options) => Stream.unwrap(Effect.map(SandboxRuntime, (rt) => rt.execStream(handle, command, options)));
277
+ export const sandboxReadFile = (handle, path) => Effect.flatMap(SandboxRuntime, (rt) => rt.readFile(handle, path));
278
+ export const sandboxReadText = (handle, path) => sandboxReadFile(handle, path).pipe(Effect.map((bytes) => new TextDecoder().decode(bytes)));
279
+ export const sandboxWriteFile = (handle, path, content) => Effect.flatMap(SandboxRuntime, (rt) => rt.writeFile(handle, path, content));
280
+ export const sandboxListFiles = (handle, dirPath) => Effect.flatMap(SandboxRuntime, (rt) => rt.listFiles(handle, dirPath));
281
+ // ---------------------------------------------------------------------------
282
+ // Portable Bucket Sync (Works on Every Sandbox Provider via `ObjectStore`)
283
+ // ---------------------------------------------------------------------------
284
+ const collectStreamBytes = (stream) => Effect.gen(function* () {
285
+ const chunks = yield* Stream.runCollect(stream);
286
+ const total = chunks.reduce((acc, c) => acc + c.byteLength, 0);
287
+ const out = new Uint8Array(total);
288
+ let offset = 0;
289
+ for (const c of chunks) {
290
+ out.set(c, offset);
291
+ offset += c.byteLength;
292
+ }
293
+ return out;
294
+ });
295
+ /**
296
+ * Copies objects from a Keel `Bucket` (`ObjectStore`) into a sandbox directory.
297
+ * Portable across every sandbox backend with zero provider-specific code.
298
+ */
299
+ export const syncBucketToSandbox = (bucket, handle, options) => Effect.gen(function* () {
300
+ const store = yield* ObjectStore;
301
+ const runtime = yield* SandboxRuntime;
302
+ const prefix = options?.prefix ?? "";
303
+ const targetDir = options?.targetDir ?? handle.workdir;
304
+ const entries = yield* store
305
+ .list(bucket.bucketName, prefix ? { prefix } : undefined)
306
+ .pipe(Stream.runCollect);
307
+ let filesCopied = 0;
308
+ let bytesCopied = 0;
309
+ for (const entry of entries) {
310
+ const rel = prefix && entry.key.startsWith(prefix)
311
+ ? entry.key.slice(prefix.length)
312
+ : entry.key;
313
+ const cleanRel = rel.replace(/^\/+/, "");
314
+ if (!cleanRel)
315
+ continue;
316
+ const obj = yield* store.get(bucket.bucketName, entry.key);
317
+ const bytes = yield* collectStreamBytes(obj.body);
318
+ yield* runtime.writeFile(handle, joinPosixPath(targetDir, cleanRel), bytes);
319
+ filesCopied++;
320
+ bytesCopied += bytes.byteLength;
321
+ }
322
+ return { filesCopied, bytesCopied };
323
+ });
324
+ /**
325
+ * Recursively copies files from a sandbox directory into a Keel `Bucket` (`ObjectStore`).
326
+ * Portable across every sandbox backend with zero provider-specific code.
327
+ */
328
+ export const syncSandboxToBucket = (handle, bucket, options) => Effect.gen(function* () {
329
+ const store = yield* ObjectStore;
330
+ const runtime = yield* SandboxRuntime;
331
+ const sourceDir = normalizePosixPath(options?.sourceDir ?? handle.workdir);
332
+ const rawPrefix = options?.prefix ?? "";
333
+ const prefix = rawPrefix && !rawPrefix.endsWith("/") ? `${rawPrefix}/` : rawPrefix;
334
+ const contentType = options?.contentType ??
335
+ bucket.contentTypes[0] ??
336
+ "application/octet-stream";
337
+ const entries = yield* runtime.listFiles(handle, sourceDir);
338
+ let filesCopied = 0;
339
+ let bytesCopied = 0;
340
+ for (const entry of entries) {
341
+ if (entry.isDirectory)
342
+ continue;
343
+ const normPath = normalizePosixPath(entry.path);
344
+ const rel = normPath.startsWith(`${sourceDir}/`)
345
+ ? normPath.slice(sourceDir.length + 1)
346
+ : normPath.replace(/^\/+/, "");
347
+ if (!rel)
348
+ continue;
349
+ const bytes = yield* runtime.readFile(handle, normPath);
350
+ yield* store.put(bucket.bucketName, `${prefix}${rel}`, bytes, {
351
+ contentType,
352
+ metadata: {},
353
+ maxBytes: bucket.maxBytes,
354
+ });
355
+ filesCopied++;
356
+ bytesCopied += bytes.byteLength;
357
+ }
358
+ return { filesCopied, bytesCopied };
359
+ });
360
+ // ---------------------------------------------------------------------------
361
+ // Portable Snapshot / Restore & Pause / Resume (Native or Bucket Fallback!)
362
+ // ---------------------------------------------------------------------------
363
+ const BUCKET_SNAPSHOT_PREFIX = "keel-bucket:";
364
+ const parseBucketSnapshotId = (snapshotId) => {
365
+ if (!snapshotId.startsWith(BUCKET_SNAPSHOT_PREFIX))
366
+ return undefined;
367
+ const rest = snapshotId.slice(BUCKET_SNAPSHOT_PREFIX.length);
368
+ const idx = rest.indexOf(":");
369
+ if (idx <= 0)
370
+ return undefined;
371
+ return {
372
+ bucket: rest.slice(0, idx),
373
+ key: rest.slice(idx + 1),
374
+ };
375
+ };
376
+ /**
377
+ * Snapshots a sandbox filesystem.
378
+ * - Uses provider-native `snapshot()` when `capabilities.nativeSnapshot === true`.
379
+ * - Otherwise transparently archives the sandbox `workdir` into `options.bucket`
380
+ * or `sandbox.snapshotBucket` via `ObjectStore`, returning a portable
381
+ * `keel-bucket:<bucket>:<key>` snapshot ID.
382
+ */
383
+ export const snapshotSandbox = (sandbox, handle, options) => Effect.gen(function* () {
384
+ const runtime = yield* SandboxRuntime;
385
+ const caps = runtime.capabilitiesFor(sandbox.sandboxName);
386
+ if (caps.nativeSnapshot && runtime.snapshot) {
387
+ return yield* runtime.snapshot(handle);
388
+ }
389
+ const fallbackBucket = options?.bucket ?? sandbox.snapshotBucket;
390
+ if (!fallbackBucket) {
391
+ return yield* new SandboxUnsupportedCapabilityError({
392
+ sandbox: sandbox.sandboxName,
393
+ provider: caps.provider,
394
+ requirement: "nativeSnapshot",
395
+ message: `Provider "${caps.provider}" does not support nativeSnapshot and no snapshotBucket was configured on sandbox "${sandbox.sandboxName}"`,
396
+ });
397
+ }
398
+ const storeOpt = yield* Effect.serviceOption(ObjectStore);
399
+ if (Option.isNone(storeOpt)) {
400
+ return yield* new SandboxError({
401
+ sandbox: sandbox.sandboxName,
402
+ instanceId: handle.id,
403
+ cause: new Error(`ObjectStore is required for portable Bucket snapshot fallback on sandbox "${sandbox.sandboxName}"`),
404
+ });
405
+ }
406
+ const sourceDir = normalizePosixPath(options?.sourceDir ?? handle.workdir);
407
+ const entries = yield* runtime.listFiles(handle, sourceDir);
408
+ const files = [];
409
+ for (const entry of entries) {
410
+ if (entry.isDirectory)
411
+ continue;
412
+ const bytes = yield* runtime.readFile(handle, entry.path);
413
+ files.push({
414
+ path: normalizePosixPath(entry.path),
415
+ contentBase64: Buffer.from(bytes).toString("base64"),
416
+ });
417
+ }
418
+ const archive = {
419
+ version: 1,
420
+ sandboxName: sandbox.sandboxName,
421
+ workdir: handle.workdir,
422
+ createdAt: new Date().toISOString(),
423
+ files,
424
+ };
425
+ const payload = new TextEncoder().encode(JSON.stringify(archive));
426
+ const key = `_keel_snapshots/${sandbox.sandboxName}/${randomUUID()}.json`;
427
+ yield* storeOpt.value.put(fallbackBucket.bucketName, key, payload, {
428
+ contentType: "application/json",
429
+ metadata: { sandbox: sandbox.sandboxName },
430
+ maxBytes: Math.max(fallbackBucket.maxBytes, payload.byteLength),
431
+ });
432
+ return `${BUCKET_SNAPSHOT_PREFIX}${fallbackBucket.bucketName}:${key}`;
433
+ });
434
+ /**
435
+ * Restores a sandbox from either a provider-native snapshot ID or a portable
436
+ * `keel-bucket:<bucket>:<key>` archive created by `snapshotSandbox`.
437
+ */
438
+ export const restoreSandbox = (sandbox, snapshotId, options) => Effect.gen(function* () {
439
+ const runtime = yield* SandboxRuntime;
440
+ yield* verifySandboxCapabilities(sandbox);
441
+ const req = yield* resolveCreateRequest(sandbox, options);
442
+ const bucketRef = parseBucketSnapshotId(snapshotId);
443
+ if (!bucketRef) {
444
+ const caps = runtime.capabilitiesFor(sandbox.sandboxName);
445
+ if (!caps.nativeSnapshot || !runtime.restore) {
446
+ return yield* new SandboxUnsupportedCapabilityError({
447
+ sandbox: sandbox.sandboxName,
448
+ provider: caps.provider,
449
+ requirement: "nativeSnapshot",
450
+ message: `Provider "${caps.provider}" does not support native snapshot restore`,
451
+ });
452
+ }
453
+ return yield* Effect.acquireRelease(runtime.restore(req, snapshotId), (handle) => runtime.destroy(handle).pipe(Effect.ignore));
454
+ }
455
+ const storeOpt = yield* Effect.serviceOption(ObjectStore);
456
+ if (Option.isNone(storeOpt)) {
457
+ return yield* new SandboxError({
458
+ sandbox: sandbox.sandboxName,
459
+ cause: new Error(`ObjectStore is required to restore portable snapshot "${snapshotId}"`),
460
+ });
461
+ }
462
+ const rawObj = yield* storeOpt.value.get(bucketRef.bucket, bucketRef.key);
463
+ const bytes = yield* collectStreamBytes(rawObj.body);
464
+ const archive = JSON.parse(new TextDecoder().decode(bytes));
465
+ const handle = yield* Effect.acquireRelease(runtime.create(req), (h) => runtime.destroy(h).pipe(Effect.ignore));
466
+ for (const file of archive.files) {
467
+ yield* runtime.writeFile(handle, file.path, new Uint8Array(Buffer.from(file.contentBase64, "base64")));
468
+ }
469
+ return handle;
470
+ });
471
+ /**
472
+ * Pauses a running sandbox: uses provider-native RAM+disk `pause()` when
473
+ * supported, otherwise falls back to `snapshotSandbox()` + `destroy()` using
474
+ * `snapshotBucket` (unless `requireMemoryPause: true` was declared).
475
+ */
476
+ export const pauseSandbox = (sandbox, handle, options) => Effect.gen(function* () {
477
+ const runtime = yield* SandboxRuntime;
478
+ const caps = runtime.capabilitiesFor(sandbox.sandboxName);
479
+ if (caps.memoryPause && runtime.pause) {
480
+ return yield* runtime.pause(handle);
481
+ }
482
+ if (sandbox.requireMemoryPause) {
483
+ return yield* new SandboxUnsupportedCapabilityError({
484
+ sandbox: sandbox.sandboxName,
485
+ provider: caps.provider,
486
+ requirement: "memoryPause",
487
+ message: `Provider "${caps.provider}" does not support memoryPause`,
488
+ });
489
+ }
490
+ const snapId = yield* snapshotSandbox(sandbox, handle, options);
491
+ yield* runtime.destroy(handle);
492
+ return snapId;
493
+ });
494
+ /**
495
+ * Resumes a previously paused sandbox (either provider-native memory checkpoint
496
+ * or portable filesystem snapshot).
497
+ */
498
+ export const resumeSandbox = (sandbox, checkpointId, options) => Effect.gen(function* () {
499
+ const runtime = yield* SandboxRuntime;
500
+ const caps = runtime.capabilitiesFor(sandbox.sandboxName);
501
+ if (!parseBucketSnapshotId(checkpointId) &&
502
+ caps.memoryPause &&
503
+ runtime.resume) {
504
+ yield* verifySandboxCapabilities(sandbox);
505
+ const req = yield* resolveCreateRequest(sandbox, options);
506
+ return yield* Effect.acquireRelease(runtime.resume(req, checkpointId), (h) => runtime.destroy(h).pipe(Effect.ignore));
507
+ }
508
+ return yield* restoreSandbox(sandbox, checkpointId, options);
509
+ });
510
+ /**
511
+ * Routes different `Sandbox` descriptors to different `SandboxRuntime` backends
512
+ * within the same application (e.g. Docker/gVisor default + Modal for GPUs +
513
+ * Vercel Firecracker for hostile code).
514
+ */
515
+ export const SandboxRouterLive = (config) => Layer.effect(SandboxRuntime, Effect.gen(function* () {
516
+ const scope = yield* Effect.scope;
517
+ const defaultCtx = yield* Layer.buildWithScope(config.default, scope);
518
+ const defaultRt = Context.get(defaultCtx, SandboxRuntime);
519
+ const byNameMap = new Map();
520
+ for (const [name, layer] of Object.entries(config.byName ?? {})) {
521
+ const ctx = yield* Layer.buildWithScope(layer, scope);
522
+ byNameMap.set(name, Context.get(ctx, SandboxRuntime));
523
+ }
524
+ const instanceRoutes = new Map();
525
+ const snapshotRoutes = new Map();
526
+ const resolveForName = (name) => byNameMap.get(name) ?? defaultRt;
527
+ const resolveForHandle = (handle) => instanceRoutes.get(handle.id) ?? resolveForName(handle.sandboxName);
528
+ return SandboxRuntime.of({
529
+ capabilitiesFor: (sandboxName) => resolveForName(sandboxName).capabilitiesFor(sandboxName),
530
+ create: (request) => Effect.gen(function* () {
531
+ const rt = resolveForName(request.sandboxName);
532
+ const handle = yield* rt.create(request);
533
+ instanceRoutes.set(handle.id, rt);
534
+ return handle;
535
+ }),
536
+ exec: (handle, command, options) => resolveForHandle(handle).exec(handle, command, options),
537
+ execStream: (handle, command, options) => resolveForHandle(handle).execStream(handle, command, options),
538
+ readFile: (handle, path) => resolveForHandle(handle).readFile(handle, path),
539
+ writeFile: (handle, path, content) => resolveForHandle(handle).writeFile(handle, path, content),
540
+ listFiles: (handle, dirPath) => resolveForHandle(handle).listFiles(handle, dirPath),
541
+ destroy: (handle) => resolveForHandle(handle)
542
+ .destroy(handle)
543
+ .pipe(Effect.tap(() => Effect.sync(() => {
544
+ instanceRoutes.delete(handle.id);
545
+ }))),
546
+ snapshot: (handle) => Effect.gen(function* () {
547
+ const rt = resolveForHandle(handle);
548
+ if (!rt.snapshot) {
549
+ return yield* new SandboxError({
550
+ sandbox: handle.sandboxName,
551
+ instanceId: handle.id,
552
+ cause: new Error(`Routed provider "${handle.provider}" does not support native snapshot`),
553
+ });
554
+ }
555
+ const snapId = yield* rt.snapshot(handle);
556
+ snapshotRoutes.set(snapId, rt);
557
+ return snapId;
558
+ }),
559
+ restore: (request, snapshotId) => Effect.gen(function* () {
560
+ const rt = snapshotRoutes.get(snapshotId) ??
561
+ resolveForName(request.sandboxName);
562
+ if (!rt.restore) {
563
+ return yield* new SandboxUnsupportedCapabilityError({
564
+ sandbox: request.sandboxName,
565
+ provider: rt.capabilitiesFor(request.sandboxName).provider,
566
+ requirement: "nativeSnapshot",
567
+ message: `Routed provider does not support native snapshot restore`,
568
+ });
569
+ }
570
+ const handle = yield* rt.restore(request, snapshotId);
571
+ instanceRoutes.set(handle.id, rt);
572
+ return handle;
573
+ }),
574
+ pause: (handle) => Effect.gen(function* () {
575
+ const rt = resolveForHandle(handle);
576
+ if (!rt.pause) {
577
+ return yield* new SandboxError({
578
+ sandbox: handle.sandboxName,
579
+ instanceId: handle.id,
580
+ cause: new Error(`Routed provider "${handle.provider}" does not support native pause`),
581
+ });
582
+ }
583
+ const cpId = yield* rt.pause(handle);
584
+ snapshotRoutes.set(cpId, rt);
585
+ instanceRoutes.delete(handle.id);
586
+ return cpId;
587
+ }),
588
+ resume: (request, checkpointId) => Effect.gen(function* () {
589
+ const rt = snapshotRoutes.get(checkpointId) ??
590
+ resolveForName(request.sandboxName);
591
+ if (!rt.resume) {
592
+ return yield* new SandboxUnsupportedCapabilityError({
593
+ sandbox: request.sandboxName,
594
+ provider: rt.capabilitiesFor(request.sandboxName).provider,
595
+ requirement: "memoryPause",
596
+ message: `Routed provider does not support native memory resume`,
597
+ });
598
+ }
599
+ const handle = yield* rt.resume(request, checkpointId);
600
+ instanceRoutes.set(handle.id, rt);
601
+ return handle;
602
+ }),
603
+ });
604
+ }));
605
+ const defaultMemoryExec = (ctx) => {
606
+ const start = Date.now();
607
+ const rawCmd = ctx.command.trim();
608
+ // Unwrap simple `sh -c "..."` / `bash -c "..."`
609
+ let effective = rawCmd;
610
+ if ((ctx.args[0] === "sh" || ctx.args[0] === "bash") &&
611
+ ctx.args[1] === "-c" &&
612
+ ctx.args[2] !== undefined) {
613
+ effective = ctx.args[2].trim();
614
+ }
615
+ const parts = effective.split(/\s+/).filter(Boolean);
616
+ const bin = parts[0] ?? "";
617
+ if (bin === "echo") {
618
+ const rest = effective.slice(effective.indexOf("echo") + 4).trim();
619
+ const unquoted = (rest.startsWith('"') && rest.endsWith('"')) ||
620
+ (rest.startsWith("'") && rest.endsWith("'"))
621
+ ? rest.slice(1, -1)
622
+ : rest;
623
+ const expanded = unquoted.replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g, (_, k) => ctx.env[k] ?? "");
624
+ return {
625
+ exitCode: 0,
626
+ stdout: `${expanded}\n`,
627
+ stderr: "",
628
+ durationMs: Math.max(0, Date.now() - start),
629
+ };
630
+ }
631
+ if (bin === "pwd") {
632
+ return {
633
+ exitCode: 0,
634
+ stdout: `${ctx.cwd}\n`,
635
+ stderr: "",
636
+ durationMs: Math.max(0, Date.now() - start),
637
+ };
638
+ }
639
+ if (bin === "env") {
640
+ const lines = Object.entries(ctx.env)
641
+ .sort(([a], [b]) => a.localeCompare(b))
642
+ .map(([k, v]) => `${k}=${v}`)
643
+ .join("\n");
644
+ return {
645
+ exitCode: 0,
646
+ stdout: lines ? `${lines}\n` : "",
647
+ stderr: "",
648
+ durationMs: Math.max(0, Date.now() - start),
649
+ };
650
+ }
651
+ if (bin === "cat" && parts[1]) {
652
+ const target = joinPosixPath(ctx.cwd, parts[1]);
653
+ const data = ctx.files.get(target);
654
+ if (!data) {
655
+ return {
656
+ exitCode: 1,
657
+ stdout: "",
658
+ stderr: `cat: ${parts[1]}: No such file or directory\n`,
659
+ durationMs: Math.max(0, Date.now() - start),
660
+ };
661
+ }
662
+ return {
663
+ exitCode: 0,
664
+ stdout: new TextDecoder().decode(data),
665
+ stderr: "",
666
+ durationMs: Math.max(0, Date.now() - start),
667
+ };
668
+ }
669
+ if (bin === "ls") {
670
+ const dir = normalizePosixPath(parts[1] ? joinPosixPath(ctx.cwd, parts[1]) : ctx.cwd);
671
+ const prefix = dir === "/" ? "/" : `${dir}/`;
672
+ const names = [...ctx.files.keys()]
673
+ .filter((k) => k.startsWith(prefix))
674
+ .map((k) => k.slice(prefix.length))
675
+ .sort();
676
+ return {
677
+ exitCode: 0,
678
+ stdout: names.length > 0 ? `${names.join("\n")}\n` : "",
679
+ stderr: "",
680
+ durationMs: Math.max(0, Date.now() - start),
681
+ };
682
+ }
683
+ if (bin === "rm" && parts[1]) {
684
+ const target = joinPosixPath(ctx.cwd, parts[parts.length - 1]);
685
+ ctx.files.delete(target);
686
+ return {
687
+ exitCode: 0,
688
+ stdout: "",
689
+ stderr: "",
690
+ durationMs: Math.max(0, Date.now() - start),
691
+ };
692
+ }
693
+ if (bin === "true") {
694
+ return { exitCode: 0, stdout: "", stderr: "", durationMs: 0 };
695
+ }
696
+ if (bin === "false") {
697
+ return { exitCode: 1, stdout: "", stderr: "", durationMs: 0 };
698
+ }
699
+ return {
700
+ exitCode: 0,
701
+ stdout: "",
702
+ stderr: "",
703
+ durationMs: Math.max(0, Date.now() - start),
704
+ };
705
+ };
706
+ /**
707
+ * Zero-dependency in-memory `SandboxRuntime` for fast (<10ms) deterministic
708
+ * unit tests and local prototyping.
709
+ */
710
+ export const SandboxMemoryLive = (options) => {
711
+ const caps = {
712
+ provider: options?.capabilities?.provider ?? "memory",
713
+ maxIsolation: options?.capabilities?.maxIsolation ?? "microvm",
714
+ nativeSnapshot: options?.capabilities?.nativeSnapshot ?? true,
715
+ memoryPause: options?.capabilities?.memoryPause ?? true,
716
+ gpu: options?.capabilities?.gpu ?? true,
717
+ egressFirewall: options?.capabilities?.egressFirewall ?? true,
718
+ streamingExec: options?.capabilities?.streamingExec ?? true,
719
+ };
720
+ const instances = new Map();
721
+ const snapshots = new Map();
722
+ const getInstance = (handle) => {
723
+ const inst = instances.get(handle.id);
724
+ if (!inst) {
725
+ return Effect.fail(new SandboxNotFoundError({
726
+ sandbox: handle.sandboxName,
727
+ instanceId: handle.id,
728
+ }));
729
+ }
730
+ return Effect.succeed(inst);
731
+ };
732
+ const execEffect = (handle, command, execOpts) => Effect.gen(function* () {
733
+ const inst = yield* getInstance(handle);
734
+ const args = typeof command === "string" ? [command] : [...command];
735
+ const cmdStr = typeof command === "string" ? command : command.join(" ");
736
+ const cwd = normalizePosixPath(execOpts?.cwd ?? handle.workdir);
737
+ const env = {
738
+ ...inst.env,
739
+ ...(execOpts?.env ?? {}),
740
+ };
741
+ const ctx = {
742
+ handle,
743
+ command: cmdStr,
744
+ args,
745
+ cwd,
746
+ env,
747
+ files: inst.files,
748
+ };
749
+ if (!options?.execHandler) {
750
+ return defaultMemoryExec(ctx);
751
+ }
752
+ const raw = options.execHandler(ctx);
753
+ if (Effect.isEffect(raw)) {
754
+ return yield* raw;
755
+ }
756
+ if (raw instanceof Promise) {
757
+ return yield* Effect.tryPromise({
758
+ try: () => raw,
759
+ catch: (cause) => new SandboxError({
760
+ sandbox: handle.sandboxName,
761
+ instanceId: handle.id,
762
+ cause,
763
+ }),
764
+ });
765
+ }
766
+ return raw;
767
+ });
768
+ return Layer.succeed(SandboxRuntime, SandboxRuntime.of({
769
+ capabilitiesFor: () => caps,
770
+ create: (request) => Effect.sync(() => {
771
+ const id = `mem_sb_${randomUUID().slice(0, 12)}`;
772
+ const files = new Map();
773
+ for (const [p, content] of Object.entries(options?.initialFiles ?? {})) {
774
+ files.set(joinPosixPath(request.workdir, p), typeof content === "string"
775
+ ? new TextEncoder().encode(content)
776
+ : new Uint8Array(content));
777
+ }
778
+ const handle = {
779
+ id,
780
+ sandboxName: request.sandboxName,
781
+ provider: caps.provider,
782
+ workdir: normalizePosixPath(request.workdir),
783
+ };
784
+ instances.set(id, {
785
+ handle,
786
+ env: { ...request.env },
787
+ files,
788
+ });
789
+ return handle;
790
+ }),
791
+ exec: execEffect,
792
+ execStream: (handle, command, execOpts) => Stream.unwrap(execEffect(handle, command, execOpts).pipe(Effect.map((res) => {
793
+ const chunks = [];
794
+ if (res.stdout.length > 0) {
795
+ chunks.push({ stream: "stdout", data: res.stdout });
796
+ }
797
+ if (res.stderr.length > 0) {
798
+ chunks.push({ stream: "stderr", data: res.stderr });
799
+ }
800
+ return Stream.fromIterable(chunks);
801
+ }))),
802
+ readFile: (handle, path) => Effect.gen(function* () {
803
+ const inst = yield* getInstance(handle);
804
+ const full = joinPosixPath(handle.workdir, path);
805
+ const hit = inst.files.get(full);
806
+ if (!hit) {
807
+ return yield* new SandboxFileNotFoundError({
808
+ sandbox: handle.sandboxName,
809
+ instanceId: handle.id,
810
+ path: full,
811
+ });
812
+ }
813
+ return new Uint8Array(hit);
814
+ }),
815
+ writeFile: (handle, path, content) => Effect.gen(function* () {
816
+ const inst = yield* getInstance(handle);
817
+ const full = joinPosixPath(handle.workdir, path);
818
+ const bytes = typeof content === "string"
819
+ ? new TextEncoder().encode(content)
820
+ : new Uint8Array(content);
821
+ inst.files.set(full, bytes);
822
+ }),
823
+ listFiles: (handle, dirPath) => Effect.gen(function* () {
824
+ const inst = yield* getInstance(handle);
825
+ const base = normalizePosixPath(dirPath ?? handle.workdir);
826
+ const prefix = base === "/" ? "/" : `${base}/`;
827
+ const out = [];
828
+ for (const [p, bytes] of inst.files.entries()) {
829
+ if (p === base || p.startsWith(prefix)) {
830
+ out.push({
831
+ path: p,
832
+ isDirectory: false,
833
+ size: bytes.byteLength,
834
+ });
835
+ }
836
+ }
837
+ out.sort((a, b) => a.path.localeCompare(b.path));
838
+ return out;
839
+ }),
840
+ destroy: (handle) => Effect.sync(() => {
841
+ instances.delete(handle.id);
842
+ }),
843
+ snapshot: (handle) => Effect.gen(function* () {
844
+ const inst = yield* getInstance(handle);
845
+ const snapId = `mem_snap_${randomUUID().slice(0, 12)}`;
846
+ const clonedFiles = new Map();
847
+ for (const [k, v] of inst.files.entries()) {
848
+ clonedFiles.set(k, new Uint8Array(v));
849
+ }
850
+ snapshots.set(snapId, { files: clonedFiles, env: { ...inst.env } });
851
+ return snapId;
852
+ }),
853
+ restore: (request, snapshotId) => Effect.gen(function* () {
854
+ const snap = snapshots.get(snapshotId);
855
+ if (!snap) {
856
+ return yield* new SandboxNotFoundError({
857
+ sandbox: request.sandboxName,
858
+ instanceId: snapshotId,
859
+ });
860
+ }
861
+ const id = `mem_sb_${randomUUID().slice(0, 12)}`;
862
+ const clonedFiles = new Map();
863
+ for (const [k, v] of snap.files.entries()) {
864
+ clonedFiles.set(k, new Uint8Array(v));
865
+ }
866
+ const handle = {
867
+ id,
868
+ sandboxName: request.sandboxName,
869
+ provider: caps.provider,
870
+ workdir: normalizePosixPath(request.workdir),
871
+ };
872
+ instances.set(id, {
873
+ handle,
874
+ env: { ...snap.env, ...request.env },
875
+ files: clonedFiles,
876
+ });
877
+ return handle;
878
+ }),
879
+ pause: (handle) => Effect.gen(function* () {
880
+ const inst = yield* getInstance(handle);
881
+ const cpId = `mem_cp_${randomUUID().slice(0, 12)}`;
882
+ const clonedFiles = new Map();
883
+ for (const [k, v] of inst.files.entries()) {
884
+ clonedFiles.set(k, new Uint8Array(v));
885
+ }
886
+ snapshots.set(cpId, { files: clonedFiles, env: { ...inst.env } });
887
+ instances.delete(handle.id);
888
+ return cpId;
889
+ }),
890
+ resume: (request, checkpointId) => Effect.gen(function* () {
891
+ const snap = snapshots.get(checkpointId);
892
+ if (!snap) {
893
+ return yield* new SandboxNotFoundError({
894
+ sandbox: request.sandboxName,
895
+ instanceId: checkpointId,
896
+ });
897
+ }
898
+ const id = `mem_sb_${randomUUID().slice(0, 12)}`;
899
+ const clonedFiles = new Map();
900
+ for (const [k, v] of snap.files.entries()) {
901
+ clonedFiles.set(k, new Uint8Array(v));
902
+ }
903
+ const handle = {
904
+ id,
905
+ sandboxName: request.sandboxName,
906
+ provider: caps.provider,
907
+ workdir: normalizePosixPath(request.workdir),
908
+ };
909
+ instances.set(id, {
910
+ handle,
911
+ env: { ...snap.env, ...request.env },
912
+ files: clonedFiles,
913
+ });
914
+ return handle;
915
+ }),
916
+ }));
917
+ };
918
+ const makeSandboxSession = (runner, sandboxDef, handle, scope) => {
919
+ let closed = false;
920
+ const destroy = async () => {
921
+ if (closed)
922
+ return;
923
+ closed = true;
924
+ await runner.run(Scope.close(scope, Exit.void));
925
+ };
926
+ return {
927
+ handle,
928
+ id: handle.id,
929
+ sandboxName: handle.sandboxName,
930
+ provider: handle.provider,
931
+ workdir: handle.workdir,
932
+ exec: (command, options) => runner.run(sandboxExec(handle, command, options), options),
933
+ execOrFail: (command, options) => runner.run(sandboxExecOrFail(handle, command, options), options),
934
+ execStream: (command, options) => runner.stream(sandboxExecStream(handle, command, options), options),
935
+ readFile: (path, options) => runner.run(sandboxReadFile(handle, path), options),
936
+ readText: (path, options) => runner.run(sandboxReadText(handle, path), options),
937
+ writeFile: (path, content, options) => runner.run(sandboxWriteFile(handle, path, content), options),
938
+ listFiles: (dirPath, options) => runner.run(sandboxListFiles(handle, dirPath), options),
939
+ syncFromBucket: (bucket, options) => runner.run(syncBucketToSandbox(bucket, handle, options), options),
940
+ syncToBucket: (bucket, options) => runner.run(syncSandboxToBucket(handle, bucket, options), options),
941
+ snapshot: (options) => runner.run(snapshotSandbox(sandboxDef, handle, options), options),
942
+ pause: async (options) => {
943
+ const cpId = await runner.run(pauseSandbox(sandboxDef, handle, options), options);
944
+ await destroy();
945
+ return cpId;
946
+ },
947
+ destroy,
948
+ [Symbol.asyncDispose]: destroy,
949
+ };
950
+ };
951
+ export const bindSandbox = (runner, sandboxDef) => ({
952
+ descriptor: sandboxDef,
953
+ capabilities: (options) => runner.run(Effect.map(SandboxRuntime, (rt) => rt.capabilitiesFor(sandboxDef.sandboxName)), options),
954
+ verifyCapabilities: (options) => runner.run(verifySandboxCapabilities(sandboxDef), options),
955
+ open: async (options) => {
956
+ const scope = await runner.run(Scope.make(), options);
957
+ try {
958
+ const handle = await runner.run(acquireSandbox(sandboxDef, options).pipe(Scope.provide(scope)), options);
959
+ return makeSandboxSession(runner, sandboxDef, handle, scope);
960
+ }
961
+ catch (err) {
962
+ await runner.run(Scope.close(scope, Exit.void)).catch(() => undefined);
963
+ throw err;
964
+ }
965
+ },
966
+ withSandbox: async (fn, options) => {
967
+ const session = await bindSandbox(runner, sandboxDef).open(options);
968
+ try {
969
+ return await fn(session);
970
+ }
971
+ finally {
972
+ await session.destroy();
973
+ }
974
+ },
975
+ restore: async (snapshotId, options) => {
976
+ const scope = await runner.run(Scope.make(), options);
977
+ try {
978
+ const handle = await runner.run(restoreSandbox(sandboxDef, snapshotId, options).pipe(Scope.provide(scope)), options);
979
+ return makeSandboxSession(runner, sandboxDef, handle, scope);
980
+ }
981
+ catch (err) {
982
+ await runner.run(Scope.close(scope, Exit.void)).catch(() => undefined);
983
+ throw err;
984
+ }
985
+ },
986
+ resume: async (checkpointId, options) => {
987
+ const scope = await runner.run(Scope.make(), options);
988
+ try {
989
+ const handle = await runner.run(resumeSandbox(sandboxDef, checkpointId, options).pipe(Scope.provide(scope)), options);
990
+ return makeSandboxSession(runner, sandboxDef, handle, scope);
991
+ }
992
+ catch (err) {
993
+ await runner.run(Scope.close(scope, Exit.void)).catch(() => undefined);
994
+ throw err;
995
+ }
996
+ },
997
+ });
998
+ /** Plain TypeScript SDK descriptor builder for `Sandbox`. */
999
+ export const sandbox = (sandboxName, config) => Sandbox(sandboxName, config);
1000
+ //# sourceMappingURL=sandbox.js.map