@ai-hero/sandcastle 0.13.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.
Files changed (77) hide show
  1. package/README.md +3 -3
  2. package/dist/{SandboxProvider-YCL97qco.d.ts → SandboxProvider-CwRLxIXZ.d.ts} +5 -41
  3. package/dist/{chunk-XCYK7I45.js → chunk-4BB7DNPW.js} +3 -3
  4. package/dist/chunk-4BB7DNPW.js.map +1 -0
  5. package/dist/chunk-4GZMUHVO.js +60 -0
  6. package/dist/chunk-4GZMUHVO.js.map +1 -0
  7. package/dist/{chunk-A4C2FG74.js → chunk-7JUTKCHL.js} +43 -42
  8. package/dist/chunk-7JUTKCHL.js.map +1 -0
  9. package/dist/chunk-7PHPLDVS.js +284 -0
  10. package/dist/chunk-7PHPLDVS.js.map +1 -0
  11. package/dist/{chunk-NMQ5Z6YG.js → chunk-BXLS4HRY.js} +15 -4
  12. package/dist/chunk-BXLS4HRY.js.map +1 -0
  13. package/dist/chunk-EM4QNWKF.js +3161 -0
  14. package/dist/chunk-EM4QNWKF.js.map +1 -0
  15. package/dist/chunk-EXYXBRCX.js +60 -0
  16. package/dist/chunk-EXYXBRCX.js.map +1 -0
  17. package/dist/{chunk-LWNC4UTZ.js → chunk-JEQ4IVQM.js} +1520 -5375
  18. package/dist/chunk-JEQ4IVQM.js.map +1 -0
  19. package/dist/{chunk-XCWKLDH4.js → chunk-L3BU47F6.js} +3 -3
  20. package/dist/{chunk-XCWKLDH4.js.map → chunk-L3BU47F6.js.map} +1 -1
  21. package/dist/{chunk-7N7AMUYA.js → chunk-PTJEKJPQ.js} +7 -5
  22. package/dist/chunk-PTJEKJPQ.js.map +1 -0
  23. package/dist/chunk-SAQXFLO2.js +1268 -0
  24. package/dist/chunk-SAQXFLO2.js.map +1 -0
  25. package/dist/{chunk-767EAJVT.js → chunk-TBVRAXYF.js} +3 -3
  26. package/dist/{chunk-767EAJVT.js.map → chunk-TBVRAXYF.js.map} +1 -1
  27. package/dist/{chunk-J5J5YJ5S.js → chunk-VUOXFCWO.js} +3 -3
  28. package/dist/{chunk-J5J5YJ5S.js.map → chunk-VUOXFCWO.js.map} +1 -1
  29. package/dist/{chunk-U42XXICG.js → chunk-WYOGXC72.js} +47 -82
  30. package/dist/chunk-WYOGXC72.js.map +1 -0
  31. package/dist/chunk-YDQW5IOY.js +799 -0
  32. package/dist/chunk-YDQW5IOY.js.map +1 -0
  33. package/dist/index.d.ts +51 -4
  34. package/dist/index.js +892 -2018
  35. package/dist/index.js.map +1 -1
  36. package/dist/main.js +322 -251
  37. package/dist/main.js.map +1 -1
  38. package/dist/sandboxes/bwrap.d.ts +1 -1
  39. package/dist/sandboxes/bwrap.js +9 -14
  40. package/dist/sandboxes/bwrap.js.map +1 -1
  41. package/dist/sandboxes/daytona.d.ts +1 -1
  42. package/dist/sandboxes/daytona.js +183 -136
  43. package/dist/sandboxes/daytona.js.map +1 -1
  44. package/dist/sandboxes/docker.d.ts +23 -1
  45. package/dist/sandboxes/docker.js +7 -3
  46. package/dist/sandboxes/e2b.d.ts +41 -0
  47. package/dist/sandboxes/e2b.js +202 -0
  48. package/dist/sandboxes/e2b.js.map +1 -0
  49. package/dist/sandboxes/modal.d.ts +78 -0
  50. package/dist/sandboxes/modal.js +171 -0
  51. package/dist/sandboxes/modal.js.map +1 -0
  52. package/dist/sandboxes/no-sandbox.d.ts +1 -1
  53. package/dist/sandboxes/no-sandbox.js +1 -1
  54. package/dist/sandboxes/podman.d.ts +27 -4
  55. package/dist/sandboxes/podman.js +19 -43
  56. package/dist/sandboxes/podman.js.map +1 -1
  57. package/dist/sandboxes/seatbelt.d.ts +2 -2
  58. package/dist/sandboxes/seatbelt.js +10 -7
  59. package/dist/sandboxes/seatbelt.js.map +1 -1
  60. package/dist/sandboxes/sprites.d.ts +54 -0
  61. package/dist/sandboxes/sprites.js +219 -0
  62. package/dist/sandboxes/sprites.js.map +1 -0
  63. package/dist/sandboxes/vercel.d.ts +10 -1
  64. package/dist/sandboxes/vercel.js +74 -46
  65. package/dist/sandboxes/vercel.js.map +1 -1
  66. package/dist/templates/parallel-planner/main.mts +43 -21
  67. package/dist/templates/parallel-planner-with-review/main.mts +55 -27
  68. package/dist/templates/sequential-reviewer/main.mts +1 -1
  69. package/package.json +36 -4
  70. package/dist/chunk-4EIVTSOZ.js +0 -93
  71. package/dist/chunk-4EIVTSOZ.js.map +0 -1
  72. package/dist/chunk-7N7AMUYA.js.map +0 -1
  73. package/dist/chunk-A4C2FG74.js.map +0 -1
  74. package/dist/chunk-LWNC4UTZ.js.map +0 -1
  75. package/dist/chunk-NMQ5Z6YG.js.map +0 -1
  76. package/dist/chunk-U42XXICG.js.map +0 -1
  77. package/dist/chunk-XCYK7I45.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { B as BindMountSandboxProvider } from '../SandboxProvider-YCL97qco.js';
1
+ import { B as BindMountSandboxProvider } from '../SandboxProvider-CwRLxIXZ.js';
2
2
  import { M as MountConfig } from '../MountConfig-CmXclHA5.js';
3
3
 
4
4
  /**
@@ -1,15 +1,17 @@
1
1
  import { createRequire } from 'node:module';
2
- import { resolveIdentityMounts, copyCreatingParents, collectOutput, hostPathToolchainFromEnv } from '../chunk-NMQ5Z6YG.js';
3
- import { markNativeSandboxProvider } from '../chunk-XCWKLDH4.js';
4
- import { assertBwrapUsable } from '../chunk-767EAJVT.js';
5
- import { NodeFileSystem_exports } from '../chunk-A4C2FG74.js';
6
- import { Effect_exports, FileSystem_exports, Option_exports, BwrapError, registerShutdown } from '../chunk-LWNC4UTZ.js';
7
- import { createBindMountSandboxProvider } from '../chunk-XCYK7I45.js';
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';
8
11
  import { MAX_TAIL_CHARS } from '../chunk-6NQPCXSG.js';
9
12
  import { spawn } from 'child_process';
10
13
  import { once } from 'events';
11
14
  import { join, posix } from 'path';
12
- import { rmSync } from 'fs';
13
15
 
14
16
  createRequire(import.meta.url);
15
17
 
@@ -183,13 +185,6 @@ var toHostPath = (path, dirs, mounts) => {
183
185
  }
184
186
  return p;
185
187
  };
186
- var registerNativeSandboxShutdown = (killAll, dirs) => registerShutdown(() => {
187
- killAll();
188
- try {
189
- rmSync(dirs.root, { recursive: true, force: true });
190
- } catch {
191
- }
192
- });
193
188
 
194
189
  // src/sandboxes/bwrap.ts
195
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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AE,IAAA,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 * 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,EAC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AA,EAAmB;AACnB,MAAA,MAAM,iBAAA,CAAkB,IAAI,CAAA,CAAE,IAAA,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,4 +1,4 @@
1
- import { I as IsolatedSandboxProvider } from '../SandboxProvider-YCL97qco.js';
1
+ import { I as IsolatedSandboxProvider } from '../SandboxProvider-CwRLxIXZ.js';
2
2
  import { CreateSandboxFromImageParams, CreateSandboxFromSnapshotParams } from '@daytona/sdk';
3
3
 
4
4
  /**
@@ -1,11 +1,93 @@
1
1
  import { createRequire } from 'node:module';
2
- import { createIsolatedSandboxProvider } from '../chunk-XCYK7I45.js';
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, relative, join } from 'path';
5
+ import { posix, join, relative } from 'path';
6
6
 
7
7
  createRequire(import.meta.url);
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;
29
+ }
30
+ const files = await walkFiles(hostPath);
31
+ if (files.length === 0) {
32
+ return;
33
+ }
34
+ await sandbox.fs.uploadFiles(
35
+ files.map((file) => ({
36
+ source: file,
37
+ destination: join(sandboxPath, relative(hostPath, file))
38
+ }))
39
+ );
40
+ };
41
+
42
+ // src/sandboxes/daytonaSession.ts
8
43
  var shellEscape = (s) => `'${s.replaceAll("'", String.raw`'\''`)}'`;
44
+ var prepareCommand = async (sandbox, command, opts) => {
45
+ const effectiveCommand = opts?.sudo === true ? `sudo sh -c ${shellEscape(command)}` : command;
46
+ if (opts?.stdin === void 0) {
47
+ return effectiveCommand;
48
+ }
49
+ const stdinPath = `/tmp/sandcastle-stdin-${crypto.randomUUID()}`;
50
+ await sandbox.fs.uploadFile(Buffer.from(opts.stdin), stdinPath);
51
+ return `{ rm -f ${stdinPath}; ${effectiveCommand}
52
+ } < ${stdinPath}`;
53
+ };
54
+ var probeSessionShell = async (sandbox, { sessionId, cmdId, pidPath }) => {
55
+ const alive = await sandbox.process.executeCommand(`test ! -f ${pidPath} || kill -0 "$(cat ${pidPath})"`).then((r) => r.exitCode === 0).catch(() => true);
56
+ if (alive) {
57
+ return "alive";
58
+ }
59
+ const cmd = await sandbox.process.getSessionCommand(sessionId, cmdId).catch(() => void 0);
60
+ return typeof cmd?.exitCode === "number" ? "exited" : "lost";
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
9
91
  var SESSION_WATCH_INTERVAL_MS = 15e3;
10
92
  var toDaytonaConfig = (options) => {
11
93
  const { apiKey, apiUrl, target } = options ?? {};
@@ -21,6 +103,101 @@ var toDaytonaConfig = (options) => {
21
103
  }
22
104
  return config;
23
105
  };
106
+ var watchSessionShell = (sandbox, session, command) => {
107
+ let watchTimer;
108
+ let watching = true;
109
+ const gone = new Promise((resolve, reject) => {
110
+ const scheduleCheck = () => {
111
+ watchTimer = setTimeout(() => {
112
+ check().catch(reject);
113
+ }, SESSION_WATCH_INTERVAL_MS);
114
+ };
115
+ const check = async () => {
116
+ const state = await probeSessionShell(sandbox, session);
117
+ if (!watching) {
118
+ return;
119
+ }
120
+ if (state === "alive") {
121
+ scheduleCheck();
122
+ return;
123
+ }
124
+ if (state === "exited") {
125
+ resolve();
126
+ return;
127
+ }
128
+ reject(
129
+ new Error(
130
+ `Daytona session shell exited before the command finished, so its exit code is unknown: ${command}`
131
+ )
132
+ );
133
+ };
134
+ scheduleCheck();
135
+ });
136
+ return {
137
+ gone,
138
+ stop: () => {
139
+ watching = false;
140
+ clearTimeout(watchTimer);
141
+ }
142
+ };
143
+ };
144
+ var execStreaming = async (context, {
145
+ command,
146
+ effectiveCommand,
147
+ cwd
148
+ }, onLine) => {
149
+ const { sandbox } = context;
150
+ const sessionId = `sandcastle-${crypto.randomUUID()}`;
151
+ const pidPath = `/tmp/${sessionId}.pid`;
152
+ await sandbox.process.createSession(sessionId);
153
+ try {
154
+ const { cmdId } = await sandbox.process.executeSessionCommand(sessionId, {
155
+ command: `echo $$ > ${pidPath}; ( cd ${cwd} && ${effectiveCommand}
156
+ )`,
157
+ async: true
158
+ });
159
+ const logs = streamSessionLogs(context, { sessionId, cmdId }, onLine);
160
+ logs.done.catch(() => void 0);
161
+ const shell = watchSessionShell(
162
+ sandbox,
163
+ { sessionId, cmdId, pidPath },
164
+ command
165
+ );
166
+ try {
167
+ await Promise.race([logs.done, shell.gone]);
168
+ } finally {
169
+ shell.stop();
170
+ }
171
+ logs.flush();
172
+ const cmdInfo = await sandbox.process.getSessionCommand(sessionId, cmdId);
173
+ return {
174
+ stdout: logs.stdoutTail.toString(),
175
+ stderr: logs.stderrTail.toString(),
176
+ exitCode: cmdInfo.exitCode ?? 0
177
+ };
178
+ } finally {
179
+ await sandbox.process.deleteSession(sessionId).catch(() => void 0);
180
+ await sandbox.process.executeCommand(`rm -f ${pidPath}`).catch(() => void 0);
181
+ }
182
+ };
183
+ var daytonaExec = async (context, command, opts) => {
184
+ const { sandbox, worktreePath } = context;
185
+ const effectiveCommand = await prepareCommand(sandbox, command, opts);
186
+ const cwd = opts?.cwd ?? worktreePath;
187
+ if (opts?.onLine) {
188
+ return execStreaming(
189
+ context,
190
+ { command, effectiveCommand, cwd },
191
+ opts.onLine
192
+ );
193
+ }
194
+ const response = await sandbox.process.executeCommand(effectiveCommand, cwd);
195
+ return {
196
+ stdout: response.result,
197
+ stderr: response.exitCode === 0 ? "" : response.result,
198
+ exitCode: response.exitCode
199
+ };
200
+ };
24
201
  var daytona = (options) => createIsolatedSandboxProvider({
25
202
  name: "daytona",
26
203
  env: options?.env,
@@ -31,143 +208,13 @@ var daytona = (options) => createIsolatedSandboxProvider({
31
208
  const createParams = options?.create;
32
209
  const envVars = { ...createOptions.env, ...createParams?.envVars };
33
210
  const sandbox = createParams !== void 0 && "image" in createParams ? await client.create({ ...createParams, envVars }) : await client.create({ ...createParams, envVars });
34
- const workDir = await sandbox.getWorkDir() ?? await sandbox.getUserHomeDir() ?? "/home/daytona";
35
- const worktreePath = posix.join(workDir, "workspace");
36
- await sandbox.fs.createFolder(worktreePath, "755");
211
+ const worktreePath = await createWorkspaceFolder(sandbox);
212
+ const context = { sandbox, worktreePath, maxOutputTailChars };
37
213
  return {
38
214
  worktreePath,
39
215
  sandboxId: sandbox.id,
40
- exec: async (command, opts) => {
41
- let effectiveCommand = opts?.sudo === true ? `sudo sh -c ${shellEscape(command)}` : command;
42
- if (opts?.stdin !== void 0) {
43
- const stdinPath = `/tmp/sandcastle-stdin-${crypto.randomUUID()}`;
44
- await sandbox.fs.uploadFile(Buffer.from(opts.stdin), stdinPath);
45
- effectiveCommand = `{ rm -f ${stdinPath}; ${effectiveCommand}
46
- } < ${stdinPath}`;
47
- }
48
- if (opts?.onLine) {
49
- const { onLine } = opts;
50
- const sessionId = `sandcastle-${crypto.randomUUID()}`;
51
- const pidPath = `/tmp/${sessionId}.pid`;
52
- await sandbox.process.createSession(sessionId);
53
- try {
54
- const execResponse = await sandbox.process.executeSessionCommand(
55
- sessionId,
56
- {
57
- command: `echo $$ > ${pidPath}; ( cd ${opts?.cwd ?? worktreePath} && ${effectiveCommand}
58
- )`,
59
- async: true
60
- }
61
- );
62
- const { cmdId } = execResponse;
63
- const stdoutTail = new BoundedTail(maxOutputTailChars, "\n");
64
- const stderrTail = new BoundedTail(maxOutputTailChars, "");
65
- let partial = "";
66
- const logsDone = sandbox.process.getSessionCommandLogs(
67
- sessionId,
68
- cmdId,
69
- (chunk) => {
70
- const text = partial + chunk;
71
- const lines = text.split("\n");
72
- partial = lines.pop() ?? "";
73
- for (const line of lines) {
74
- stdoutTail.push(line);
75
- onLine(line);
76
- }
77
- },
78
- (chunk) => {
79
- stderrTail.push(chunk);
80
- }
81
- );
82
- logsDone.catch(() => {
83
- });
84
- let watchTimer;
85
- let watching = true;
86
- const sessionGone = new Promise((resolve, reject) => {
87
- const check = async () => {
88
- const alive = await sandbox.process.executeCommand(
89
- `test ! -f ${pidPath} || kill -0 "$(cat ${pidPath})"`
90
- ).then((r) => r.exitCode === 0).catch(() => true);
91
- const cmd = alive ? void 0 : await sandbox.process.getSessionCommand(sessionId, cmdId).catch(() => void 0);
92
- if (!watching) {
93
- return;
94
- }
95
- if (alive) {
96
- watchTimer = setTimeout(check, SESSION_WATCH_INTERVAL_MS);
97
- return;
98
- }
99
- if (typeof cmd?.exitCode === "number") {
100
- return resolve();
101
- }
102
- reject(
103
- new Error(
104
- `Daytona session shell exited before the command finished, so its exit code is unknown: ${command}`
105
- )
106
- );
107
- };
108
- watchTimer = setTimeout(check, SESSION_WATCH_INTERVAL_MS);
109
- });
110
- try {
111
- await Promise.race([logsDone, sessionGone]);
112
- } finally {
113
- watching = false;
114
- clearTimeout(watchTimer);
115
- }
116
- if (partial) {
117
- stdoutTail.push(partial);
118
- onLine(partial);
119
- }
120
- const cmdInfo = await sandbox.process.getSessionCommand(
121
- sessionId,
122
- cmdId
123
- );
124
- return {
125
- stdout: stdoutTail.toString(),
126
- stderr: stderrTail.toString(),
127
- exitCode: cmdInfo.exitCode ?? 0
128
- };
129
- } finally {
130
- await sandbox.process.deleteSession(sessionId).catch(() => {
131
- });
132
- await sandbox.process.executeCommand(`rm -f ${pidPath}`).catch(() => {
133
- });
134
- }
135
- }
136
- const response = await sandbox.process.executeCommand(
137
- effectiveCommand,
138
- opts?.cwd ?? worktreePath
139
- );
140
- return {
141
- stdout: response.result,
142
- stderr: response.exitCode === 0 ? "" : response.result,
143
- exitCode: response.exitCode
144
- };
145
- },
146
- copyIn: async (hostPath, sandboxPath) => {
147
- const info = await stat(hostPath);
148
- if (info.isDirectory()) {
149
- const walk = async (dir) => {
150
- const entries = await readdir(dir, { withFileTypes: true });
151
- const files2 = [];
152
- for (const entry of entries) {
153
- const full = join(dir, entry.name);
154
- if (entry.isDirectory()) {
155
- files2.push(...await walk(full));
156
- } else {
157
- files2.push(full);
158
- }
159
- }
160
- return files2;
161
- };
162
- const files = await walk(hostPath);
163
- for (const file of files) {
164
- const rel = relative(hostPath, file);
165
- await sandbox.fs.uploadFile(file, join(sandboxPath, rel));
166
- }
167
- } else {
168
- await sandbox.fs.uploadFile(hostPath, sandboxPath);
169
- }
170
- },
216
+ exec: async (command, opts) => daytonaExec(context, command, opts),
217
+ copyIn: async (hostPath, sandboxPath) => copyInToSandbox(sandbox, hostPath, sandboxPath),
171
218
  copyFileOut: async (sandboxPath, hostPath) => {
172
219
  await sandbox.fs.downloadFile(sandboxPath, hostPath);
173
220
  },