@ai-hero/sandcastle 0.14.0 → 0.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{SandboxProvider-Chsi-Zs6.d.ts → SandboxProvider-CwRLxIXZ.d.ts} +2 -39
- package/dist/{chunk-BVZWLFFT.js → chunk-4BB7DNPW.js} +3 -3
- package/dist/chunk-4BB7DNPW.js.map +1 -0
- package/dist/chunk-4GZMUHVO.js +60 -0
- package/dist/chunk-4GZMUHVO.js.map +1 -0
- package/dist/{chunk-S6UHPTRG.js → chunk-7JUTKCHL.js} +4 -4
- package/dist/{chunk-S6UHPTRG.js.map → chunk-7JUTKCHL.js.map} +1 -1
- package/dist/chunk-7PHPLDVS.js +284 -0
- package/dist/chunk-7PHPLDVS.js.map +1 -0
- package/dist/{chunk-HSXPRZKG.js → chunk-BXLS4HRY.js} +15 -6
- package/dist/chunk-BXLS4HRY.js.map +1 -0
- package/dist/{chunk-G2R53CVZ.js → chunk-EM4QNWKF.js} +695 -706
- package/dist/chunk-EM4QNWKF.js.map +1 -0
- package/dist/{chunk-STB2U7BB.js → chunk-JEQ4IVQM.js} +384 -264
- package/dist/chunk-JEQ4IVQM.js.map +1 -0
- package/dist/{chunk-VRXR2T3S.js → chunk-L3BU47F6.js} +3 -3
- package/dist/{chunk-VRXR2T3S.js.map → chunk-L3BU47F6.js.map} +1 -1
- package/dist/{chunk-7N7AMUYA.js → chunk-PTJEKJPQ.js} +7 -5
- package/dist/chunk-PTJEKJPQ.js.map +1 -0
- package/dist/{chunk-H2PEFS4W.js → chunk-SAQXFLO2.js} +30 -6
- package/dist/chunk-SAQXFLO2.js.map +1 -0
- package/dist/{chunk-ATA2V2TC.js → chunk-TBVRAXYF.js} +3 -3
- package/dist/{chunk-ATA2V2TC.js.map → chunk-TBVRAXYF.js.map} +1 -1
- package/dist/{chunk-IBK2XNSS.js → chunk-VUOXFCWO.js} +3 -3
- package/dist/{chunk-IBK2XNSS.js.map → chunk-VUOXFCWO.js.map} +1 -1
- package/dist/{chunk-GCLEXPXG.js → chunk-WYOGXC72.js} +46 -84
- package/dist/chunk-WYOGXC72.js.map +1 -0
- package/dist/{chunk-RDW7FNN6.js → chunk-YDQW5IOY.js} +11 -4
- package/dist/chunk-YDQW5IOY.js.map +1 -0
- package/dist/index.d.ts +47 -4
- package/dist/index.js +536 -445
- package/dist/index.js.map +1 -1
- package/dist/main.js +72 -16
- package/dist/main.js.map +1 -1
- package/dist/sandboxes/bwrap.d.ts +1 -1
- package/dist/sandboxes/bwrap.js +9 -17
- package/dist/sandboxes/bwrap.js.map +1 -1
- package/dist/sandboxes/daytona.d.ts +1 -1
- package/dist/sandboxes/daytona.js +82 -79
- package/dist/sandboxes/daytona.js.map +1 -1
- package/dist/sandboxes/docker.d.ts +23 -1
- package/dist/sandboxes/docker.js +6 -5
- package/dist/sandboxes/e2b.d.ts +1 -1
- package/dist/sandboxes/e2b.js +4 -4
- package/dist/sandboxes/modal.d.ts +1 -1
- package/dist/sandboxes/modal.js +1 -1
- package/dist/sandboxes/no-sandbox.d.ts +1 -1
- package/dist/sandboxes/no-sandbox.js +1 -1
- package/dist/sandboxes/podman.d.ts +27 -4
- package/dist/sandboxes/podman.js +18 -45
- package/dist/sandboxes/podman.js.map +1 -1
- package/dist/sandboxes/seatbelt.d.ts +2 -2
- package/dist/sandboxes/seatbelt.js +10 -10
- package/dist/sandboxes/seatbelt.js.map +1 -1
- package/dist/sandboxes/sprites.d.ts +1 -1
- package/dist/sandboxes/sprites.js +25 -4
- package/dist/sandboxes/sprites.js.map +1 -1
- package/dist/sandboxes/vercel.d.ts +10 -1
- package/dist/sandboxes/vercel.js +74 -46
- package/dist/sandboxes/vercel.js.map +1 -1
- package/dist/templates/parallel-planner/main.mts +43 -21
- package/dist/templates/parallel-planner-with-review/main.mts +55 -27
- package/dist/templates/sequential-reviewer/main.mts +1 -1
- package/package.json +7 -3
- package/dist/chunk-7N7AMUYA.js.map +0 -1
- package/dist/chunk-BIF2X6QB.js +0 -94
- package/dist/chunk-BIF2X6QB.js.map +0 -1
- package/dist/chunk-BVZWLFFT.js.map +0 -1
- package/dist/chunk-G2R53CVZ.js.map +0 -1
- package/dist/chunk-GCLEXPXG.js.map +0 -1
- package/dist/chunk-H2PEFS4W.js.map +0 -1
- package/dist/chunk-HSXPRZKG.js.map +0 -1
- package/dist/chunk-RDW7FNN6.js.map +0 -1
- package/dist/chunk-STB2U7BB.js.map +0 -1
package/dist/sandboxes/bwrap.js
CHANGED
|
@@ -1,18 +1,17 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';
|
|
2
|
-
import { resolveIdentityMounts, copyCreatingParents, collectOutput, hostPathToolchainFromEnv } from '../chunk-
|
|
3
|
-
import { markNativeSandboxProvider } from '../chunk-
|
|
4
|
-
import { assertBwrapUsable } from '../chunk-
|
|
5
|
-
import { NodeFileSystem_exports } from '../chunk-
|
|
6
|
-
import '../chunk-
|
|
7
|
-
import
|
|
8
|
-
import { FileSystem_exports, BwrapError } from '../chunk-
|
|
9
|
-
import { Effect_exports, Option_exports } from '../chunk-
|
|
10
|
-
import { createBindMountSandboxProvider } from '../chunk-
|
|
2
|
+
import { resolveIdentityMounts, registerNativeSandboxShutdown, copyCreatingParents, collectOutput, hostPathToolchainFromEnv } from '../chunk-BXLS4HRY.js';
|
|
3
|
+
import { markNativeSandboxProvider } from '../chunk-L3BU47F6.js';
|
|
4
|
+
import { assertBwrapUsable } from '../chunk-TBVRAXYF.js';
|
|
5
|
+
import { NodeFileSystem_exports } from '../chunk-7JUTKCHL.js';
|
|
6
|
+
import '../chunk-7PHPLDVS.js';
|
|
7
|
+
import '../chunk-EXYXBRCX.js';
|
|
8
|
+
import { FileSystem_exports, BwrapError } from '../chunk-YDQW5IOY.js';
|
|
9
|
+
import { Effect_exports, Option_exports } from '../chunk-JEQ4IVQM.js';
|
|
10
|
+
import { createBindMountSandboxProvider } from '../chunk-4BB7DNPW.js';
|
|
11
11
|
import { MAX_TAIL_CHARS } from '../chunk-6NQPCXSG.js';
|
|
12
12
|
import { spawn } from 'child_process';
|
|
13
13
|
import { once } from 'events';
|
|
14
14
|
import { join, posix } from 'path';
|
|
15
|
-
import { rmSync } from 'fs';
|
|
16
15
|
|
|
17
16
|
createRequire(import.meta.url);
|
|
18
17
|
|
|
@@ -186,13 +185,6 @@ var toHostPath = (path, dirs, mounts) => {
|
|
|
186
185
|
}
|
|
187
186
|
return p;
|
|
188
187
|
};
|
|
189
|
-
var registerNativeSandboxShutdown = (killAll, dirs) => registerShutdown(() => {
|
|
190
|
-
killAll();
|
|
191
|
-
try {
|
|
192
|
-
rmSync(dirs.root, { recursive: true, force: true });
|
|
193
|
-
} catch {
|
|
194
|
-
}
|
|
195
|
-
});
|
|
196
188
|
|
|
197
189
|
// src/sandboxes/bwrap.ts
|
|
198
190
|
var trackSandboxProcess = (proc) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/bwrapProcess.ts","../../src/bwrapSandbox.ts","../../src/nativeSandboxShutdown.ts","../../src/sandboxes/bwrap.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAQO,IAAM,OAAA,GAAU,CAAA;AAqBhB,IAAM,QAAA,GAAW,CAAA;AAcjB,IAAM,cAAA,GAAiB,CAAC,OAAA,KAA8B;AAAA,EAC3D,IAAA;AAAA,EACA,IAAA;AAAA,EACA,qCAAqC,QAAQ,CAAA;AAAA,KAAA,EACxC,QAAQ,CAAA;AAAA,eAAA,CAAA;AAAA,EAEb,IAAA;AAAA,EACA;AACF,CAAA;AAEA,IAAM,SAAA,GAAY,gCAAA;AAGX,IAAM,aAAA,GAAgB,CAAC,IAAA,KAAqC;AACjE,EAAA,MAAM,MAAM,SAAA,CAAU,IAAA,CAAK,IAAI,CAAA,EAAG,SAAS,KAAK,CAAA;AAChD,EAAA,OAAO,GAAA,KAAQ,MAAA,GAAY,MAAA,GAAY,MAAA,CAAO,GAAG,CAAA;AACnD,CAAA;AAGO,IA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IAAM,KAAA,GAAQ,CAAC,OAAA,KAAqD;AAGzE,EAAA,MAAM,UAAA,GAAa,WAAA,CAAY,OAAA,EAAS,MAAA,IAAU,EAAE,CAAA;AACpD,EAAA,iBAAA,EAAkB;AAClB,EAAA,MAAM,YAAA,GAAe,SAAS,kBAAA,IAAsB,cAAA;AACpD,EAAA,OAAO,yBAAA;AAAA,IACL,8BAAA,CAA+B;AAAA,MAC7B,IAAA,EAAM,OAAA;AAAA,MACN,GAAA,EAAK,OAAA,EAAS,GAAA,IAAO,EAAC;AAAA,MACtB,cAAA,EAAgB,YAAA;AAAA,MAChB,MAAA,EAAQ,OAAO,aAAA,KACb,YAAA,CAAa,eAAe,EAAE,YAAA,EAAc,YAAY;AAAA,KAC3D;AAAA,GACH;AACF","file":"bwrap.js","sourcesContent":["/**\n * The processes behind one `bwrap()` exec, and how to kill all of them. Used\n * only by `bwrap()`, through src/bwrapSandbox.ts.\n */\n\nimport type { ChildProcess } from \"node:child_process\";\n\n/** The fd bwrap reports the sandbox's PID 1 on (`--info-fd`). */\nexport const INFO_FD = 3;\n\n/**\n * One exec's bwrap. `proc` is the outer bwrap; `sandboxPid` is the host PID\n * of the sandbox's PID 1, once bwrap has reported it on {@link INFO_FD}.\n * Killing only the outer bwrap leaves the sandbox running: its PID 1 has its\n * own session and outlives its parent. Killing PID 1 ends every process in\n * the sandbox's PID namespace.\n */\nexport interface SandboxProcess {\n readonly proc: ChildProcess;\n sandboxPid: number | undefined;\n /** Settles once bwrap has reported the PID, or closed its info fd without one. */\n readonly reported: Promise<void>;\n}\n\n/**\n * The fd each sandbox's watcher reads (see {@link watchedCommand}). Its\n * other end is held only by this Node process, so it reads end-of-file\n * exactly when this process dies, however it dies.\n */\nexport const WATCH_FD = 4;\n\n/**\n * Runs `command` in the sandbox under a watcher: a background shell blocked\n * on {@link WATCH_FD}, which SIGKILLs every process in the sandbox's PID\n * namespace (`kill -1` spares only PID 1, which then exits) once this Node\n * process dies.\n *\n * `--die-with-parent` alone isn't enough: bwrap arms it in the sandbox's PID 1\n * only once setup is done, so a host process SIGKILLed during an exec's first\n * milliseconds leaves the sandbox running. The watcher starts after setup and\n * sees the end-of-file even if the host died first. The command itself runs\n * without the watcher's fd.\n */\nexport const watchedCommand = (command: string): string[] => [\n \"sh\",\n \"-c\",\n `{ read -r _ || :; kill -9 -1; } <&${WATCH_FD} >/dev/null 2>&1 &\nexec ${WATCH_FD}<&-\nexec sh -c \"$1\"`,\n \"sh\",\n command,\n];\n\nconst CHILD_PID = /\"child-pid\"\\s*:\\s*(?<pid>\\d+)/u;\n\n/** The `child-pid` in bwrap's `--info-fd` JSON, if it has one. */\nexport const parseChildPid = (info: string): number | undefined => {\n const pid = CHILD_PID.exec(info)?.groups?.[\"pid\"];\n return pid === undefined ? undefined : Number(pid);\n};\n\n/** SIGKILLs the sandbox's PID 1, if reported, and the outer bwrap. Synchronous, for shutdown. */\nexport const killSandboxProcess = (sandbox: SandboxProcess): void => {\n if (sandbox.sandboxPid !== undefined) {\n try {\n process.kill(sandbox.sandboxPid, \"SIGKILL\");\n } catch {\n // Already gone.\n }\n }\n sandbox.proc.kill(\"SIGKILL\");\n};\n","/**\n * The pieces of the `bwrap()` provider (src/sandboxes/bwrap.ts) that don't\n * run processes: the Bubblewrap arguments for a sandbox, its private dirs,\n * and the in-sandbox to host path mapping. Used only by `bwrap()`.\n */\n\nimport { join, posix } from \"node:path\";\nimport { FileSystem } from \"@effect/platform\";\nimport { Effect, Option } from \"effect\";\nimport type { BindMountCreateOptions } from \"./SandboxProvider.js\";\nimport { hostPathToolchainFromEnv } from \"./hostPathToolchain.js\";\nimport type { HostPathToolchain } from \"./hostPathToolchain.js\";\nimport { resolveIdentityMounts } from \"./identityMounts.js\";\nimport type { IdentityMount, MountConfig } from \"./identityMounts.js\";\nimport { BwrapError } from \"./errors.js\";\n\n/** The construction check, from its own module (it runs a process, synchronously). */\nexport { assertBwrapUsable } from \"./bwrapPreflight.js\";\nexport type { IdentityMount, MountConfig } from \"./identityMounts.js\";\n/** Tracking and killing each exec's processes, from their own module. */\nexport {\n INFO_FD,\n WATCH_FD,\n killSandboxProcess,\n parseChildPid,\n watchedCommand,\n} from \"./bwrapProcess.js\";\nexport type { SandboxProcess } from \"./bwrapProcess.js\";\n/** Output collection and file copies, shared by the native sandbox providers. */\nexport { collectOutput, copyCreatingParents } from \"./nativeSandboxIo.js\";\n\n/** The private home's path inside the sandbox. */\nexport const SANDBOX_HOME = \"/home/agent\";\nconst SANDBOX_TMP = \"/tmp\";\n\n/** Host dirs every sandbox sees read-only: the system toolchain. */\nconst SYSTEM_DIRS = [\n \"/usr\",\n \"/etc\",\n \"/bin\",\n \"/sbin\",\n \"/lib\",\n \"/lib32\",\n \"/lib64\",\n \"/libx32\",\n \"/opt\",\n];\n\n/**\n * Host dirs that stay hidden even when the host PATH names them: WSL2's\n * Windows drives and interop, so a planted `.exe` can't run.\n */\nconst DENIED_ROOTS = [\"/mnt\", \"/run/WSL\"];\nconst FALLBACK_PATH = \"/usr/local/bin:/usr/bin:/bin\";\n\nconst isWithin = (path: string, root: string): boolean =>\n path === root || path.startsWith(`${root}/`);\n\n/** `--ro-bind` each system dir, or recreate it as a symlink (merged-/usr layouts). */\nconst systemDirArgs: Effect.Effect<string[], never, FileSystem.FileSystem> =\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const args = yield* Effect.all(\n SYSTEM_DIRS.map((dir) =>\n Effect.gen(function* () {\n const link = yield* Effect.option(fs.readLink(dir));\n if (Option.isSome(link)) {\n return [\"--symlink\", link.value, dir];\n }\n const exists = yield* fs\n .exists(dir)\n .pipe(Effect.orElseSucceed(() => false));\n return exists ? [\"--ro-bind\", dir, dir] : [];\n }),\n ),\n );\n return args.flat();\n });\n\n/**\n * `/etc/resolv.conf` may point outside the system dirs (WSL2 links it into\n * `/mnt/wsl`). Mount just that file, read-only, so DNS works.\n */\nconst resolvConfArgs: Effect.Effect<string[], never, FileSystem.FileSystem> =\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const target = yield* Effect.option(fs.realPath(\"/etc/resolv.conf\"));\n return Option.isNone(target) ||\n SYSTEM_DIRS.some((d) => isWithin(target.value, d))\n ? []\n : [\"--ro-bind\", target.value, target.value];\n });\n\n/** Every mount at its host path, in order, so read-only overlays land on their writable parents. */\nconst mountArgs = (\n mounts: readonly { readonly hostPath: string; readonly readonly?: boolean }[],\n): string[] =>\n mounts.flatMap((m) => [\n m.readonly === true ? \"--ro-bind\" : \"--bind\",\n m.hostPath,\n m.hostPath,\n ]);\n\n/**\n * Each dir between a read-only overlay and the writable mount that holds it,\n * bound onto itself, each chain shallowest first. A mount point can't be renamed or\n * removed, so the overlay can't be moved aside by moving a parent (the git\n * worktree admin dir that holds `commondir`, say).\n */\nconst anchorArgs = (\n mounts: readonly { readonly hostPath: string; readonly readonly?: boolean }[],\n): string[] => {\n const writable = mounts.filter((m) => m.readonly !== true);\n const anchors = new Set<string>();\n for (const overlay of mounts.filter((m) => m.readonly === true)) {\n const roots = writable.filter((m) =>\n isWithin(overlay.hostPath, m.hostPath),\n );\n const chain: string[] = [];\n let dir = posix.dirname(overlay.hostPath);\n while (roots.some((m) => dir !== m.hostPath && isWithin(dir, m.hostPath))) {\n chain.unshift(dir);\n dir = posix.dirname(dir);\n }\n for (const anchor of chain) {\n anchors.add(anchor);\n }\n }\n return [...anchors].flatMap((anchor) => [\"--bind\", anchor, anchor]);\n};\n\n/**\n * Checks `bwrap()`'s `mounts` option: each mount, after resolution, must sit\n * at its own host path. Throws at construction otherwise.\n */\nexport const bwrapMounts = (mounts: readonly MountConfig[]): IdentityMount[] =>\n resolveIdentityMounts(\"bwrap\", mounts, SANDBOX_HOME);\n\n/** The host PATH toolchain: each readable dir `--ro-bind`, each symlinked PATH dir recreated. */\nconst toolchainArgs = (toolchain: HostPathToolchain): string[] => [\n ...toolchain.readableDirs.flatMap((dir) => [\"--ro-bind\", dir, dir]),\n ...toolchain.symlinks.flatMap((link) => [\n \"--symlink\",\n link.target,\n link.path,\n ]),\n];\n\nconst envArgs = (env: Record<string, string>): string[] =>\n Object.entries(env).flatMap(([key, value]) => [\"--setenv\", key, value]);\n\n/** The host dirs behind a sandbox's private home and `/tmp`. */\nexport interface PrivateDirs {\n readonly root: string;\n readonly home: string;\n readonly tmp: string;\n}\n\n/** Creates a sandbox's private dirs under the host temp dir. */\nexport const makePrivateDirs: Effect.Effect<\n PrivateDirs,\n BwrapError,\n FileSystem.FileSystem\n> = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const root = yield* fs.makeTempDirectory({ prefix: \"sandcastle-bwrap-\" });\n const dirs = { root, home: join(root, \"home\"), tmp: join(root, \"tmp\") };\n yield* fs.makeDirectory(dirs.home);\n yield* fs.makeDirectory(dirs.tmp);\n return dirs;\n}).pipe(\n Effect.mapError(\n (e) =>\n new BwrapError({\n message: `Couldn't create the bwrap() sandbox's private dirs: ${e.message}`,\n }),\n ),\n);\n\n/** Removes a sandbox's private dirs. */\nexport const removePrivateDirs = (\n dirs: PrivateDirs,\n): Effect.Effect<void, never, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n yield* fs\n .remove(dirs.root, { recursive: true })\n .pipe(Effect.orElse(() => Effect.void));\n });\n\n/** The bwrap arguments shared by every exec of one sandbox, up to `--chdir`. */\nexport const sandboxArgs = (\n options: BindMountCreateOptions,\n dirs: PrivateDirs,\n userMounts: readonly IdentityMount[],\n): Effect.Effect<string[], never, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const toolchain = yield* hostPathToolchainFromEnv({\n coveredRoots: SYSTEM_DIRS,\n deniedRoots: DENIED_ROOTS,\n });\n return [\n ...(yield* systemDirArgs),\n ...(yield* resolvConfArgs),\n \"--proc\",\n \"/proc\",\n \"--dev\",\n \"/dev\",\n \"--tmpfs\",\n \"/home\",\n \"--bind\",\n dirs.home,\n SANDBOX_HOME,\n \"--bind\",\n dirs.tmp,\n SANDBOX_TMP,\n ...toolchainArgs(toolchain),\n ...mountArgs(options.mounts),\n ...mountArgs(userMounts),\n ...anchorArgs(options.mounts),\n // The read-only core mounts (the #1261 overlays) again, so no user\n // mount can uncover them.\n ...mountArgs(options.mounts.filter((m) => m.readonly === true)),\n \"--clearenv\",\n ...envArgs({\n ...options.env,\n PATH:\n toolchain.pathEntries.length > 0\n ? toolchain.pathEntries.join(\":\")\n : FALLBACK_PATH,\n HOME: SANDBOX_HOME,\n TMPDIR: SANDBOX_TMP,\n }),\n \"--unshare-all\",\n \"--share-net\",\n \"--die-with-parent\",\n \"--new-session\",\n ];\n });\n\n/**\n * Maps an in-sandbox path to the host file behind it. Mounts sit at their\n * host paths; the private home and `/tmp` are the private dirs.\n */\nexport const toHostPath = (\n path: string,\n dirs: PrivateDirs,\n mounts: BindMountCreateOptions[\"mounts\"],\n): string => {\n const p = posix.normalize(path);\n if (mounts.some((m) => isWithin(p, m.hostPath))) {\n return p;\n }\n if (isWithin(p, SANDBOX_HOME)) {\n return join(dirs.home, posix.relative(SANDBOX_HOME, p));\n }\n if (isWithin(p, SANDBOX_TMP)) {\n return join(dirs.tmp, posix.relative(SANDBOX_TMP, p));\n }\n return p;\n};\n","/**\n * A native sandbox's shutdown teardown (src/shutdownRegistry.ts). On\n * SIGINT/SIGTERM nothing calls `close()`, and the registry exits as soon as\n * its teardowns return, so the private dirs are removed synchronously: async\n * removal would never finish.\n */\n\n/* oxlint-disable node/no-sync -- a shutdown teardown is synchronous (allowlisted in scripts/lint-ratchet-config.ts). */\n\nimport { rmSync } from \"node:fs\";\nimport { registerShutdown } from \"./shutdownRegistry.js\";\n\n/**\n * Registers the teardown that runs if the process is interrupted or exits\n * before the sandbox is closed: `killAll`, then removing the private dirs\n * under `dirs.root`, best-effort.\n *\n * @returns An idempotent function that unregisters the teardown.\n */\nexport const registerNativeSandboxShutdown = (\n killAll: () => void,\n dirs: { readonly root: string },\n): (() => void) =>\n registerShutdown(() => {\n killAll();\n try {\n rmSync(dirs.root, { recursive: true, force: true });\n } catch {\n // Best-effort: the process is exiting either way.\n }\n });\n","/**\n * Bubblewrap sandbox provider — a native sandbox provider for Linux and WSL2.\n *\n * Usage:\n * import { bwrap } from \"@ai-hero/sandcastle/sandboxes/bwrap\";\n * await run({ agent: claudeCode(\"claude-opus-4-8\"), sandbox: bwrap() });\n *\n * Each `exec` runs in a fresh Bubblewrap sandbox: the host's system dirs\n * read-only, the worktree and git dirs at their host paths, a private home at\n * `/home/agent` and a private `/tmp`, its own PID namespace, the host network,\n * and only the env vars Sandcastle passes in. No image, no daemon.\n */\n\nimport { spawn } from \"node:child_process\";\nimport type { ChildProcess } from \"node:child_process\";\nimport { once } from \"node:events\";\nimport type { FileSystem } from \"@effect/platform\";\nimport { NodeFileSystem } from \"@effect/platform-node\";\nimport { Effect } from \"effect\";\nimport {\n INFO_FD,\n SANDBOX_HOME,\n assertBwrapUsable,\n collectOutput,\n copyCreatingParents,\n bwrapMounts,\n killSandboxProcess,\n makePrivateDirs,\n removePrivateDirs,\n sandboxArgs,\n parseChildPid,\n toHostPath,\n watchedCommand,\n} from \"../bwrapSandbox.js\";\nimport type {\n IdentityMount,\n MountConfig,\n PrivateDirs,\n SandboxProcess,\n} from \"../bwrapSandbox.js\";\nimport { createBindMountSandboxProvider } from \"../SandboxProvider.js\";\nimport type {\n BindMountCreateOptions,\n BindMountSandboxHandle,\n BindMountSandboxProvider,\n ExecResult,\n} from \"../SandboxProvider.js\";\nimport { MAX_TAIL_CHARS } from \"../boundedTail.js\";\nimport { markNativeSandboxProvider } from \"../nativeSandboxProvider.js\";\nimport { registerNativeSandboxShutdown } from \"../nativeSandboxShutdown.js\";\n\n/** Options for {@link bwrap}. */\nexport interface BwrapOptions {\n /** Environment variables injected by this provider. Merged at launch time. */\n readonly env?: Record<string, string>;\n /**\n * Maximum number of characters of streamed `exec` output retained per stream\n * (stdout and stderr) when an `onLine` callback is supplied (default: 64KiB).\n *\n * Output is delivered live to `onLine` regardless; this only bounds the tail\n * returned in `ExecResult`, preventing a long-running agent's output from\n * overflowing V8's max string length and crashing the run.\n */\n readonly maxOutputTailChars?: number;\n /**\n * Extra host paths to make visible in the sandbox (a cache, a sibling\n * checkout, `.beads/`). Each appears at its own host path, so after\n * resolution `sandboxPath` must equal `hostPath`; `bwrap()` throws\n * otherwise. `readonly` defaults to `false`.\n */\n readonly mounts?: readonly MountConfig[];\n}\n\n/** Tracks the sandbox PID bwrap reports on the child's {@link INFO_FD} pipe. */\nconst trackSandboxProcess = (proc: ChildProcess): SandboxProcess => {\n const info = proc.stdio[INFO_FD];\n const tracked: { -readonly [K in keyof SandboxProcess]: SandboxProcess[K] } =\n { proc, sandboxPid: undefined, reported: Promise.resolve() };\n if (info !== null && info !== undefined) {\n let text = \"\";\n info.on(\"data\", (chunk: Buffer) => {\n text += chunk.toString();\n });\n const record = async (): Promise<void> => {\n await once(info, \"close\").catch(() => undefined);\n tracked.sandboxPid = parseChildPid(text);\n };\n tracked.reported = record();\n }\n return tracked;\n};\n\ntype ExecOptions = Parameters<BindMountSandboxHandle[\"exec\"]>[1];\n\n/** Runs `sh -c command` in a fresh bwrap and resolves when it exits. */\nconst runInBwrap = async (\n args: readonly string[],\n opts: ExecOptions,\n sandbox: { live: Set<SandboxProcess>; maxTailChars: number },\n): Promise<ExecResult> => {\n const { live, maxTailChars } = sandbox;\n const proc = spawn(\"bwrap\", [\"--info-fd\", String(INFO_FD), ...args], {\n // fd 3 is INFO_FD; fd 4 is the watcher's WATCH_FD, which is never\n // written and ends only when this process does.\n stdio: [\"pipe\", \"pipe\", \"pipe\", \"pipe\", \"pipe\"],\n });\n const tracked = trackSandboxProcess(proc);\n live.add(tracked);\n const output = collectOutput(proc, opts?.onLine, maxTailChars);\n proc.stdin.on(\"error\", () => undefined);\n proc.stdin.end(opts?.stdin ?? \"\");\n try {\n await once(proc, \"close\");\n return { ...output(), exitCode: proc.exitCode ?? 1 };\n } finally {\n live.delete(tracked);\n }\n};\n\n/** Runs a file-system Effect on the host's file system. */\nconst runOnHost = async <A, E>(\n effect: Effect.Effect<A, E, FileSystem.FileSystem>,\n): Promise<A> =>\n effect.pipe(Effect.provide(NodeFileSystem.layer), Effect.runPromise);\n\n/** Creates the sandbox's private dirs and the bwrap arguments every exec shares. */\nconst prepare = async (\n options: BindMountCreateOptions,\n userMounts: readonly IdentityMount[],\n): Promise<{ dirs: PrivateDirs; baseArgs: string[] }> =>\n Effect.gen(function* () {\n const dirs = yield* makePrivateDirs;\n const baseArgs = yield* sandboxArgs(options, dirs, userMounts);\n return { dirs, baseArgs };\n }).pipe(runOnHost);\n\nconst createHandle = async (\n options: BindMountCreateOptions,\n config: { maxTailChars: number; userMounts: readonly IdentityMount[] },\n): Promise<BindMountSandboxHandle> => {\n const { maxTailChars, userMounts } = config;\n const { dirs, baseArgs } = await prepare(options, userMounts);\n const live = new Set<SandboxProcess>();\n const killAll = (): void => {\n for (const sandbox of live) {\n killSandboxProcess(sandbox);\n }\n };\n const unregisterShutdown = registerNativeSandboxShutdown(killAll, dirs);\n let closed = false;\n const hostPathOf = (p: string): string => toHostPath(p, dirs, options.mounts);\n\n return {\n worktreePath: options.worktreePath,\n exec: async (command, opts) => {\n if (opts?.sudo === true) {\n throw new Error(\n \"bwrap() has no root: exec with sudo: true isn't supported in a native sandbox. \" +\n \"Use docker() for setup that needs root.\",\n );\n }\n if (closed) {\n throw new Error(\"bwrap() sandbox is closed\");\n }\n const cwd = opts?.cwd ?? options.worktreePath;\n const args = [...baseArgs, \"--chdir\", cwd, ...watchedCommand(command)];\n return runInBwrap(args, opts, { live, maxTailChars });\n },\n copyFileIn: async (hostPath, sandboxFile) =>\n copyCreatingParents(hostPath, hostPathOf(sandboxFile)).pipe(runOnHost),\n copyFileOut: async (sandboxFile, hostPath) =>\n copyCreatingParents(hostPathOf(sandboxFile), hostPath).pipe(runOnHost),\n close: async () => {\n closed = true;\n const running = [...live];\n const exits = running.map(async ({ proc }) => once(proc, \"close\"));\n // Wait for each sandbox's PID 1, so a just-started exec is killed too.\n await Promise.all(running.map(async ({ reported }) => reported));\n killAll();\n await Promise.allSettled(exits);\n unregisterShutdown();\n await removePrivateDirs(dirs).pipe(runOnHost);\n },\n };\n};\n\n/**\n * Create a Bubblewrap sandbox provider (Linux and WSL2).\n *\n * The agent runs the host's own toolchain, read-only, and can write only the\n * worktree, the git dirs Sandcastle mounts, a private `/tmp` and a private\n * home at `/home/agent`. Both private dirs are removed on close, and so is\n * every process the sandbox started. The toolchain comes from the host\n * `PATH`: each `PATH` dir (never the home dir or an ancestor of it) and the\n * install root of each executable symlinked from one. Add other paths with\n * `mounts`. It has no root: `exec` with\n * `sudo: true` rejects. All three branch strategies are supported.\n *\n * Checks once per process that Bubblewrap is usable, and throws\n * `NativeSandboxUnavailableError` (with a `fixCommand` when there is\n * one) if it isn't: on a non-Linux OS, when `bwrap` isn't on `PATH`, or when\n * the kernel blocks unprivileged user namespaces. It never falls back to\n * running unsandboxed.\n */\nexport const bwrap = (options?: BwrapOptions): BindMountSandboxProvider => {\n // Reject a sandboxPath/hostPath mismatch before the preflight, so the\n // config error surfaces on every OS.\n const userMounts = bwrapMounts(options?.mounts ?? []);\n assertBwrapUsable();\n const maxTailChars = options?.maxOutputTailChars ?? MAX_TAIL_CHARS;\n return markNativeSandboxProvider(\n createBindMountSandboxProvider({\n name: \"bwrap\",\n env: options?.env ?? {},\n sandboxHomedir: SANDBOX_HOME,\n create: async (createOptions) =>\n createHandle(createOptions, { maxTailChars, userMounts }),\n }),\n );\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/bwrapProcess.ts","../../src/bwrapSandbox.ts","../../src/sandboxes/bwrap.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAQO,IAAM,OAAA,GAAU,CAAA;AAqBhB,IAAM,QAAA,GAAW,CAAA;AAcjB,IAAM,cAAA,GAAiB,CAAC,OAAA,KAA8B;AAAA,EAC3D,IAAA;AAAA,EACA,IAAA;AAAA,EACA,qCAAqC,QAAQ,CAAA;AAAA,KAAA,EACxC,QAA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AAA,CAAK,SAAS,CAAA;AAAA,IAC9C;AAAA,GACF;AACF,CAAA;AAoBO,IAAM,KAAA,GAAQ,CAAC,OAAA,KAAqD;AAGzE,EAAA,MAAM,UAAA,GAAa,WAAA,CAAY,OAAA,EAAS,MAAA,IAAU,EAAE,CAAA;AACpD,EAAA,iBAAA,EAAkB;AAClB,EAAA,MAAM,YAAA,GAAe,SAAS,kBAAA,IAAsB,cAAA;AACpD,EAAA,OAAO,yBAAA;AAAA,IACL,8BAAA,CAA+B;AAAA,MAC7B,IAAA,EAAM,OAAA;AAAA,MACN,GAAA,EAAK,OAAA,EAAS,GAAA,IAAO,EAAC;AAAA,MACtB,cAAA,EAAgB,YAAA;AAAA,MAChB,MAAA,EAAQ,OAAO,aAAA,KACb,YAAA,CAAa,eAAe,EAAE,YAAA,EAAc,YAAY;AAAA,KAC3D;AAAA,GACH;AACF","file":"bwrap.js","sourcesContent":["/**\n * The processes behind one `bwrap()` exec, and how to kill all of them. Used\n * only by `bwrap()`, through src/bwrapSandbox.ts.\n */\n\nimport type { ChildProcess } from \"node:child_process\";\n\n/** The fd bwrap reports the sandbox's PID 1 on (`--info-fd`). */\nexport const INFO_FD = 3;\n\n/**\n * One exec's bwrap. `proc` is the outer bwrap; `sandboxPid` is the host PID\n * of the sandbox's PID 1, once bwrap has reported it on {@link INFO_FD}.\n * Killing only the outer bwrap leaves the sandbox running: its PID 1 has its\n * own session and outlives its parent. Killing PID 1 ends every process in\n * the sandbox's PID namespace.\n */\nexport interface SandboxProcess {\n readonly proc: ChildProcess;\n sandboxPid: number | undefined;\n /** Settles once bwrap has reported the PID, or closed its info fd without one. */\n readonly reported: Promise<void>;\n}\n\n/**\n * The fd each sandbox's watcher reads (see {@link watchedCommand}). Its\n * other end is held only by this Node process, so it reads end-of-file\n * exactly when this process dies, however it dies.\n */\nexport const WATCH_FD = 4;\n\n/**\n * Runs `command` in the sandbox under a watcher: a background shell blocked\n * on {@link WATCH_FD}, which SIGKILLs every process in the sandbox's PID\n * namespace (`kill -1` spares only PID 1, which then exits) once this Node\n * process dies.\n *\n * `--die-with-parent` alone isn't enough: bwrap arms it in the sandbox's PID 1\n * only once setup is done, so a host process SIGKILLed during an exec's first\n * milliseconds leaves the sandbox running. The watcher starts after setup and\n * sees the end-of-file even if the host died first. The command itself runs\n * without the watcher's fd.\n */\nexport const watchedCommand = (command: string): string[] => [\n \"sh\",\n \"-c\",\n `{ read -r _ || :; kill -9 -1; } <&${WATCH_FD} >/dev/null 2>&1 &\nexec ${WATCH_FD}<&-\nexec sh -c \"$1\"`,\n \"sh\",\n command,\n];\n\nconst CHILD_PID = /\"child-pid\"\\s*:\\s*(?<pid>\\d+)/u;\n\n/** The `child-pid` in bwrap's `--info-fd` JSON, if it has one. */\nexport const parseChildPid = (info: string): number | undefined => {\n const pid = CHILD_PID.exec(info)?.groups?.[\"pid\"];\n return pid === undefined ? undefined : Number(pid);\n};\n\n/** SIGKILLs the sandbox's PID 1, if reported, and the outer bwrap. Synchronous, for shutdown. */\nexport const killSandboxProcess = (sandbox: SandboxProcess): void => {\n if (sandbox.sandboxPid !== undefined) {\n try {\n process.kill(sandbox.sandboxPid, \"SIGKILL\");\n } catch {\n // Already gone.\n }\n }\n sandbox.proc.kill(\"SIGKILL\");\n};\n","/**\n * The pieces of the `bwrap()` provider (src/sandboxes/bwrap.ts) that don't\n * run processes: the Bubblewrap arguments for a sandbox, its private dirs,\n * and the in-sandbox to host path mapping. Used only by `bwrap()`.\n */\n\nimport { join, posix } from \"node:path\";\nimport { FileSystem } from \"@effect/platform\";\nimport { Effect, Option } from \"effect\";\nimport type { BindMountCreateOptions } from \"./SandboxProvider.js\";\nimport { hostPathToolchainFromEnv } from \"./hostPathToolchain.js\";\nimport type { HostPathToolchain } from \"./hostPathToolchain.js\";\nimport { resolveIdentityMounts } from \"./identityMounts.js\";\nimport type { IdentityMount, MountConfig } from \"./identityMounts.js\";\nimport { BwrapError } from \"./errors.js\";\n\n/** The construction check, from its own module (it runs a process, synchronously). */\nexport { assertBwrapUsable } from \"./bwrapPreflight.js\";\nexport type { IdentityMount, MountConfig } from \"./identityMounts.js\";\n/** Tracking and killing each exec's processes, from their own module. */\nexport {\n INFO_FD,\n WATCH_FD,\n killSandboxProcess,\n parseChildPid,\n watchedCommand,\n} from \"./bwrapProcess.js\";\nexport type { SandboxProcess } from \"./bwrapProcess.js\";\n/** Output collection and file copies, shared by the native sandbox providers. */\nexport { collectOutput, copyCreatingParents } from \"./nativeSandboxIo.js\";\n\n/** The private home's path inside the sandbox. */\nexport const SANDBOX_HOME = \"/home/agent\";\nconst SANDBOX_TMP = \"/tmp\";\n\n/** Host dirs every sandbox sees read-only: the system toolchain. */\nconst SYSTEM_DIRS = [\n \"/usr\",\n \"/etc\",\n \"/bin\",\n \"/sbin\",\n \"/lib\",\n \"/lib32\",\n \"/lib64\",\n \"/libx32\",\n \"/opt\",\n];\n\n/**\n * Host dirs that stay hidden even when the host PATH names them: WSL2's\n * Windows drives and interop, so a planted `.exe` can't run.\n */\nconst DENIED_ROOTS = [\"/mnt\", \"/run/WSL\"];\nconst FALLBACK_PATH = \"/usr/local/bin:/usr/bin:/bin\";\n\nconst isWithin = (path: string, root: string): boolean =>\n path === root || path.startsWith(`${root}/`);\n\n/** `--ro-bind` each system dir, or recreate it as a symlink (merged-/usr layouts). */\nconst systemDirArgs: Effect.Effect<string[], never, FileSystem.FileSystem> =\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const args = yield* Effect.all(\n SYSTEM_DIRS.map((dir) =>\n Effect.gen(function* () {\n const link = yield* Effect.option(fs.readLink(dir));\n if (Option.isSome(link)) {\n return [\"--symlink\", link.value, dir];\n }\n const exists = yield* fs\n .exists(dir)\n .pipe(Effect.orElseSucceed(() => false));\n return exists ? [\"--ro-bind\", dir, dir] : [];\n }),\n ),\n );\n return args.flat();\n });\n\n/**\n * `/etc/resolv.conf` may point outside the system dirs (WSL2 links it into\n * `/mnt/wsl`). Mount just that file, read-only, so DNS works.\n */\nconst resolvConfArgs: Effect.Effect<string[], never, FileSystem.FileSystem> =\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const target = yield* Effect.option(fs.realPath(\"/etc/resolv.conf\"));\n return Option.isNone(target) ||\n SYSTEM_DIRS.some((d) => isWithin(target.value, d))\n ? []\n : [\"--ro-bind\", target.value, target.value];\n });\n\n/** Every mount at its host path, in order, so read-only overlays land on their writable parents. */\nconst mountArgs = (\n mounts: readonly { readonly hostPath: string; readonly readonly?: boolean }[],\n): string[] =>\n mounts.flatMap((m) => [\n m.readonly === true ? \"--ro-bind\" : \"--bind\",\n m.hostPath,\n m.hostPath,\n ]);\n\n/**\n * Each dir between a read-only overlay and the writable mount that holds it,\n * bound onto itself, each chain shallowest first. A mount point can't be renamed or\n * removed, so the overlay can't be moved aside by moving a parent (the git\n * worktree admin dir that holds `commondir`, say).\n */\nconst anchorArgs = (\n mounts: readonly { readonly hostPath: string; readonly readonly?: boolean }[],\n): string[] => {\n const writable = mounts.filter((m) => m.readonly !== true);\n const anchors = new Set<string>();\n for (const overlay of mounts.filter((m) => m.readonly === true)) {\n const roots = writable.filter((m) =>\n isWithin(overlay.hostPath, m.hostPath),\n );\n const chain: string[] = [];\n let dir = posix.dirname(overlay.hostPath);\n while (roots.some((m) => dir !== m.hostPath && isWithin(dir, m.hostPath))) {\n chain.unshift(dir);\n dir = posix.dirname(dir);\n }\n for (const anchor of chain) {\n anchors.add(anchor);\n }\n }\n return [...anchors].flatMap((anchor) => [\"--bind\", anchor, anchor]);\n};\n\n/**\n * Checks `bwrap()`'s `mounts` option: each mount, after resolution, must sit\n * at its own host path. Throws at construction otherwise.\n */\nexport const bwrapMounts = (mounts: readonly MountConfig[]): IdentityMount[] =>\n resolveIdentityMounts(\"bwrap\", mounts, SANDBOX_HOME);\n\n/** The host PATH toolchain: each readable dir `--ro-bind`, each symlinked PATH dir recreated. */\nconst toolchainArgs = (toolchain: HostPathToolchain): string[] => [\n ...toolchain.readableDirs.flatMap((dir) => [\"--ro-bind\", dir, dir]),\n ...toolchain.symlinks.flatMap((link) => [\n \"--symlink\",\n link.target,\n link.path,\n ]),\n];\n\nconst envArgs = (env: Record<string, string>): string[] =>\n Object.entries(env).flatMap(([key, value]) => [\"--setenv\", key, value]);\n\n/** The host dirs behind a sandbox's private home and `/tmp`. */\nexport interface PrivateDirs {\n readonly root: string;\n readonly home: string;\n readonly tmp: string;\n}\n\n/** Creates a sandbox's private dirs under the host temp dir. */\nexport const makePrivateDirs: Effect.Effect<\n PrivateDirs,\n BwrapError,\n FileSystem.FileSystem\n> = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const root = yield* fs.makeTempDirectory({ prefix: \"sandcastle-bwrap-\" });\n const dirs = { root, home: join(root, \"home\"), tmp: join(root, \"tmp\") };\n yield* fs.makeDirectory(dirs.home);\n yield* fs.makeDirectory(dirs.tmp);\n return dirs;\n}).pipe(\n Effect.mapError(\n (e) =>\n new BwrapError({\n message: `Couldn't create the bwrap() sandbox's private dirs: ${e.message}`,\n }),\n ),\n);\n\n/** Removes a sandbox's private dirs. */\nexport const removePrivateDirs = (\n dirs: PrivateDirs,\n): Effect.Effect<void, never, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n yield* fs\n .remove(dirs.root, { recursive: true })\n .pipe(Effect.orElse(() => Effect.void));\n });\n\n/** The bwrap arguments shared by every exec of one sandbox, up to `--chdir`. */\nexport const sandboxArgs = (\n options: BindMountCreateOptions,\n dirs: PrivateDirs,\n userMounts: readonly IdentityMount[],\n): Effect.Effect<string[], never, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const toolchain = yield* hostPathToolchainFromEnv({\n coveredRoots: SYSTEM_DIRS,\n deniedRoots: DENIED_ROOTS,\n });\n return [\n ...(yield* systemDirArgs),\n ...(yield* resolvConfArgs),\n \"--proc\",\n \"/proc\",\n \"--dev\",\n \"/dev\",\n \"--tmpfs\",\n \"/home\",\n \"--bind\",\n dirs.home,\n SANDBOX_HOME,\n \"--bind\",\n dirs.tmp,\n SANDBOX_TMP,\n ...toolchainArgs(toolchain),\n ...mountArgs(options.mounts),\n ...mountArgs(userMounts),\n ...anchorArgs(options.mounts),\n // The read-only core mounts (the #1261 overlays) again, so no user\n // mount can uncover them.\n ...mountArgs(options.mounts.filter((m) => m.readonly === true)),\n \"--clearenv\",\n ...envArgs({\n ...options.env,\n PATH:\n toolchain.pathEntries.length > 0\n ? toolchain.pathEntries.join(\":\")\n : FALLBACK_PATH,\n HOME: SANDBOX_HOME,\n TMPDIR: SANDBOX_TMP,\n }),\n \"--unshare-all\",\n \"--share-net\",\n \"--die-with-parent\",\n \"--new-session\",\n ];\n });\n\n/**\n * Maps an in-sandbox path to the host file behind it. Mounts sit at their\n * host paths; the private home and `/tmp` are the private dirs.\n */\nexport const toHostPath = (\n path: string,\n dirs: PrivateDirs,\n mounts: BindMountCreateOptions[\"mounts\"],\n): string => {\n const p = posix.normalize(path);\n if (mounts.some((m) => isWithin(p, m.hostPath))) {\n return p;\n }\n if (isWithin(p, SANDBOX_HOME)) {\n return join(dirs.home, posix.relative(SANDBOX_HOME, p));\n }\n if (isWithin(p, SANDBOX_TMP)) {\n return join(dirs.tmp, posix.relative(SANDBOX_TMP, p));\n }\n return p;\n};\n","/**\n * Bubblewrap sandbox provider — a native sandbox provider for Linux and WSL2.\n *\n * Usage:\n * import { bwrap } from \"@ai-hero/sandcastle/sandboxes/bwrap\";\n * await run({ agent: claudeCode(\"claude-opus-4-8\"), sandbox: bwrap() });\n *\n * Each `exec` runs in a fresh Bubblewrap sandbox: the host's system dirs\n * read-only, the worktree and git dirs at their host paths, a private home at\n * `/home/agent` and a private `/tmp`, its own PID namespace, the host network,\n * and only the env vars Sandcastle passes in. No image, no daemon.\n */\n\nimport { spawn } from \"node:child_process\";\nimport type { ChildProcess } from \"node:child_process\";\nimport { once } from \"node:events\";\nimport type { FileSystem } from \"@effect/platform\";\nimport { NodeFileSystem } from \"@effect/platform-node\";\nimport { Effect } from \"effect\";\nimport {\n INFO_FD,\n SANDBOX_HOME,\n assertBwrapUsable,\n collectOutput,\n copyCreatingParents,\n bwrapMounts,\n killSandboxProcess,\n makePrivateDirs,\n removePrivateDirs,\n sandboxArgs,\n parseChildPid,\n toHostPath,\n watchedCommand,\n} from \"../bwrapSandbox.js\";\nimport type {\n IdentityMount,\n MountConfig,\n PrivateDirs,\n SandboxProcess,\n} from \"../bwrapSandbox.js\";\nimport { createBindMountSandboxProvider } from \"../SandboxProvider.js\";\nimport type {\n BindMountCreateOptions,\n BindMountSandboxHandle,\n BindMountSandboxProvider,\n ExecResult,\n} from \"../SandboxProvider.js\";\nimport { MAX_TAIL_CHARS } from \"../boundedTail.js\";\nimport { markNativeSandboxProvider } from \"../nativeSandboxProvider.js\";\nimport { registerNativeSandboxShutdown } from \"../nativeSandboxShutdown.js\";\n\n/** Options for {@link bwrap}. */\nexport interface BwrapOptions {\n /** Environment variables injected by this provider. Merged at launch time. */\n readonly env?: Record<string, string>;\n /**\n * Maximum number of characters of streamed `exec` output retained per stream\n * (stdout and stderr) when an `onLine` callback is supplied (default: 64KiB).\n *\n * Output is delivered live to `onLine` regardless; this only bounds the tail\n * returned in `ExecResult`, preventing a long-running agent's output from\n * overflowing V8's max string length and crashing the run.\n */\n readonly maxOutputTailChars?: number;\n /**\n * Extra host paths to make visible in the sandbox (a cache, a sibling\n * checkout, `.beads/`). Each appears at its own host path, so after\n * resolution `sandboxPath` must equal `hostPath`; `bwrap()` throws\n * otherwise. `readonly` defaults to `false`.\n */\n readonly mounts?: readonly MountConfig[];\n}\n\n/** Tracks the sandbox PID bwrap reports on the child's {@link INFO_FD} pipe. */\nconst trackSandboxProcess = (proc: ChildProcess): SandboxProcess => {\n const info = proc.stdio[INFO_FD];\n const tracked: { -readonly [K in keyof SandboxProcess]: SandboxProcess[K] } =\n { proc, sandboxPid: undefined, reported: Promise.resolve() };\n if (info !== null && info !== undefined) {\n let text = \"\";\n info.on(\"data\", (chunk: Buffer) => {\n text += chunk.toString();\n });\n const record = async (): Promise<void> => {\n await once(info, \"close\").catch(() => undefined);\n tracked.sandboxPid = parseChildPid(text);\n };\n tracked.reported = record();\n }\n return tracked;\n};\n\ntype ExecOptions = Parameters<BindMountSandboxHandle[\"exec\"]>[1];\n\n/** Runs `sh -c command` in a fresh bwrap and resolves when it exits. */\nconst runInBwrap = async (\n args: readonly string[],\n opts: ExecOptions,\n sandbox: { live: Set<SandboxProcess>; maxTailChars: number },\n): Promise<ExecResult> => {\n const { live, maxTailChars } = sandbox;\n const proc = spawn(\"bwrap\", [\"--info-fd\", String(INFO_FD), ...args], {\n // fd 3 is INFO_FD; fd 4 is the watcher's WATCH_FD, which is never\n // written and ends only when this process does.\n stdio: [\"pipe\", \"pipe\", \"pipe\", \"pipe\", \"pipe\"],\n });\n const tracked = trackSandboxProcess(proc);\n live.add(tracked);\n const output = collectOutput(proc, opts?.onLine, maxTailChars);\n proc.stdin.on(\"error\", () => undefined);\n proc.stdin.end(opts?.stdin ?? \"\");\n try {\n await once(proc, \"close\");\n return { ...output(), exitCode: proc.exitCode ?? 1 };\n } finally {\n live.delete(tracked);\n }\n};\n\n/** Runs a file-system Effect on the host's file system. */\nconst runOnHost = async <A, E>(\n effect: Effect.Effect<A, E, FileSystem.FileSystem>,\n): Promise<A> =>\n effect.pipe(Effect.provide(NodeFileSystem.layer), Effect.runPromise);\n\n/** Creates the sandbox's private dirs and the bwrap arguments every exec shares. */\nconst prepare = async (\n options: BindMountCreateOptions,\n userMounts: readonly IdentityMount[],\n): Promise<{ dirs: PrivateDirs; baseArgs: string[] }> =>\n Effect.gen(function* () {\n const dirs = yield* makePrivateDirs;\n const baseArgs = yield* sandboxArgs(options, dirs, userMounts);\n return { dirs, baseArgs };\n }).pipe(runOnHost);\n\nconst createHandle = async (\n options: BindMountCreateOptions,\n config: { maxTailChars: number; userMounts: readonly IdentityMount[] },\n): Promise<BindMountSandboxHandle> => {\n const { maxTailChars, userMounts } = config;\n const { dirs, baseArgs } = await prepare(options, userMounts);\n const live = new Set<SandboxProcess>();\n const killAll = (): void => {\n for (const sandbox of live) {\n killSandboxProcess(sandbox);\n }\n };\n const unregisterShutdown = registerNativeSandboxShutdown(killAll, dirs);\n let closed = false;\n const hostPathOf = (p: string): string => toHostPath(p, dirs, options.mounts);\n\n return {\n worktreePath: options.worktreePath,\n exec: async (command, opts) => {\n if (opts?.sudo === true) {\n throw new Error(\n \"bwrap() has no root: exec with sudo: true isn't supported in a native sandbox. \" +\n \"Use docker() for setup that needs root.\",\n );\n }\n if (closed) {\n throw new Error(\"bwrap() sandbox is closed\");\n }\n const cwd = opts?.cwd ?? options.worktreePath;\n const args = [...baseArgs, \"--chdir\", cwd, ...watchedCommand(command)];\n return runInBwrap(args, opts, { live, maxTailChars });\n },\n copyFileIn: async (hostPath, sandboxFile) =>\n copyCreatingParents(hostPath, hostPathOf(sandboxFile)).pipe(runOnHost),\n copyFileOut: async (sandboxFile, hostPath) =>\n copyCreatingParents(hostPathOf(sandboxFile), hostPath).pipe(runOnHost),\n close: async () => {\n closed = true;\n const running = [...live];\n const exits = running.map(async ({ proc }) => once(proc, \"close\"));\n // Wait for each sandbox's PID 1, so a just-started exec is killed too.\n await Promise.all(running.map(async ({ reported }) => reported));\n killAll();\n await Promise.allSettled(exits);\n unregisterShutdown();\n await removePrivateDirs(dirs).pipe(runOnHost);\n },\n };\n};\n\n/**\n * Create a Bubblewrap sandbox provider (Linux and WSL2).\n *\n * The agent runs the host's own toolchain, read-only, and can write only the\n * worktree, the git dirs Sandcastle mounts, a private `/tmp` and a private\n * home at `/home/agent`. Both private dirs are removed on close, and so is\n * every process the sandbox started. The toolchain comes from the host\n * `PATH`: each `PATH` dir (never the home dir or an ancestor of it) and the\n * install root of each executable symlinked from one. Add other paths with\n * `mounts`. It has no root: `exec` with\n * `sudo: true` rejects. All three branch strategies are supported.\n *\n * Checks once per process that Bubblewrap is usable, and throws\n * `NativeSandboxUnavailableError` (with a `fixCommand` when there is\n * one) if it isn't: on a non-Linux OS, when `bwrap` isn't on `PATH`, or when\n * the kernel blocks unprivileged user namespaces. It never falls back to\n * running unsandboxed.\n */\nexport const bwrap = (options?: BwrapOptions): BindMountSandboxProvider => {\n // Reject a sandboxPath/hostPath mismatch before the preflight, so the\n // config error surfaces on every OS.\n const userMounts = bwrapMounts(options?.mounts ?? []);\n assertBwrapUsable();\n const maxTailChars = options?.maxOutputTailChars ?? MAX_TAIL_CHARS;\n return markNativeSandboxProvider(\n createBindMountSandboxProvider({\n name: \"bwrap\",\n env: options?.env ?? {},\n sandboxHomedir: SANDBOX_HOME,\n create: async (createOptions) =>\n createHandle(createOptions, { maxTailChars, userMounts }),\n }),\n );\n};\n"]}
|
|
@@ -1,26 +1,46 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';
|
|
2
|
-
import { createIsolatedSandboxProvider } from '../chunk-
|
|
2
|
+
import { createIsolatedSandboxProvider } from '../chunk-4BB7DNPW.js';
|
|
3
3
|
import { MAX_TAIL_CHARS, BoundedTail } from '../chunk-6NQPCXSG.js';
|
|
4
4
|
import { stat, readdir } from 'fs/promises';
|
|
5
|
-
import { posix,
|
|
5
|
+
import { posix, join, relative } from 'path';
|
|
6
6
|
|
|
7
7
|
createRequire(import.meta.url);
|
|
8
|
-
var
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
|
|
8
|
+
var createWorkspaceFolder = async (sandbox) => {
|
|
9
|
+
const workDir = await sandbox.getWorkDir() ?? await sandbox.getUserHomeDir() ?? "/home/daytona";
|
|
10
|
+
const worktreePath = posix.join(workDir, "workspace");
|
|
11
|
+
await sandbox.fs.createFolder(worktreePath, "755");
|
|
12
|
+
return worktreePath;
|
|
13
|
+
};
|
|
14
|
+
var walkFiles = async (dir) => {
|
|
15
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
16
|
+
const nested = await Promise.all(
|
|
17
|
+
entries.map(async (entry) => {
|
|
18
|
+
const full = join(dir, entry.name);
|
|
19
|
+
return entry.isDirectory() ? walkFiles(full) : [full];
|
|
20
|
+
})
|
|
21
|
+
);
|
|
22
|
+
return nested.flat();
|
|
23
|
+
};
|
|
24
|
+
var copyInToSandbox = async (sandbox, hostPath, sandboxPath) => {
|
|
25
|
+
const info = await stat(hostPath);
|
|
26
|
+
if (!info.isDirectory()) {
|
|
27
|
+
await sandbox.fs.uploadFile(hostPath, sandboxPath);
|
|
28
|
+
return;
|
|
18
29
|
}
|
|
19
|
-
|
|
20
|
-
|
|
30
|
+
const files = await walkFiles(hostPath);
|
|
31
|
+
if (files.length === 0) {
|
|
32
|
+
return;
|
|
21
33
|
}
|
|
22
|
-
|
|
34
|
+
await sandbox.fs.uploadFiles(
|
|
35
|
+
files.map((file) => ({
|
|
36
|
+
source: file,
|
|
37
|
+
destination: join(sandboxPath, relative(hostPath, file))
|
|
38
|
+
}))
|
|
39
|
+
);
|
|
23
40
|
};
|
|
41
|
+
|
|
42
|
+
// src/sandboxes/daytonaSession.ts
|
|
43
|
+
var shellEscape = (s) => `'${s.replaceAll("'", String.raw`'\''`)}'`;
|
|
24
44
|
var prepareCommand = async (sandbox, command, opts) => {
|
|
25
45
|
const effectiveCommand = opts?.sudo === true ? `sudo sh -c ${shellEscape(command)}` : command;
|
|
26
46
|
if (opts?.stdin === void 0) {
|
|
@@ -39,6 +59,50 @@ var probeSessionShell = async (sandbox, { sessionId, cmdId, pidPath }) => {
|
|
|
39
59
|
const cmd = await sandbox.process.getSessionCommand(sessionId, cmdId).catch(() => void 0);
|
|
40
60
|
return typeof cmd?.exitCode === "number" ? "exited" : "lost";
|
|
41
61
|
};
|
|
62
|
+
var streamSessionLogs = ({ sandbox, maxOutputTailChars }, { sessionId, cmdId }, onLine) => {
|
|
63
|
+
const stdoutTail = new BoundedTail(maxOutputTailChars, "\n");
|
|
64
|
+
const stderrTail = new BoundedTail(maxOutputTailChars, "");
|
|
65
|
+
let partial = "";
|
|
66
|
+
const done = sandbox.process.getSessionCommandLogs(
|
|
67
|
+
sessionId,
|
|
68
|
+
cmdId,
|
|
69
|
+
(chunk) => {
|
|
70
|
+
const lines = (partial + chunk).split("\n");
|
|
71
|
+
partial = lines.pop() ?? "";
|
|
72
|
+
for (const line of lines) {
|
|
73
|
+
stdoutTail.push(line);
|
|
74
|
+
onLine(line);
|
|
75
|
+
}
|
|
76
|
+
},
|
|
77
|
+
(chunk) => {
|
|
78
|
+
stderrTail.push(chunk);
|
|
79
|
+
}
|
|
80
|
+
);
|
|
81
|
+
const flush = () => {
|
|
82
|
+
if (partial) {
|
|
83
|
+
stdoutTail.push(partial);
|
|
84
|
+
onLine(partial);
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
return { done, flush, stdoutTail, stderrTail };
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
// src/sandboxes/daytona.ts
|
|
91
|
+
var SESSION_WATCH_INTERVAL_MS = 15e3;
|
|
92
|
+
var toDaytonaConfig = (options) => {
|
|
93
|
+
const { apiKey, apiUrl, target } = options ?? {};
|
|
94
|
+
const config = {};
|
|
95
|
+
if (apiKey !== void 0 && apiKey !== "") {
|
|
96
|
+
config.apiKey = apiKey;
|
|
97
|
+
}
|
|
98
|
+
if (apiUrl !== void 0 && apiUrl !== "") {
|
|
99
|
+
config.apiUrl = apiUrl;
|
|
100
|
+
}
|
|
101
|
+
if (target !== void 0 && target !== "") {
|
|
102
|
+
config.target = target;
|
|
103
|
+
}
|
|
104
|
+
return config;
|
|
105
|
+
};
|
|
42
106
|
var watchSessionShell = (sandbox, session, command) => {
|
|
43
107
|
let watchTimer;
|
|
44
108
|
let watching = true;
|
|
@@ -77,33 +141,6 @@ var watchSessionShell = (sandbox, session, command) => {
|
|
|
77
141
|
}
|
|
78
142
|
};
|
|
79
143
|
};
|
|
80
|
-
var streamSessionLogs = ({ sandbox, maxOutputTailChars }, { sessionId, cmdId }, onLine) => {
|
|
81
|
-
const stdoutTail = new BoundedTail(maxOutputTailChars, "\n");
|
|
82
|
-
const stderrTail = new BoundedTail(maxOutputTailChars, "");
|
|
83
|
-
let partial = "";
|
|
84
|
-
const done = sandbox.process.getSessionCommandLogs(
|
|
85
|
-
sessionId,
|
|
86
|
-
cmdId,
|
|
87
|
-
(chunk) => {
|
|
88
|
-
const lines = (partial + chunk).split("\n");
|
|
89
|
-
partial = lines.pop() ?? "";
|
|
90
|
-
for (const line of lines) {
|
|
91
|
-
stdoutTail.push(line);
|
|
92
|
-
onLine(line);
|
|
93
|
-
}
|
|
94
|
-
},
|
|
95
|
-
(chunk) => {
|
|
96
|
-
stderrTail.push(chunk);
|
|
97
|
-
}
|
|
98
|
-
);
|
|
99
|
-
const flush = () => {
|
|
100
|
-
if (partial) {
|
|
101
|
-
stdoutTail.push(partial);
|
|
102
|
-
onLine(partial);
|
|
103
|
-
}
|
|
104
|
-
};
|
|
105
|
-
return { done, flush, stdoutTail, stderrTail };
|
|
106
|
-
};
|
|
107
144
|
var execStreaming = async (context, {
|
|
108
145
|
command,
|
|
109
146
|
effectiveCommand,
|
|
@@ -120,8 +157,7 @@ var execStreaming = async (context, {
|
|
|
120
157
|
async: true
|
|
121
158
|
});
|
|
122
159
|
const logs = streamSessionLogs(context, { sessionId, cmdId }, onLine);
|
|
123
|
-
logs.done.catch(() =>
|
|
124
|
-
});
|
|
160
|
+
logs.done.catch(() => void 0);
|
|
125
161
|
const shell = watchSessionShell(
|
|
126
162
|
sandbox,
|
|
127
163
|
{ sessionId, cmdId, pidPath },
|
|
@@ -140,10 +176,8 @@ var execStreaming = async (context, {
|
|
|
140
176
|
exitCode: cmdInfo.exitCode ?? 0
|
|
141
177
|
};
|
|
142
178
|
} finally {
|
|
143
|
-
await sandbox.process.deleteSession(sessionId).catch(() =>
|
|
144
|
-
});
|
|
145
|
-
await sandbox.process.executeCommand(`rm -f ${pidPath}`).catch(() => {
|
|
146
|
-
});
|
|
179
|
+
await sandbox.process.deleteSession(sessionId).catch(() => void 0);
|
|
180
|
+
await sandbox.process.executeCommand(`rm -f ${pidPath}`).catch(() => void 0);
|
|
147
181
|
}
|
|
148
182
|
};
|
|
149
183
|
var daytonaExec = async (context, command, opts) => {
|
|
@@ -164,37 +198,6 @@ var daytonaExec = async (context, command, opts) => {
|
|
|
164
198
|
exitCode: response.exitCode
|
|
165
199
|
};
|
|
166
200
|
};
|
|
167
|
-
var createWorkspaceFolder = async (sandbox) => {
|
|
168
|
-
const workDir = await sandbox.getWorkDir() ?? await sandbox.getUserHomeDir() ?? "/home/daytona";
|
|
169
|
-
const worktreePath = posix.join(workDir, "workspace");
|
|
170
|
-
await sandbox.fs.createFolder(worktreePath, "755");
|
|
171
|
-
return worktreePath;
|
|
172
|
-
};
|
|
173
|
-
var walkFiles = async (dir) => {
|
|
174
|
-
const entries = await readdir(dir, { withFileTypes: true });
|
|
175
|
-
const files = [];
|
|
176
|
-
for (const entry of entries) {
|
|
177
|
-
const full = join(dir, entry.name);
|
|
178
|
-
if (entry.isDirectory()) {
|
|
179
|
-
files.push(...await walkFiles(full));
|
|
180
|
-
} else {
|
|
181
|
-
files.push(full);
|
|
182
|
-
}
|
|
183
|
-
}
|
|
184
|
-
return files;
|
|
185
|
-
};
|
|
186
|
-
var copyInToSandbox = async (sandbox, hostPath, sandboxPath) => {
|
|
187
|
-
const info = await stat(hostPath);
|
|
188
|
-
if (!info.isDirectory()) {
|
|
189
|
-
await sandbox.fs.uploadFile(hostPath, sandboxPath);
|
|
190
|
-
return;
|
|
191
|
-
}
|
|
192
|
-
const files = await walkFiles(hostPath);
|
|
193
|
-
for (const file of files) {
|
|
194
|
-
const rel = relative(hostPath, file);
|
|
195
|
-
await sandbox.fs.uploadFile(file, join(sandboxPath, rel));
|
|
196
|
-
}
|
|
197
|
-
};
|
|
198
201
|
var daytona = (options) => createIsolatedSandboxProvider({
|
|
199
202
|
name: "daytona",
|
|
200
203
|
env: options?.env,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../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AAA,MAAM,OAAA,GAAU,EAAE,OAAA,EAAS,YAAA,EAAc,kBAAA,EAAmB;AAC5D,IAAA,OAAO;AAAA,MACL,YAAA;AAAA,MACA,WAAW,OAAA,CAAQ,EAAA;AAAA,MACnB,MAAM,OAAO,OAAA,EAAiB,SAC5B,WAAA,CAAY,OAAA,EAAS,SAAS,IAAI,CAAA;AAAA,MACpC,QAAQ,OAAO,QAAA,EAAkB,gBAC/B,eAAA,CAAgB,OAAA,EAAS,UAAU,WAAW,CAAA;AAAA,MAChD,WAAA,EAAa,OACX,WAAA,EACA,QAAA,KACkB;AAClB,QAAA,MAAM,OAAA,CAAQ,EAAA,CAAG,YAAA,CAAa,WAAA,EAAa,QAAQ,CAAA;AAAA,MACrD,CAAA;AAAA,MAEA,OAAO,YAA2B;AAChC,QAAA,MAAM,MAAA,CAAO,OAAO,OAAO,CAAA;AAAA,MAC7B;AAAA,KACF;AAAA,EACF;AACF,CAAC","file":"daytona.js","sourcesContent":["/**\n * Daytona isolated sandbox provider.\n *\n * Creates ephemeral Daytona sandboxes via `@daytona/sdk`.\n * Requires `@daytona/sdk` as a peer dependency.\n */\n\nimport { readdir, stat } from \"node:fs/promises\";\nimport { join, posix, relative } from \"node:path\";\nimport { createIsolatedSandboxProvider } from \"../SandboxProvider.js\";\nimport type {\n ExecResult,\n IsolatedSandboxHandle,\n IsolatedSandboxProvider,\n} from \"../SandboxProvider.js\";\nimport { BoundedTail, MAX_TAIL_CHARS } from \"../boundedTail.js\";\n\nimport type {\n Daytona as DaytonaClient,\n DaytonaConfig,\n Sandbox as DaytonaSandbox,\n CreateSandboxFromImageParams,\n CreateSandboxFromSnapshotParams,\n} from \"@daytona/sdk\";\n\nconst shellEscape = (s: string): string =>\n `'${s.replaceAll(\"'\", String.raw`'\\''`)}'`;\n\n/** Options for the Daytona sandbox provider. */\nexport interface DaytonaOptions {\n /**\n * Daytona API key for authentication.\n * Falls back to the `DAYTONA_API_KEY` environment variable if not provided.\n */\n readonly apiKey?: string;\n\n /**\n * Daytona API URL.\n * Falls back to the `DAYTONA_API_URL` environment variable if not provided.\n */\n readonly apiUrl?: string;\n\n /**\n * Target environment for sandboxes.\n * Falls back to the `DAYTONA_TARGET` environment variable if not provided.\n */\n readonly target?: string;\n\n /**\n * Options passed through to the Daytona SDK when creating a sandbox.\n * Supports both image-based and snapshot-based creation.\n */\n readonly create?:\n | CreateSandboxFromImageParams\n | CreateSandboxFromSnapshotParams;\n\n /** Environment variables injected by this provider. Merged at launch time with env resolver and agent provider env. */\n readonly env?: Record<string, string>;\n\n /**\n * Maximum number of characters of streamed `exec` output retained per stream\n * (stdout and stderr) when an `onLine` callback is supplied (default: 64KiB).\n *\n * Output is delivered live to `onLine` regardless; this only bounds the tail\n * returned in `ExecResult`, preventing a long-running agent's output from\n * overflowing V8's max string length and crashing the run.\n */\n readonly maxOutputTailChars?: number;\n}\n\n/** How often a streamed `exec` checks that its session shell is still alive. */\nconst SESSION_WATCH_INTERVAL_MS = 15_000;\n\n/** The Daytona client config: only the connection options that are set. */\nconst toDaytonaConfig = (options?: DaytonaOptions): DaytonaConfig => {\n const { apiKey, apiUrl, target } = options ?? {};\n const config: DaytonaConfig = {};\n if (apiKey !== undefined && apiKey !== \"\") {\n config.apiKey = apiKey;\n }\n if (apiUrl !== undefined && apiUrl !== \"\") {\n config.apiUrl = apiUrl;\n }\n if (target !== undefined && target !== \"\") {\n config.target = target;\n }\n return config;\n};\n\n/** Options `exec` accepts. */\ninterface DaytonaExecOptions {\n readonly onLine?: (line: string) => void;\n readonly cwd?: string;\n readonly sudo?: boolean;\n readonly stdin?: string;\n}\n\n/** The sandbox a handle drives, and the settings its `exec` needs. */\ninterface DaytonaExecContext {\n readonly sandbox: DaytonaSandbox;\n readonly worktreePath: string;\n readonly maxOutputTailChars: number;\n}\n\n/**\n * `command` ready to run: wrapped in `sudo sh -c` when asked, and with any\n * stdin uploaded to a file in the sandbox and redirected in.\n */\nconst prepareCommand = async (\n sandbox: DaytonaSandbox,\n command: string,\n opts: DaytonaExecOptions | undefined,\n): Promise<string> => {\n // Wrap the whole command in `sh -c`, so sudo elevates all of it\n // (`a && b`, not just `a`).\n const effectiveCommand =\n opts?.sudo === true ? `sudo sh -c ${shellEscape(command)}` : command;\n if (opts?.stdin === undefined) {\n return effectiveCommand;\n }\n // Daytona's exec APIs have no stdin channel: the command reads\n // EOF. So write stdin to a file in the sandbox and redirect it in\n // (a file, not an argument, keeps clear of the per-arg size\n // limit). The redirect opens the file before the group runs, so\n // the group can delete it straight away and leave nothing behind.\n const stdinPath = `/tmp/sandcastle-stdin-${crypto.randomUUID()}`;\n await sandbox.fs.uploadFile(Buffer.from(opts.stdin), stdinPath);\n return `{ rm -f ${stdinPath}; ${effectiveCommand}\\n} < ${stdinPath}`;\n};\n\n/** A running session command, and the file holding its shell's PID. */\ninterface SessionCommand {\n readonly sessionId: string;\n readonly cmdId: string;\n readonly pidPath: string;\n}\n\n/**\n * Whether a session's shell is still `alive`; if not, whether its command\n * `exited` with a recorded exit code or was `lost` without one.\n */\nconst probeSessionShell = async (\n sandbox: DaytonaSandbox,\n { sessionId, cmdId, pidPath }: SessionCommand,\n): Promise<\"alive\" | \"exited\" | \"lost\"> => {\n const alive = await sandbox.process\n .executeCommand(`test ! -f ${pidPath} || kill -0 \"$(cat ${pidPath})\"`)\n .then((r) => r.exitCode === 0)\n .catch(() => true);\n if (alive) {\n return \"alive\";\n }\n const cmd = await sandbox.process\n .getSessionCommand(sessionId, cmdId)\n .catch(() => undefined);\n return typeof cmd?.exitCode === \"number\" ? \"exited\" : \"lost\";\n};\n\n/**\n * Watches a session's shell: if it dies (killed, say) the log stream would\n * wait forever, so once it is gone `gone` settles: it fails if the command\n * recorded no exit code. A missing PID file counts as alive, so it can never\n * fail a command. Call `stop` once the race is over. An unexpected throw\n * while checking rejects `gone` instead of escaping as an unhandled\n * rejection from the timer.\n */\nconst watchSessionShell = (\n sandbox: DaytonaSandbox,\n session: SessionCommand,\n command: string,\n): { readonly gone: Promise<void>; readonly stop: () => void } => {\n let watchTimer: ReturnType<typeof setTimeout> | undefined;\n let watching = true;\n const gone = new Promise<void>((resolve, reject) => {\n const scheduleCheck = () => {\n watchTimer = setTimeout(() => {\n check().catch(reject);\n }, SESSION_WATCH_INTERVAL_MS);\n };\n const check = async () => {\n const state = await probeSessionShell(sandbox, session);\n if (!watching) {\n return;\n }\n if (state === \"alive\") {\n scheduleCheck();\n return;\n }\n if (state === \"exited\") {\n resolve();\n return;\n }\n reject(\n new Error(\n `Daytona session shell exited before the command finished, so its exit code is unknown: ${command}`,\n ),\n );\n };\n scheduleCheck();\n });\n return {\n gone,\n stop: () => {\n watching = false;\n clearTimeout(watchTimer);\n },\n };\n};\n\n/**\n * Streams a running session command's stdout to `onLine`, line by line,\n * keeping a bounded tail of stdout and stderr. `done` settles once the log\n * stream closes; `flush` then emits any final unterminated line.\n */\nconst streamSessionLogs = (\n { sandbox, maxOutputTailChars }: DaytonaExecContext,\n { sessionId, cmdId }: { readonly sessionId: string; readonly cmdId: string },\n onLine: (line: string) => void,\n) => {\n const stdoutTail = new BoundedTail(maxOutputTailChars, \"\\n\");\n const stderrTail = new BoundedTail(maxOutputTailChars, \"\");\n let partial = \"\";\n const done = sandbox.process.getSessionCommandLogs(\n sessionId,\n cmdId,\n (chunk: string) => {\n const lines = (partial + chunk).split(\"\\n\");\n partial = lines.pop() ?? \"\";\n for (const line of lines) {\n stdoutTail.push(line);\n onLine(line);\n }\n },\n (chunk: string) => {\n stderrTail.push(chunk);\n },\n );\n const flush = () => {\n if (partial) {\n stdoutTail.push(partial);\n onLine(partial);\n }\n };\n return { done, flush, stdoutTail, stderrTail };\n};\n\n/**\n * Runs `command` in a fresh session, streaming its stdout to `onLine`.\n *\n * A session runs its commands in one long-lived shell, which records each\n * command's exit code once it returns. A command that ends that shell (a\n * top-level `exit`) never gets one, and its log stream never closes. So the\n * command runs in a subshell, where `exit` ends only the subshell. The\n * newline before `)` keeps a trailing comment from swallowing it. The\n * session shell's PID goes to a file, to check it is still alive.\n */\nconst execStreaming = async (\n context: DaytonaExecContext,\n {\n command,\n effectiveCommand,\n cwd,\n }: {\n readonly command: string;\n readonly effectiveCommand: string;\n readonly cwd: string;\n },\n onLine: (line: string) => void,\n): Promise<ExecResult> => {\n const { sandbox } = context;\n const sessionId = `sandcastle-${crypto.randomUUID()}`;\n const pidPath = `/tmp/${sessionId}.pid`;\n await sandbox.process.createSession(sessionId);\n try {\n const { cmdId } = await sandbox.process.executeSessionCommand(sessionId, {\n command: `echo $$ > ${pidPath}; ( cd ${cwd} && ${effectiveCommand}\\n)`,\n async: true,\n });\n const logs = streamSessionLogs(context, { sessionId, cmdId }, onLine);\n // Once the race below is lost, a late failure of the stream\n // must not surface as an unhandled rejection.\n logs.done.catch(() => {});\n const shell = watchSessionShell(\n sandbox,\n { sessionId, cmdId, pidPath },\n command,\n );\n try {\n await Promise.race([logs.done, shell.gone]);\n } finally {\n shell.stop();\n }\n logs.flush();\n const cmdInfo = await sandbox.process.getSessionCommand(sessionId, cmdId);\n return {\n stdout: logs.stdoutTail.toString(),\n stderr: logs.stderrTail.toString(),\n exitCode: cmdInfo.exitCode ?? 0,\n };\n } finally {\n await sandbox.process.deleteSession(sessionId).catch(() => {});\n await sandbox.process.executeCommand(`rm -f ${pidPath}`).catch(() => {});\n }\n};\n\n/** A handle's `exec`: streamed through a session with `onLine`, else plain. */\nconst daytonaExec = async (\n context: DaytonaExecContext,\n command: string,\n opts?: DaytonaExecOptions,\n): Promise<ExecResult> => {\n const { sandbox, worktreePath } = context;\n const effectiveCommand = await prepareCommand(sandbox, command, opts);\n const cwd = opts?.cwd ?? worktreePath;\n if (opts?.onLine) {\n return execStreaming(\n context,\n { command, effectiveCommand, cwd },\n opts.onLine,\n );\n }\n const response = await sandbox.process.executeCommand(effectiveCommand, cwd);\n // `executeCommand` merges stdout and stderr into `result` and has\n // no separate stderr. On failure, surface that output as stderr\n // too, so the error says why the command failed, not just its exit\n // code.\n return {\n stdout: response.result,\n stderr: response.exitCode === 0 ? \"\" : response.result,\n exitCode: response.exitCode,\n };\n};\n\n/**\n * Creates the sandbox's worktree folder and returns its path. It is a\n * subdirectory of the work dir, not the work dir itself: sync-in clones into\n * `${worktreePath}_clone` and then replaces worktreePath, which needs a\n * parent the sandbox user can write. On the default snapshot the work dir is\n * the user's home (/home/daytona), and /home is root-owned.\n */\nconst createWorkspaceFolder = async (\n sandbox: DaytonaSandbox,\n): Promise<string> => {\n const workDir =\n (await sandbox.getWorkDir()) ??\n (await sandbox.getUserHomeDir()) ??\n \"/home/daytona\";\n const worktreePath = posix.join(workDir, \"workspace\");\n await sandbox.fs.createFolder(worktreePath, \"755\");\n return worktreePath;\n};\n\n/** Every file under `dir`, recursively. */\nconst walkFiles = async (dir: string): Promise<string[]> => {\n const entries = await readdir(dir, { withFileTypes: true });\n const files: string[] = [];\n for (const entry of entries) {\n const full = join(dir, entry.name);\n if (entry.isDirectory()) {\n files.push(...(await walkFiles(full)));\n } else {\n files.push(full);\n }\n }\n return files;\n};\n\n/** Uploads a host file, or a directory's files, to `sandboxPath`. */\nconst copyInToSandbox = async (\n sandbox: DaytonaSandbox,\n hostPath: string,\n sandboxPath: string,\n): Promise<void> => {\n const info = await stat(hostPath);\n if (!info.isDirectory()) {\n await sandbox.fs.uploadFile(hostPath, sandboxPath);\n return;\n }\n const files = await walkFiles(hostPath);\n for (const file of files) {\n const rel = relative(hostPath, file);\n await sandbox.fs.uploadFile(file, join(sandboxPath, rel));\n }\n};\n\n/**\n * Create a Daytona isolated sandbox provider.\n *\n * Sandboxes are ephemeral — each `create()` call spins up a new Daytona\n * sandbox and `close()` destroys it.\n *\n * @example\n * ```ts\n * import { daytona } from \"@ai-hero/sandcastle/sandboxes/daytona\";\n *\n * const provider = daytona({ apiKey: \"dyt_my_key\" });\n * ```\n */\nexport const daytona = (options?: DaytonaOptions): IsolatedSandboxProvider =>\n createIsolatedSandboxProvider({\n name: \"daytona\",\n env: options?.env,\n create: async (createOptions): Promise<IsolatedSandboxHandle> => {\n const maxOutputTailChars = options?.maxOutputTailChars ?? MAX_TAIL_CHARS;\n const { Daytona } = await import(\"@daytona/sdk\");\n\n const client: DaytonaClient = new Daytona(toDaytonaConfig(options));\n // Pass the resolved env (env resolver + provider + agent) to the\n // sandbox. Explicit `create.envVars` win, as the most specific source.\n const createParams = options?.create;\n const envVars = { ...createOptions.env, ...createParams?.envVars };\n // `client.create` is overloaded per params shape, so call the overload\n // that matches instead of passing the union.\n const sandbox =\n createParams !== undefined && \"image\" in createParams\n ? await client.create({ ...createParams, envVars })\n : await client.create({ ...createParams, envVars });\n\n const worktreePath = await createWorkspaceFolder(sandbox);\n\n const context = { sandbox, worktreePath, maxOutputTailChars };\n return {\n worktreePath,\n sandboxId: sandbox.id,\n exec: async (command: string, opts?: DaytonaExecOptions) =>\n daytonaExec(context, command, opts),\n copyIn: async (hostPath: string, sandboxPath: string) =>\n copyInToSandbox(sandbox, hostPath, sandboxPath),\n copyFileOut: async (\n sandboxPath: string,\n hostPath: string,\n ): Promise<void> => {\n await sandbox.fs.downloadFile(sandboxPath, hostPath);\n },\n\n close: async (): Promise<void> => {\n await client.delete(sandbox);\n },\n };\n },\n });\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/sandboxes/daytonaFiles.ts","../../src/sandboxes/daytonaSession.ts","../../src/sandboxes/daytona.ts"],"names":[],"mappings":";;;;;;;AAaO,IAAM,qBAAA,GAAwB,OACnC,OAAA,KACoB;AACpB,EAAA,MAAM,OAAA,GACH,MAAM,OAAA,CAAQ,UAAA,MACd,MAAM,OAAA,CAAQ,gBAAe,IAC9B,eAAA;AACF,EAAA,MAAM,YAAA,GAAe,KAAA,CAAM,IAAA,CAAK,OAAA,EAAS,WAAW,CAAA;AACpD,EAAA,MAAM,OAAA,CAAQ,EAAA,CAAG,YAAA,CAAa,YAAA,EAAc,KAAK,CAAA;AACjD,EAAA,OAAO,YAAA;AACT,CAAA;AAGA,IAAM,SAAA,GAAY,OAAO,GAAA,KAAmC;AA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AAM,OAAA,CAAQ,EAAA,CAAG,YAAA,CAAa,WAAA,EAAa,QAAQ,CAAA;AAAA,MACrD,CAAA;AAAA,MAEA,OAAO,YAA2B;AAChC,QAAA,MAAM,MAAA,CAAO,OAAO,OAAO,CAAA;AAAA,MAC7B;AAAA,KACF;AAAA,EACF;AACF,CAAC","file":"daytona.js","sourcesContent":["/** Daytona file transfer: the sandbox worktree folder and `copyIn`. */\n\nimport { readdir, stat } from \"node:fs/promises\";\nimport { join, posix, relative } from \"node:path\";\nimport type { Sandbox as DaytonaSandbox } from \"@daytona/sdk\";\n\n/**\n * Creates the sandbox's worktree folder and returns its path. It is a\n * subdirectory of the work dir, not the work dir itself: sync-in clones into\n * `${worktreePath}_clone` and then replaces worktreePath, which needs a\n * parent the sandbox user can write. On the default snapshot the work dir is\n * the user's home (/home/daytona), and /home is root-owned.\n */\nexport const createWorkspaceFolder = async (\n sandbox: DaytonaSandbox,\n): Promise<string> => {\n const workDir =\n (await sandbox.getWorkDir()) ??\n (await sandbox.getUserHomeDir()) ??\n \"/home/daytona\";\n const worktreePath = posix.join(workDir, \"workspace\");\n await sandbox.fs.createFolder(worktreePath, \"755\");\n return worktreePath;\n};\n\n/** Every file under `dir`, recursively. */\nconst walkFiles = async (dir: string): Promise<string[]> => {\n const entries = await readdir(dir, { withFileTypes: true });\n const nested = await Promise.all(\n entries.map(async (entry) => {\n const full = join(dir, entry.name);\n return entry.isDirectory() ? walkFiles(full) : [full];\n }),\n );\n return nested.flat();\n};\n\n/** Uploads a host file, or a directory's files, to `sandboxPath`. */\nexport const copyInToSandbox = async (\n sandbox: DaytonaSandbox,\n hostPath: string,\n sandboxPath: string,\n): Promise<void> => {\n const info = await stat(hostPath);\n if (!info.isDirectory()) {\n await sandbox.fs.uploadFile(hostPath, sandboxPath);\n return;\n }\n const files = await walkFiles(hostPath);\n if (files.length === 0) {\n return;\n }\n // One batched request, as `uploadFile` itself is `uploadFiles` of one file.\n await sandbox.fs.uploadFiles(\n files.map((file) => ({\n source: file,\n destination: join(sandboxPath, relative(hostPath, file)),\n })),\n );\n};\n","/**\n * Daytona session plumbing: preparing a command for `exec`, probing a\n * session's shell, and streaming a session command's logs.\n */\n\nimport type { Sandbox as DaytonaSandbox } from \"@daytona/sdk\";\nimport { BoundedTail } from \"../boundedTail.js\";\n\nconst shellEscape = (s: string): string =>\n `'${s.replaceAll(\"'\", String.raw`'\\''`)}'`;\n\n/** Options `exec` accepts. */\nexport interface DaytonaExecOptions {\n readonly onLine?: (line: string) => void;\n readonly cwd?: string;\n readonly sudo?: boolean;\n readonly stdin?: string;\n}\n\n/** The sandbox a handle drives, and the settings its `exec` needs. */\nexport interface DaytonaExecContext {\n readonly sandbox: DaytonaSandbox;\n readonly worktreePath: string;\n readonly maxOutputTailChars: number;\n}\n\n/**\n * `command` ready to run: wrapped in `sudo sh -c` when asked, and with any\n * stdin uploaded to a file in the sandbox and redirected in.\n */\nexport const prepareCommand = async (\n sandbox: DaytonaSandbox,\n command: string,\n opts: DaytonaExecOptions | undefined,\n): Promise<string> => {\n // Wrap the whole command in `sh -c`, so sudo elevates all of it\n // (`a && b`, not just `a`).\n const effectiveCommand =\n opts?.sudo === true ? `sudo sh -c ${shellEscape(command)}` : command;\n if (opts?.stdin === undefined) {\n return effectiveCommand;\n }\n // Daytona's exec APIs have no stdin channel: the command reads\n // EOF. So write stdin to a file in the sandbox and redirect it in\n // (a file, not an argument, keeps clear of the per-arg size\n // limit). The redirect opens the file before the group runs, so\n // the group can delete it straight away and leave nothing behind.\n const stdinPath = `/tmp/sandcastle-stdin-${crypto.randomUUID()}`;\n await sandbox.fs.uploadFile(Buffer.from(opts.stdin), stdinPath);\n return `{ rm -f ${stdinPath}; ${effectiveCommand}\\n} < ${stdinPath}`;\n};\n\n/** A running session command, and the file holding its shell's PID. */\nexport interface SessionCommand {\n readonly sessionId: string;\n readonly cmdId: string;\n readonly pidPath: string;\n}\n\n/**\n * Whether a session's shell is still `alive`; if not, whether its command\n * `exited` with a recorded exit code or was `lost` without one.\n */\nexport const probeSessionShell = async (\n sandbox: DaytonaSandbox,\n { sessionId, cmdId, pidPath }: SessionCommand,\n): Promise<\"alive\" | \"exited\" | \"lost\"> => {\n const alive = await sandbox.process\n .executeCommand(`test ! -f ${pidPath} || kill -0 \"$(cat ${pidPath})\"`)\n .then((r) => r.exitCode === 0)\n .catch(() => true);\n if (alive) {\n return \"alive\";\n }\n const cmd = await sandbox.process\n .getSessionCommand(sessionId, cmdId)\n .catch(() => undefined);\n return typeof cmd?.exitCode === \"number\" ? \"exited\" : \"lost\";\n};\n\n/**\n * Streams a running session command's stdout to `onLine`, line by line,\n * keeping a bounded tail of stdout and stderr. `done` settles once the log\n * stream closes; `flush` then emits any final unterminated line.\n */\nexport const streamSessionLogs = (\n { sandbox, maxOutputTailChars }: DaytonaExecContext,\n { sessionId, cmdId }: { readonly sessionId: string; readonly cmdId: string },\n onLine: (line: string) => void,\n) => {\n const stdoutTail = new BoundedTail(maxOutputTailChars, \"\\n\");\n const stderrTail = new BoundedTail(maxOutputTailChars, \"\");\n let partial = \"\";\n const done = sandbox.process.getSessionCommandLogs(\n sessionId,\n cmdId,\n (chunk: string) => {\n const lines = (partial + chunk).split(\"\\n\");\n partial = lines.pop() ?? \"\";\n for (const line of lines) {\n stdoutTail.push(line);\n onLine(line);\n }\n },\n (chunk: string) => {\n stderrTail.push(chunk);\n },\n );\n const flush = () => {\n if (partial) {\n stdoutTail.push(partial);\n onLine(partial);\n }\n };\n return { done, flush, stdoutTail, stderrTail };\n};\n","/**\n * Daytona isolated sandbox provider.\n *\n * Creates ephemeral Daytona sandboxes via `@daytona/sdk`.\n * Requires `@daytona/sdk` as a peer dependency.\n */\n\nimport { createIsolatedSandboxProvider } from \"../SandboxProvider.js\";\nimport type {\n ExecResult,\n IsolatedSandboxHandle,\n IsolatedSandboxProvider,\n} from \"../SandboxProvider.js\";\nimport { MAX_TAIL_CHARS } from \"../boundedTail.js\";\nimport { copyInToSandbox, createWorkspaceFolder } from \"./daytonaFiles.js\";\nimport {\n prepareCommand,\n probeSessionShell,\n streamSessionLogs,\n} from \"./daytonaSession.js\";\nimport type {\n DaytonaExecContext,\n DaytonaExecOptions,\n SessionCommand,\n} from \"./daytonaSession.js\";\n\nimport type {\n Daytona as DaytonaClient,\n DaytonaConfig,\n Sandbox as DaytonaSandbox,\n CreateSandboxFromImageParams,\n CreateSandboxFromSnapshotParams,\n} from \"@daytona/sdk\";\n\n/** Options for the Daytona sandbox provider. */\nexport interface DaytonaOptions {\n /**\n * Daytona API key for authentication.\n * Falls back to the `DAYTONA_API_KEY` environment variable if not provided.\n */\n readonly apiKey?: string;\n\n /**\n * Daytona API URL.\n * Falls back to the `DAYTONA_API_URL` environment variable if not provided.\n */\n readonly apiUrl?: string;\n\n /**\n * Target environment for sandboxes.\n * Falls back to the `DAYTONA_TARGET` environment variable if not provided.\n */\n readonly target?: string;\n\n /**\n * Options passed through to the Daytona SDK when creating a sandbox.\n * Supports both image-based and snapshot-based creation.\n */\n readonly create?:\n | CreateSandboxFromImageParams\n | CreateSandboxFromSnapshotParams;\n\n /** Environment variables injected by this provider. Merged at launch time with env resolver and agent provider env. */\n readonly env?: Record<string, string>;\n\n /**\n * Maximum number of characters of streamed `exec` output retained per stream\n * (stdout and stderr) when an `onLine` callback is supplied (default: 64KiB).\n *\n * Output is delivered live to `onLine` regardless; this only bounds the tail\n * returned in `ExecResult`, preventing a long-running agent's output from\n * overflowing V8's max string length and crashing the run.\n */\n readonly maxOutputTailChars?: number;\n}\n\n/** How often a streamed `exec` checks that its session shell is still alive. */\nconst SESSION_WATCH_INTERVAL_MS = 15_000;\n\n/** The Daytona client config: only the connection options that are set. */\nconst toDaytonaConfig = (options?: DaytonaOptions): DaytonaConfig => {\n const { apiKey, apiUrl, target } = options ?? {};\n const config: DaytonaConfig = {};\n if (apiKey !== undefined && apiKey !== \"\") {\n config.apiKey = apiKey;\n }\n if (apiUrl !== undefined && apiUrl !== \"\") {\n config.apiUrl = apiUrl;\n }\n if (target !== undefined && target !== \"\") {\n config.target = target;\n }\n return config;\n};\n\n/**\n * Watches a session's shell: if it dies (killed, say) the log stream would\n * wait forever, so once it is gone `gone` settles: it fails if the command\n * recorded no exit code. A missing PID file counts as alive, so it can never\n * fail a command. Call `stop` once the race is over. An unexpected throw\n * while checking rejects `gone` instead of escaping as an unhandled\n * rejection from the timer.\n */\nconst watchSessionShell = (\n sandbox: DaytonaSandbox,\n session: SessionCommand,\n command: string,\n): { readonly gone: Promise<void>; readonly stop: () => void } => {\n let watchTimer: ReturnType<typeof setTimeout> | undefined;\n let watching = true;\n const gone = new Promise<void>((resolve, reject) => {\n const scheduleCheck = () => {\n watchTimer = setTimeout(() => {\n check().catch(reject);\n }, SESSION_WATCH_INTERVAL_MS);\n };\n const check = async () => {\n const state = await probeSessionShell(sandbox, session);\n if (!watching) {\n return;\n }\n if (state === \"alive\") {\n scheduleCheck();\n return;\n }\n if (state === \"exited\") {\n resolve();\n return;\n }\n reject(\n new Error(\n `Daytona session shell exited before the command finished, so its exit code is unknown: ${command}`,\n ),\n );\n };\n scheduleCheck();\n });\n return {\n gone,\n stop: () => {\n watching = false;\n clearTimeout(watchTimer);\n },\n };\n};\n\n/**\n * Runs `command` in a fresh session, streaming its stdout to `onLine`.\n *\n * A session runs its commands in one long-lived shell, which records each\n * command's exit code once it returns. A command that ends that shell (a\n * top-level `exit`) never gets one, and its log stream never closes. So the\n * command runs in a subshell, where `exit` ends only the subshell. The\n * newline before `)` keeps a trailing comment from swallowing it. The\n * session shell's PID goes to a file, to check it is still alive.\n */\nconst execStreaming = async (\n context: DaytonaExecContext,\n {\n command,\n effectiveCommand,\n cwd,\n }: {\n readonly command: string;\n readonly effectiveCommand: string;\n readonly cwd: string;\n },\n onLine: (line: string) => void,\n): Promise<ExecResult> => {\n const { sandbox } = context;\n const sessionId = `sandcastle-${crypto.randomUUID()}`;\n const pidPath = `/tmp/${sessionId}.pid`;\n await sandbox.process.createSession(sessionId);\n try {\n const { cmdId } = await sandbox.process.executeSessionCommand(sessionId, {\n command: `echo $$ > ${pidPath}; ( cd ${cwd} && ${effectiveCommand}\\n)`,\n async: true,\n });\n const logs = streamSessionLogs(context, { sessionId, cmdId }, onLine);\n // Once the race below is lost, a late failure of the stream\n // must not surface as an unhandled rejection.\n logs.done.catch(() => undefined);\n const shell = watchSessionShell(\n sandbox,\n { sessionId, cmdId, pidPath },\n command,\n );\n try {\n await Promise.race([logs.done, shell.gone]);\n } finally {\n shell.stop();\n }\n logs.flush();\n const cmdInfo = await sandbox.process.getSessionCommand(sessionId, cmdId);\n return {\n stdout: logs.stdoutTail.toString(),\n stderr: logs.stderrTail.toString(),\n exitCode: cmdInfo.exitCode ?? 0,\n };\n } finally {\n await sandbox.process.deleteSession(sessionId).catch(() => undefined);\n await sandbox.process\n .executeCommand(`rm -f ${pidPath}`)\n .catch(() => undefined);\n }\n};\n\n/** A handle's `exec`: streamed through a session with `onLine`, else plain. */\nconst daytonaExec = async (\n context: DaytonaExecContext,\n command: string,\n opts?: DaytonaExecOptions,\n): Promise<ExecResult> => {\n const { sandbox, worktreePath } = context;\n const effectiveCommand = await prepareCommand(sandbox, command, opts);\n const cwd = opts?.cwd ?? worktreePath;\n if (opts?.onLine) {\n return execStreaming(\n context,\n { command, effectiveCommand, cwd },\n opts.onLine,\n );\n }\n const response = await sandbox.process.executeCommand(effectiveCommand, cwd);\n // `executeCommand` merges stdout and stderr into `result` and has\n // no separate stderr. On failure, surface that output as stderr\n // too, so the error says why the command failed, not just its exit\n // code.\n return {\n stdout: response.result,\n stderr: response.exitCode === 0 ? \"\" : response.result,\n exitCode: response.exitCode,\n };\n};\n\n/**\n * Create a Daytona isolated sandbox provider.\n *\n * Sandboxes are ephemeral — each `create()` call spins up a new Daytona\n * sandbox and `close()` destroys it.\n *\n * @example\n * ```ts\n * import { daytona } from \"@ai-hero/sandcastle/sandboxes/daytona\";\n *\n * const provider = daytona({ apiKey: \"dyt_my_key\" });\n * ```\n */\nexport const daytona = (options?: DaytonaOptions): IsolatedSandboxProvider =>\n createIsolatedSandboxProvider({\n name: \"daytona\",\n env: options?.env,\n create: async (createOptions): Promise<IsolatedSandboxHandle> => {\n const maxOutputTailChars = options?.maxOutputTailChars ?? MAX_TAIL_CHARS;\n const { Daytona } = await import(\"@daytona/sdk\");\n\n const client: DaytonaClient = new Daytona(toDaytonaConfig(options));\n // Pass the resolved env (env resolver + provider + agent) to the\n // sandbox. Explicit `create.envVars` win, as the most specific source.\n const createParams = options?.create;\n const envVars = { ...createOptions.env, ...createParams?.envVars };\n // `client.create` is overloaded per params shape, so call the overload\n // that matches instead of passing the union.\n const sandbox =\n createParams !== undefined && \"image\" in createParams\n ? await client.create({ ...createParams, envVars })\n : await client.create({ ...createParams, envVars });\n\n const worktreePath = await createWorkspaceFolder(sandbox);\n\n const context = { sandbox, worktreePath, maxOutputTailChars };\n return {\n worktreePath,\n sandboxId: sandbox.id,\n exec: async (command: string, opts?: DaytonaExecOptions) =>\n daytonaExec(context, command, opts),\n copyIn: async (hostPath: string, sandboxPath: string) =>\n copyInToSandbox(sandbox, hostPath, sandboxPath),\n copyFileOut: async (\n sandboxPath: string,\n hostPath: string,\n ): Promise<void> => {\n await sandbox.fs.downloadFile(sandboxPath, hostPath);\n },\n\n close: async (): Promise<void> => {\n await client.delete(sandbox);\n },\n };\n },\n });\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { S as SelinuxLabel, L as LinuxCapability } from '../LinuxCapability-B_PQfsY_.js';
|
|
2
2
|
export { d as defaultImageName } from '../LinuxCapability-B_PQfsY_.js';
|
|
3
|
-
import { S as SandboxProvider } from '../SandboxProvider-
|
|
3
|
+
import { S as SandboxProvider } from '../SandboxProvider-CwRLxIXZ.js';
|
|
4
4
|
import { M as MountConfig } from '../MountConfig-CmXclHA5.js';
|
|
5
5
|
|
|
6
6
|
/**
|
|
@@ -112,6 +112,28 @@ interface DockerOptions {
|
|
|
112
112
|
* When omitted, no `--cpus` flag is added and the container is unconstrained.
|
|
113
113
|
*/
|
|
114
114
|
readonly cpus?: number;
|
|
115
|
+
/**
|
|
116
|
+
* Limit the memory available to the container, via `--memory`.
|
|
117
|
+
*
|
|
118
|
+
* Accepts Docker memory strings:
|
|
119
|
+
*
|
|
120
|
+
* - `"2g"` → `--memory 2g --memory-swap 2g`
|
|
121
|
+
* - `"512m"` → `--memory 512m --memory-swap 512m`
|
|
122
|
+
*
|
|
123
|
+
* `--memory-swap` is set to the same value, making this a hard cap with no
|
|
124
|
+
* swap headroom. When omitted, no memory flags are added and the container
|
|
125
|
+
* is unconstrained.
|
|
126
|
+
*/
|
|
127
|
+
readonly memory?: string;
|
|
128
|
+
/**
|
|
129
|
+
* Limit the number of processes in the container, via `--pids-limit`.
|
|
130
|
+
*
|
|
131
|
+
* - `256` → `--pids-limit 256`
|
|
132
|
+
*
|
|
133
|
+
* Useful against fork bombs in untrusted workloads. When omitted, no
|
|
134
|
+
* `--pids-limit` flag is added.
|
|
135
|
+
*/
|
|
136
|
+
readonly pidsLimit?: number;
|
|
115
137
|
}
|
|
116
138
|
/**
|
|
117
139
|
* Create a Docker sandbox provider.
|
package/dist/sandboxes/docker.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';
|
|
2
|
-
export { docker } from '../chunk-
|
|
3
|
-
|
|
2
|
+
export { docker } from '../chunk-WYOGXC72.js';
|
|
3
|
+
import '../chunk-4GZMUHVO.js';
|
|
4
|
+
export { defaultImageName } from '../chunk-7PHPLDVS.js';
|
|
4
5
|
import '../chunk-EXYXBRCX.js';
|
|
5
|
-
import '../chunk-
|
|
6
|
-
import '../chunk-
|
|
7
|
-
import '../chunk-
|
|
6
|
+
import '../chunk-YDQW5IOY.js';
|
|
7
|
+
import '../chunk-JEQ4IVQM.js';
|
|
8
|
+
import '../chunk-4BB7DNPW.js';
|
|
8
9
|
import '../chunk-6NQPCXSG.js';
|
|
9
10
|
|
|
10
11
|
createRequire(import.meta.url);
|
package/dist/sandboxes/e2b.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { SandboxOpts } from 'e2b';
|
|
2
|
-
import { I as IsolatedSandboxProvider } from '../SandboxProvider-
|
|
2
|
+
import { I as IsolatedSandboxProvider } from '../SandboxProvider-CwRLxIXZ.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* E2B isolated sandbox provider — wraps the `e2b` SDK into a SandboxProvider.
|
package/dist/sandboxes/e2b.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';
|
|
2
|
-
import { shellEscape } from '../chunk-
|
|
3
|
-
import '../chunk-
|
|
4
|
-
import '../chunk-
|
|
5
|
-
import { createIsolatedSandboxProvider } from '../chunk-
|
|
2
|
+
import { shellEscape } from '../chunk-SAQXFLO2.js';
|
|
3
|
+
import '../chunk-YDQW5IOY.js';
|
|
4
|
+
import '../chunk-JEQ4IVQM.js';
|
|
5
|
+
import { createIsolatedSandboxProvider } from '../chunk-4BB7DNPW.js';
|
|
6
6
|
import { MAX_TAIL_CHARS, BoundedTail } from '../chunk-6NQPCXSG.js';
|
|
7
7
|
import { mkdir, writeFile, stat, rm, readFile } from 'fs/promises';
|
|
8
8
|
import { dirname, join } from 'path';
|
package/dist/sandboxes/modal.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';
|
|
2
|
-
import { createIsolatedSandboxProvider } from '../chunk-
|
|
2
|
+
import { createIsolatedSandboxProvider } from '../chunk-4BB7DNPW.js';
|
|
3
3
|
import { MAX_TAIL_CHARS, BoundedTail } from '../chunk-6NQPCXSG.js';
|
|
4
4
|
import { stat, readdir } from 'fs/promises';
|
|
5
5
|
import { relative, sep, posix, join } from 'path';
|