@ai-hero/sandcastle 0.10.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +15 -1316
  2. package/dist/LinuxCapability-B_PQfsY_.d.ts +32 -0
  3. package/dist/{SandboxProvider-EkSMuBp8.d.ts → SandboxProvider-YCL97qco.d.ts} +30 -3
  4. package/dist/chunk-4EIVTSOZ.js +93 -0
  5. package/dist/chunk-4EIVTSOZ.js.map +1 -0
  6. package/dist/{chunk-NGBM7T3E.js → chunk-6NQPCXSG.js} +5 -2
  7. package/dist/chunk-6NQPCXSG.js.map +1 -0
  8. package/dist/chunk-767EAJVT.js +112 -0
  9. package/dist/chunk-767EAJVT.js.map +1 -0
  10. package/dist/chunk-7N7AMUYA.js +353 -0
  11. package/dist/chunk-7N7AMUYA.js.map +1 -0
  12. package/dist/{chunk-52CIJF45.js → chunk-A4C2FG74.js} +258 -327
  13. package/dist/chunk-A4C2FG74.js.map +1 -0
  14. package/dist/chunk-J5J5YJ5S.js +50 -0
  15. package/dist/chunk-J5J5YJ5S.js.map +1 -0
  16. package/dist/{chunk-5VM5QZ26.js → chunk-LWNC4UTZ.js} +12097 -3252
  17. package/dist/chunk-LWNC4UTZ.js.map +1 -0
  18. package/dist/chunk-NMQ5Z6YG.js +148 -0
  19. package/dist/chunk-NMQ5Z6YG.js.map +1 -0
  20. package/dist/{chunk-NSFQW6ML.js → chunk-U42XXICG.js} +92 -85
  21. package/dist/chunk-U42XXICG.js.map +1 -0
  22. package/dist/chunk-XCWKLDH4.js +24 -0
  23. package/dist/chunk-XCWKLDH4.js.map +1 -0
  24. package/dist/{chunk-BIWNFKGV.js → chunk-XCYK7I45.js} +2 -2
  25. package/dist/chunk-XCYK7I45.js.map +1 -0
  26. package/dist/index.d.ts +335 -39
  27. package/dist/index.js +2854 -2090
  28. package/dist/index.js.map +1 -1
  29. package/dist/main.js +1006 -627
  30. package/dist/main.js.map +1 -1
  31. package/dist/sandboxes/bwrap.d.ts +58 -0
  32. package/dist/sandboxes/bwrap.js +293 -0
  33. package/dist/sandboxes/bwrap.js.map +1 -0
  34. package/dist/sandboxes/daytona.d.ts +1 -1
  35. package/dist/sandboxes/daytona.js +78 -17
  36. package/dist/sandboxes/daytona.js.map +1 -1
  37. package/dist/sandboxes/docker.d.ts +19 -5
  38. package/dist/sandboxes/docker.js +4 -4
  39. package/dist/sandboxes/no-sandbox.d.ts +2 -2
  40. package/dist/sandboxes/no-sandbox.js +2 -2
  41. package/dist/sandboxes/podman.d.ts +19 -5
  42. package/dist/sandboxes/podman.js +69 -56
  43. package/dist/sandboxes/podman.js.map +1 -1
  44. package/dist/sandboxes/seatbelt.d.ts +65 -0
  45. package/dist/sandboxes/seatbelt.js +422 -0
  46. package/dist/sandboxes/seatbelt.js.map +1 -0
  47. package/dist/sandboxes/vercel.d.ts +13 -6
  48. package/dist/sandboxes/vercel.js +195 -126
  49. package/dist/sandboxes/vercel.js.map +1 -1
  50. package/dist/templates/blank/main.mts +1 -1
  51. package/dist/templates/parallel-planner/main.mts +14 -23
  52. package/dist/templates/parallel-planner-with-review/main.mts +14 -16
  53. package/dist/templates/simple-loop/main.mts +1 -1
  54. package/package.json +34 -10
  55. package/dist/chunk-52CIJF45.js.map +0 -1
  56. package/dist/chunk-5VM5QZ26.js.map +0 -1
  57. package/dist/chunk-72UVAC7B.js +0 -99
  58. package/dist/chunk-72UVAC7B.js.map +0 -1
  59. package/dist/chunk-BIWNFKGV.js.map +0 -1
  60. package/dist/chunk-NGBM7T3E.js.map +0 -1
  61. package/dist/chunk-NSFQW6ML.js.map +0 -1
  62. package/dist/mountUtils-CCA-bbpK.d.ts +0 -25
@@ -0,0 +1,148 @@
1
+ import { createRequire } from 'node:module';
2
+ import { Effect_exports, FileSystem_exports, CopyError, Config_exports, resolveUserMounts, Option_exports } from './chunk-LWNC4UTZ.js';
3
+ import { BoundedTail } from './chunk-6NQPCXSG.js';
4
+ import { dirname, posix } from 'path';
5
+ import { createInterface } from 'readline';
6
+ import { homedir } from 'os';
7
+
8
+ createRequire(import.meta.url);
9
+ var collectOutput = (proc, onLine, maxTailChars) => {
10
+ const streaming = onLine !== void 0;
11
+ const stdout = streaming ? new BoundedTail(maxTailChars, "\n") : new BoundedTail(Infinity);
12
+ const stderr = new BoundedTail(streaming ? maxTailChars : Infinity);
13
+ if (onLine === void 0) {
14
+ proc.stdout.on("data", (chunk) => {
15
+ stdout.push(chunk.toString());
16
+ });
17
+ } else {
18
+ createInterface({ input: proc.stdout }).on("line", (line) => {
19
+ stdout.push(line);
20
+ onLine(line);
21
+ });
22
+ }
23
+ proc.stderr.on("data", (chunk) => {
24
+ stderr.push(chunk.toString());
25
+ });
26
+ return () => ({ stdout: stdout.toString(), stderr: stderr.toString() });
27
+ };
28
+ var copyCreatingParents = (from, to) => Effect_exports.gen(function* () {
29
+ const fs = yield* FileSystem_exports.FileSystem;
30
+ yield* fs.makeDirectory(dirname(to), { recursive: true });
31
+ yield* fs.copyFile(from, to);
32
+ }).pipe(
33
+ Effect_exports.mapError(
34
+ (e) => new CopyError({
35
+ message: `Couldn't copy ${from} to ${to}: ${e.message}`
36
+ })
37
+ )
38
+ );
39
+ var isWithin = (path, root) => root === "/" || path === root || path.startsWith(`${root}/`);
40
+ var isWithinAny = (path, roots) => roots.some((root) => isWithin(path, root));
41
+ var isHomeOrAncestor = (path, home) => isWithin(home, path);
42
+ var normalizeEntry = (entry) => {
43
+ const normalized = posix.normalize(entry);
44
+ return normalized.length > 1 && normalized.endsWith("/") ? normalized.slice(0, -1) : normalized;
45
+ };
46
+ var realPathOf = (fs, path) => Effect_exports.option(fs.realPath(path));
47
+ var isInNodeModules = (dir) => dir.split("/").includes("node_modules");
48
+ var installRootOf = (fs, file, home) => Effect_exports.gen(function* () {
49
+ const fileDir = posix.dirname(file);
50
+ let dir = fileDir;
51
+ while (isInNodeModules(dir) && !isHomeOrAncestor(dir, home)) {
52
+ const hasPackageJson = yield* fs.exists(posix.join(dir, "package.json")).pipe(Effect_exports.orElseSucceed(() => false));
53
+ if (hasPackageJson) {
54
+ return dir;
55
+ }
56
+ dir = posix.dirname(dir);
57
+ }
58
+ return fileDir;
59
+ });
60
+ var isRepoRoot = (fs, dir) => fs.exists(posix.join(dir, ".git")).pipe(Effect_exports.orElseSucceed(() => false));
61
+ var symlinkTargetsIn = (fs, dir) => Effect_exports.gen(function* () {
62
+ const names = yield* fs.readDirectory(dir).pipe(Effect_exports.orElseSucceed(() => []));
63
+ const targets = yield* Effect_exports.forEach(
64
+ names,
65
+ (name) => Effect_exports.gen(function* () {
66
+ const entry = posix.join(dir, name);
67
+ const link = yield* Effect_exports.option(fs.readLink(entry));
68
+ return Option_exports.isSome(link) ? yield* realPathOf(fs, entry) : Option_exports.none();
69
+ }),
70
+ { concurrency: 32 }
71
+ );
72
+ return targets.flatMap((t) => Option_exports.isSome(t) ? [t.value] : []);
73
+ });
74
+ var isRefused = (path, rules) => isHomeOrAncestor(path, rules.home) || isWithinAny(path, rules.deniedRoots);
75
+ var acceptEntry = (fs, entry, rules) => isRefused(entry, rules) ? Effect_exports.succeed(Option_exports.none()) : realPathOf(fs, entry).pipe(
76
+ Effect_exports.map(Option_exports.filter((real) => !isRefused(real, rules))),
77
+ Effect_exports.map(Option_exports.map((real) => ({ entry, real })))
78
+ );
79
+ var installRootsIn = (fs, dir, rules) => Effect_exports.gen(function* () {
80
+ const targets = (yield* symlinkTargetsIn(fs, dir)).filter(
81
+ (target) => !isWithin(target, dir) && !isWithinAny(target, rules.coveredRoots)
82
+ );
83
+ const roots = yield* Effect_exports.all(
84
+ targets.map((target) => installRootOf(fs, target, rules.home))
85
+ );
86
+ return yield* Effect_exports.filter(
87
+ roots.filter((root) => !isRefused(root, rules)),
88
+ (root) => Effect_exports.map(isRepoRoot(fs, root), (isRepo) => !isRepo)
89
+ );
90
+ });
91
+ var outermost = (dirs) => {
92
+ const unique = [...new Set(dirs)];
93
+ return unique.filter(
94
+ (dir) => !unique.some((other) => other !== dir && isWithin(dir, other))
95
+ );
96
+ };
97
+ var resolveHostPathToolchain = (input) => Effect_exports.gen(function* () {
98
+ const fs = yield* FileSystem_exports.FileSystem;
99
+ const rules = { ...input, home: normalizeEntry(input.home) };
100
+ const entries = [
101
+ ...new Set(
102
+ input.path.split(":").filter((entry) => entry.startsWith("/")).map((entry) => normalizeEntry(entry))
103
+ )
104
+ ];
105
+ const accepted = (yield* Effect_exports.all(
106
+ entries.map((entry) => acceptEntry(fs, entry, rules))
107
+ )).flatMap((a) => Option_exports.isSome(a) ? [a.value] : []);
108
+ const uncovered = accepted.filter(
109
+ (a) => !isWithinAny(a.real, rules.coveredRoots)
110
+ );
111
+ const installRoots = yield* Effect_exports.all(
112
+ [...new Set(accepted.map((a) => a.real))].map(
113
+ (dir) => installRootsIn(fs, dir, rules)
114
+ )
115
+ );
116
+ return {
117
+ pathEntries: accepted.map((a) => a.entry),
118
+ readableDirs: outermost([
119
+ ...uncovered.map((a) => a.real),
120
+ ...installRoots.flat()
121
+ ]),
122
+ symlinks: uncovered.filter(
123
+ (a) => a.real !== a.entry && !isWithinAny(a.entry, rules.coveredRoots)
124
+ ).map((a) => ({ path: a.entry, target: a.real }))
125
+ };
126
+ });
127
+ var hostPathToolchainFromEnv = (roots) => Effect_exports.gen(function* () {
128
+ const path = yield* Config_exports.string("PATH").pipe(Config_exports.withDefault(""));
129
+ return yield* resolveHostPathToolchain({ path, home: homedir(), ...roots });
130
+ }).pipe(Effect_exports.orDie);
131
+
132
+ // src/identityMounts.ts
133
+ var resolveIdentityMounts = (provider, mounts, sandboxHomedir) => resolveUserMounts(mounts, sandboxHomedir).map((resolved, i) => {
134
+ if (resolved.sandboxPath !== resolved.hostPath) {
135
+ const given = mounts[i];
136
+ throw new Error(
137
+ `${provider}() mounts appear at their host path, so sandboxPath must equal hostPath: got hostPath ${given?.hostPath ?? resolved.hostPath} (resolved to ${resolved.hostPath}) and sandboxPath ${given?.sandboxPath ?? resolved.sandboxPath} (resolved to ${resolved.sandboxPath}).`
138
+ );
139
+ }
140
+ return {
141
+ hostPath: resolved.hostPath,
142
+ readonly: resolved.readonly === true
143
+ };
144
+ });
145
+
146
+ export { collectOutput, copyCreatingParents, hostPathToolchainFromEnv, resolveIdentityMounts };
147
+ //# sourceMappingURL=chunk-NMQ5Z6YG.js.map
148
+ //# sourceMappingURL=chunk-NMQ5Z6YG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/nativeSandboxIo.ts","../src/hostPathToolchain.ts","../src/identityMounts.ts"],"names":[],"mappings":";;;;;;;;AAeO,IAAM,aAAA,GAAgB,CAC3B,IAAA,EACA,MAAA,EACA,YAAA,KAC+C;AAC/C,EAAA,MAAM,YAAY,MAAA,KAAW,MAAA;AAC7B,EAAA,MAAM,MAAA,GAAS,YACX,IAAI,WAAA,CAAY,cAAc,IAAI,CAAA,GAClC,IAAI,WAAA,CAAY,QAAQ,CAAA;AAC5B,EAAA,MAAM,MAAA,GAAS,IAAI,WAAA,CAAY,SAAA,GAAY,eAAe,QAAQ,CAAA;AAClE,EAAA,IAAI,WAAW,MAAA,EAAW;AACxB,IAAA,IAAA,CAAK,MAAA,CAAO,EAAA,CAAG,MAAA,EAAQ,CAAC,KAAA,KAAkB;AACxC,MAAA,MAAA,CAAO,IAAA,CAAK,KAAA,CAAM,QAAA,EAAU,CAAA;AAAA,IAC9B,CAAC,CAAA;AAAA,EACH,CAAA,MAAO;AACL,IAAA,eAAA,CAAgB,EAAE,OAAO,IAAA,CAAK,MAAA,EAAQ,CAAA,CAAE,EAAA,CAAG,MAAA,EAAQ,CAAC,IAAA,KAAS;AAC3D,MAAA,MAAA,CAAO,KAAK,IAAI,CAAA;AAChB,MAAA,MAAA,CAAO,IAAI,CAAA;AAAA,IACb,CAAC,CAAA;AAAA,EACH;AACA,EAAA,IAAA,CAAK,MAAA,CAAO,EAAA,CAAG,MAAA,EAAQ,CAAC,KAAA,KAAkB;AACxC,IAAA,MAAA,CAAO,IAA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AAG,QAAQ,CAAA,sFAAA,EACO,KAAA,EAAO,QAAA,IAAY,SAAS,QAAQ,CAAA,cAAA,EAAiB,QAAA,CAAS,QAAQ,qBACnE,KAAA,EAAO,WAAA,IAAe,SAAS,WAAW,CAAA,cAAA,EAAiB,SAAS,WAAW,CAAA,EAAA;AAAA,KACtG;AAAA,EACF;AACA,EAAA,OAAO;AAAA,IACL,UAAU,QAAA,CAAS,QAAA;AAAA,IACnB,QAAA,EAAU,SAAS,QAAA,KAAa;AAAA,GAClC;AACF,CAAC","file":"chunk-NMQ5Z6YG.js","sourcesContent":["/**\n * Provider-agnostic helpers for the native sandbox providers (`bwrap()`,\n * `seatbelt()`): collecting a child process's output, and copying a file\n * between host paths. Each is purely a function of its inputs.\n */\n\nimport type { ChildProcessWithoutNullStreams } from \"node:child_process\";\nimport { dirname } from \"node:path\";\nimport { createInterface } from \"node:readline\";\nimport { FileSystem } from \"@effect/platform\";\nimport { Effect } from \"effect\";\nimport { BoundedTail } from \"./boundedTail.js\";\nimport { CopyError } from \"./errors.js\";\n\n/** Collects a child's output: streamed line by line with a bounded tail, or whole. */\nexport const collectOutput = (\n proc: ChildProcessWithoutNullStreams,\n onLine: ((line: string) => void) | undefined,\n maxTailChars: number,\n): (() => { stdout: string; stderr: string }) => {\n const streaming = onLine !== undefined;\n const stdout = streaming\n ? new BoundedTail(maxTailChars, \"\\n\")\n : new BoundedTail(Infinity);\n const stderr = new BoundedTail(streaming ? maxTailChars : Infinity);\n if (onLine === undefined) {\n proc.stdout.on(\"data\", (chunk: Buffer) => {\n stdout.push(chunk.toString());\n });\n } else {\n createInterface({ input: proc.stdout }).on(\"line\", (line) => {\n stdout.push(line);\n onLine(line);\n });\n }\n proc.stderr.on(\"data\", (chunk: Buffer) => {\n stderr.push(chunk.toString());\n });\n return () => ({ stdout: stdout.toString(), stderr: stderr.toString() });\n};\n\n/** Copies a file, creating the target's parent dirs. */\nexport const copyCreatingParents = (\n from: string,\n to: string,\n): Effect.Effect<void, CopyError, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n yield* fs.makeDirectory(dirname(to), { recursive: true });\n yield* fs.copyFile(from, to);\n }).pipe(\n Effect.mapError(\n (e) =>\n new CopyError({\n message: `Couldn't copy ${from} to ${to}: ${e.message}`,\n }),\n ),\n );\n","/**\n * Resolves the host toolchain a native sandbox provider should make readable,\n * from the host `PATH`: every `PATH` dir, plus the install root of each\n * executable symlinked from those dirs (an nvm-installed `codex`, a `claude`\n * symlinked into `~/.local/bin`). A dir equal to the home dir or an ancestor\n * of it is refused, so the toolchain never exposes the whole home, and an\n * install root that holds a `.git` is refused, so it never exposes a repo.\n *\n * Provider-agnostic: it takes paths and returns paths. Shared by the native\n * sandbox providers.\n */\n\nimport { homedir } from \"node:os\";\nimport { posix } from \"node:path\";\nimport { FileSystem } from \"@effect/platform\";\nimport { Config, Effect, Option } from \"effect\";\n\n/** What to resolve the toolchain from. */\nexport interface HostPathToolchainInput {\n /** The host `PATH`. */\n readonly path: string;\n /** The host home dir: it and its ancestors are never made readable. */\n readonly home: string;\n /** Dirs the sandbox already shows: nothing inside them is returned to mount. */\n readonly coveredRoots: readonly string[];\n /** Dirs that must stay hidden: `PATH` dirs and install roots inside them are refused. */\n readonly deniedRoots: readonly string[];\n}\n\n/** The toolchain a sandbox needs, all at host paths. */\nexport interface HostPathToolchain {\n /** The `PATH` for the sandboxed child: the host `PATH` dirs it can see, in order. */\n readonly pathEntries: readonly string[];\n /** Real dirs to make readable at their own paths. */\n readonly readableDirs: readonly string[];\n /** `PATH` dirs that are symlinks on the host, to recreate pointing at their real dir. */\n readonly symlinks: readonly {\n readonly path: string;\n readonly target: string;\n }[];\n}\n\nconst isWithin = (path: string, root: string): boolean =>\n root === \"/\" || path === root || path.startsWith(`${root}/`);\n\nconst isWithinAny = (path: string, roots: readonly string[]): boolean =>\n roots.some((root) => isWithin(path, root));\n\n/** True for the home dir itself and every ancestor of it, `/` included. */\nconst isHomeOrAncestor = (path: string, home: string): boolean =>\n isWithin(home, path);\n\nconst normalizeEntry = (entry: string): string => {\n const normalized = posix.normalize(entry);\n return normalized.length > 1 && normalized.endsWith(\"/\")\n ? normalized.slice(0, -1)\n : normalized;\n};\n\nconst realPathOf = (\n fs: FileSystem.FileSystem,\n path: string,\n): Effect.Effect<Option.Option<string>> => Effect.option(fs.realPath(path));\n\n/** True when `dir` sits inside a `node_modules` tree. */\nconst isInNodeModules = (dir: string): boolean =>\n dir.split(\"/\").includes(\"node_modules\");\n\n/**\n * The install root of an executable's real file: the nearest ancestor holding\n * a `package.json` inside a `node_modules` tree (a globally installed Node\n * package's bin pulls in its own files), else the file's dir. A `package.json`\n * outside `node_modules` (an `npm link`ed checkout, a stray one above a\n * projects dir) is not an install root: mounting it would expose a project.\n * The search stops below the home dir.\n */\nconst installRootOf = (\n fs: FileSystem.FileSystem,\n file: string,\n home: string,\n): Effect.Effect<string> =>\n Effect.gen(function* () {\n const fileDir = posix.dirname(file);\n let dir = fileDir;\n while (isInNodeModules(dir) && !isHomeOrAncestor(dir, home)) {\n const hasPackageJson = yield* fs\n .exists(posix.join(dir, \"package.json\"))\n .pipe(Effect.orElseSucceed(() => false));\n if (hasPackageJson) {\n return dir;\n }\n dir = posix.dirname(dir);\n }\n return fileDir;\n });\n\n/** True when `dir` holds a `.git`: a repo's checkout is never an install root. */\nconst isRepoRoot = (\n fs: FileSystem.FileSystem,\n dir: string,\n): Effect.Effect<boolean> =>\n fs.exists(posix.join(dir, \".git\")).pipe(Effect.orElseSucceed(() => false));\n\n/** The real files behind the symlinks directly inside `dir`. */\nconst symlinkTargetsIn = (\n fs: FileSystem.FileSystem,\n dir: string,\n): Effect.Effect<string[]> =>\n Effect.gen(function* () {\n const names = yield* fs\n .readDirectory(dir)\n .pipe(Effect.orElseSucceed((): string[] => []));\n const targets = yield* Effect.forEach(\n names,\n (name) =>\n Effect.gen(function* () {\n const entry = posix.join(dir, name);\n const link = yield* Effect.option(fs.readLink(entry));\n return Option.isSome(link)\n ? yield* realPathOf(fs, entry)\n : Option.none<string>();\n }),\n { concurrency: 32 },\n );\n return targets.flatMap((t) => (Option.isSome(t) ? [t.value] : []));\n });\n\n/** The rules every resolved path is held to. */\ninterface Rules {\n readonly home: string;\n readonly coveredRoots: readonly string[];\n readonly deniedRoots: readonly string[];\n}\n\nconst isRefused = (path: string, rules: Rules): boolean =>\n isHomeOrAncestor(path, rules.home) || isWithinAny(path, rules.deniedRoots);\n\n/** A `PATH` entry the sandbox may see, and the real dir behind it. */\ninterface AcceptedEntry {\n readonly entry: string;\n readonly real: string;\n}\n\n/** Accepts a `PATH` entry that exists and isn't refused, by itself or by its real dir. */\nconst acceptEntry = (\n fs: FileSystem.FileSystem,\n entry: string,\n rules: Rules,\n): Effect.Effect<Option.Option<AcceptedEntry>> =>\n isRefused(entry, rules)\n ? Effect.succeed(Option.none())\n : realPathOf(fs, entry).pipe(\n Effect.map(Option.filter((real) => !isRefused(real, rules))),\n Effect.map(Option.map((real) => ({ entry, real }))),\n );\n\n/** The install roots of the executables symlinked from `dir` to outside it. */\nconst installRootsIn = (\n fs: FileSystem.FileSystem,\n dir: string,\n rules: Rules,\n): Effect.Effect<string[]> =>\n Effect.gen(function* () {\n const targets = (yield* symlinkTargetsIn(fs, dir)).filter(\n (target) =>\n !isWithin(target, dir) && !isWithinAny(target, rules.coveredRoots),\n );\n const roots = yield* Effect.all(\n targets.map((target) => installRootOf(fs, target, rules.home)),\n );\n return yield* Effect.filter(\n roots.filter((root) => !isRefused(root, rules)),\n (root) => Effect.map(isRepoRoot(fs, root), (isRepo) => !isRepo),\n );\n });\n\n/** Keeps only the dirs not inside another dir of the list. */\nconst outermost = (dirs: readonly string[]): string[] => {\n const unique = [...new Set(dirs)];\n return unique.filter(\n (dir) => !unique.some((other) => other !== dir && isWithin(dir, other)),\n );\n};\n\n/** Resolves the toolchain a sandbox needs from the host `PATH`. */\nexport const resolveHostPathToolchain = (\n input: HostPathToolchainInput,\n): Effect.Effect<HostPathToolchain, never, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const rules: Rules = { ...input, home: normalizeEntry(input.home) };\n const entries = [\n ...new Set(\n input.path\n .split(\":\")\n .filter((entry) => entry.startsWith(\"/\"))\n .map((entry) => normalizeEntry(entry)),\n ),\n ];\n const accepted = (yield* Effect.all(\n entries.map((entry) => acceptEntry(fs, entry, rules)),\n )).flatMap((a) => (Option.isSome(a) ? [a.value] : []));\n const uncovered = accepted.filter(\n (a) => !isWithinAny(a.real, rules.coveredRoots),\n );\n const installRoots = yield* Effect.all(\n [...new Set(accepted.map((a) => a.real))].map((dir) =>\n installRootsIn(fs, dir, rules),\n ),\n );\n return {\n pathEntries: accepted.map((a) => a.entry),\n readableDirs: outermost([\n ...uncovered.map((a) => a.real),\n ...installRoots.flat(),\n ]),\n symlinks: uncovered\n .filter(\n (a) =>\n a.real !== a.entry && !isWithinAny(a.entry, rules.coveredRoots),\n )\n .map((a) => ({ path: a.entry, target: a.real })),\n };\n });\n\n/**\n * {@link resolveHostPathToolchain} for this process: the host `PATH` and home\n * dir come from the environment.\n */\nexport const hostPathToolchainFromEnv = (roots: {\n readonly coveredRoots: readonly string[];\n readonly deniedRoots: readonly string[];\n}): Effect.Effect<HostPathToolchain, never, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const path = yield* Config.string(\"PATH\").pipe(Config.withDefault(\"\"));\n return yield* resolveHostPathToolchain({ path, home: homedir(), ...roots });\n }).pipe(Effect.orDie);\n","/**\n * Identity mounts: the `mounts` option of the native sandbox providers, where\n * every path appears inside the sandbox at its own host path. Provider-agnostic:\n * shared by the native sandbox providers.\n */\n\nimport type { MountConfig } from \"./MountConfig.js\";\nimport { resolveUserMounts } from \"./mountUtils.js\";\n\nexport type { MountConfig } from \"./MountConfig.js\";\n\n/** A resolved mount that appears at its own host path. */\nexport interface IdentityMount {\n readonly hostPath: string;\n readonly readonly: boolean;\n}\n\n/**\n * Resolves `mounts` (tilde and relative paths, as for every provider) and\n * checks each appears at its own host path. Throws, naming `provider`, when a\n * resolved `sandboxPath` differs from its resolved `hostPath`, or when a\n * `hostPath` doesn't exist.\n */\nexport const resolveIdentityMounts = (\n provider: string,\n mounts: readonly MountConfig[],\n sandboxHomedir: string,\n): IdentityMount[] =>\n resolveUserMounts(mounts, sandboxHomedir).map((resolved, i) => {\n if (resolved.sandboxPath !== resolved.hostPath) {\n const given = mounts[i];\n throw new Error(\n `${provider}() mounts appear at their host path, so sandboxPath must equal hostPath: ` +\n `got hostPath ${given?.hostPath ?? resolved.hostPath} (resolved to ${resolved.hostPath}) ` +\n `and sandboxPath ${given?.sandboxPath ?? resolved.sandboxPath} (resolved to ${resolved.sandboxPath}).`,\n );\n }\n return {\n hostPath: resolved.hostPath,\n readonly: resolved.readonly === true,\n };\n });\n"]}
@@ -1,7 +1,7 @@
1
1
  import { createRequire } from 'node:module';
2
- import { Effect_exports, resolveUserMounts, processFileMountParents, defaultImageName, registerShutdown, DockerError, formatVolumeMount } from './chunk-5VM5QZ26.js';
3
- import { createBindMountSandboxProvider } from './chunk-BIWNFKGV.js';
4
- import { MAX_TAIL_CHARS, BoundedTail } from './chunk-NGBM7T3E.js';
2
+ import { Effect_exports, ImageNotFoundError, resolveUserMounts, processFileMountParents, defaultImageName, registerShutdown, DockerError, formatVolumeMount } from './chunk-LWNC4UTZ.js';
3
+ import { createBindMountSandboxProvider } from './chunk-XCYK7I45.js';
4
+ import { MAX_TAIL_CHARS, BoundedTail } from './chunk-6NQPCXSG.js';
5
5
  import { execFile, execFileSync, spawn } from 'child_process';
6
6
  import { randomUUID } from 'crypto';
7
7
  import { createInterface } from 'readline';
@@ -18,12 +18,12 @@ var dockerExec = (args) => Effect_exports.async((resume) => {
18
18
  resume(
19
19
  Effect_exports.fail(
20
20
  new DockerError({
21
- message: `docker ${args[0]} failed: ${stderr?.toString() || error.message}`
21
+ message: `docker ${args[0]} failed: ${stderr || error.message}`
22
22
  })
23
23
  )
24
24
  );
25
25
  } else {
26
- resume(Effect_exports.succeed(stdout.toString()));
26
+ resume(Effect_exports.succeed(stdout));
27
27
  }
28
28
  }
29
29
  );
@@ -32,25 +32,15 @@ var buildImage = (imageName, dockerfileDir, options) => Effect_exports.gen(funct
32
32
  const buildArgFlags = Object.entries(options?.buildArgs ?? {}).flatMap(
33
33
  ([k, v]) => ["--build-arg", `${k}=${v}`]
34
34
  );
35
- if (options?.dockerfile) {
36
- yield* dockerExec([
37
- "build",
38
- "-t",
39
- imageName,
40
- ...buildArgFlags,
41
- "-f",
42
- resolve(options.dockerfile),
43
- process.cwd()
44
- ]);
45
- } else {
46
- yield* dockerExec([
47
- "build",
48
- "-t",
49
- imageName,
50
- ...buildArgFlags,
51
- resolve(dockerfileDir)
52
- ]);
53
- }
35
+ const dockerfile = options?.dockerfile;
36
+ const buildContext = dockerfile !== void 0 && dockerfile !== "" ? ["-f", resolve(dockerfile), process.cwd()] : [resolve(dockerfileDir)];
37
+ yield* dockerExec([
38
+ "build",
39
+ "-t",
40
+ imageName,
41
+ ...buildArgFlags,
42
+ ...buildContext
43
+ ]);
54
44
  });
55
45
  var startContainer = (containerName, imageName, env, options) => Effect_exports.gen(function* () {
56
46
  const existing = yield* dockerExec([
@@ -62,11 +52,9 @@ var startContainer = (containerName, imageName, env, options) => Effect_exports.
62
52
  "{{.Names}}"
63
53
  ]);
64
54
  if (existing.trim() === containerName) {
65
- yield* Effect_exports.fail(
66
- new DockerError({
67
- message: `Container '${containerName}' already exists. Run cleanup first.`
68
- })
69
- );
55
+ return yield* new DockerError({
56
+ message: `Container '${containerName}' already exists. Run cleanup first.`
57
+ });
70
58
  }
71
59
  const envFlags = Object.entries(env).flatMap(([k, v]) => [
72
60
  "-e",
@@ -77,20 +65,27 @@ var startContainer = (containerName, imageName, env, options) => Effect_exports.
77
65
  "-v",
78
66
  formatVolumeMount(mount, selinuxLabel)
79
67
  ]);
80
- const workdirFlags = options?.workdir ? ["-w", options.workdir] : [];
81
- const userFlags = options?.user ? ["--user", options.user] : [];
82
- const networks = options?.network ? Array.isArray(options.network) ? options.network : [options.network] : [];
68
+ const workdir = options?.workdir;
69
+ const workdirFlags = workdir !== void 0 && workdir !== "" ? ["-w", workdir] : [];
70
+ const user = options?.user;
71
+ const userFlags = user !== void 0 && user !== "" ? ["--user", user] : [];
72
+ const network = options?.network;
73
+ const networks = network === void 0 || network === "" ? [] : [network].flat();
83
74
  const networkFlags = networks.flatMap((n) => ["--network", n]);
84
75
  const groupAddFlags = (options?.groups ?? []).flatMap((g) => [
85
76
  "--group-add",
86
77
  String(g)
87
78
  ]);
79
+ const capDropFlags = (options?.capDrop ?? []).flatMap((cap) => [
80
+ "--cap-drop",
81
+ cap
82
+ ]);
88
83
  const deviceFlags = (options?.devices ?? []).flatMap((d) => [
89
84
  "--device",
90
85
  d
91
86
  ]);
92
- const cpusFlags = options?.cpus !== void 0 ? ["--cpus", String(options.cpus)] : [];
93
- yield* dockerExec([
87
+ const cpusFlags = options?.cpus === void 0 ? [] : ["--cpus", String(options.cpus)];
88
+ return yield* dockerExec([
94
89
  "run",
95
90
  "-d",
96
91
  "--name",
@@ -101,18 +96,27 @@ var startContainer = (containerName, imageName, env, options) => Effect_exports.
101
96
  ...userFlags,
102
97
  ...networkFlags,
103
98
  ...groupAddFlags,
99
+ ...capDropFlags,
104
100
  ...deviceFlags,
105
101
  ...cpusFlags,
106
102
  imageName
107
- ]);
103
+ ]).pipe(Effect_exports.asVoid);
108
104
  });
109
105
  var removeContainer = (containerName) => Effect_exports.gen(function* () {
110
106
  yield* Effect_exports.ignore(dockerExec(["stop", containerName]));
111
107
  yield* Effect_exports.ignore(dockerExec(["rm", containerName]));
112
108
  });
113
- var removeImage = (imageName) => Effect_exports.gen(function* () {
114
- yield* dockerExec(["rmi", imageName]);
115
- });
109
+ var removeImage = (imageName) => dockerExec(["rmi", imageName]).pipe(
110
+ Effect_exports.asVoid,
111
+ Effect_exports.catchTag(
112
+ "DockerError",
113
+ (error) => error.message.includes("No such image") ? Effect_exports.fail(
114
+ new ImageNotFoundError({
115
+ message: `Docker image '${imageName}' does not exist, so there is nothing to remove.`
116
+ })
117
+ ) : Effect_exports.fail(error)
118
+ )
119
+ );
116
120
 
117
121
  // src/sandboxes/docker.ts
118
122
  var docker = (options) => {
@@ -158,6 +162,7 @@ var docker = (options) => {
158
162
  user: `${containerUid}:${containerGid}`,
159
163
  network: options?.network,
160
164
  groups: options?.groups,
165
+ capDrop: options?.capDrop,
161
166
  devices: options?.devices,
162
167
  cpus: options?.cpus,
163
168
  selinuxLabel
@@ -205,29 +210,31 @@ var docker = (options) => {
205
210
  const unregisterShutdown = registerShutdown(removeContainerSync);
206
211
  const handle = {
207
212
  worktreePath,
208
- exec: (command, opts) => {
209
- const effectiveCommand = opts?.sudo ? `sudo ${command}` : command;
213
+ sandboxId: containerName,
214
+ exec: async (command, opts) => {
210
215
  const args = ["exec"];
211
- if (opts?.stdin !== void 0) args.push("-i");
212
- if (opts?.cwd) args.push("-w", opts.cwd);
213
- args.push(containerName, "sh", "-c", effectiveCommand);
216
+ if (opts?.sudo === true) {
217
+ args.push("--user", "0:0");
218
+ }
219
+ if (opts?.stdin !== void 0) {
220
+ args.push("-i");
221
+ }
222
+ if (opts?.cwd !== void 0 && opts.cwd !== "") {
223
+ args.push("-w", opts.cwd);
224
+ }
225
+ args.push(containerName, "sh", "-c", command);
214
226
  return new Promise((resolve2, reject) => {
215
- const proc = spawn("docker", args, {
216
- stdio: [
217
- opts?.stdin !== void 0 ? "pipe" : "ignore",
218
- "pipe",
219
- "pipe"
220
- ]
221
- });
222
- if (opts?.stdin !== void 0) {
223
- proc.stdin.write(opts.stdin);
224
- proc.stdin.end();
227
+ const stdin = opts?.stdin;
228
+ const proc = stdin === void 0 ? spawn("docker", args, { stdio: ["ignore", "pipe", "pipe"] }) : spawn("docker", args, { stdio: ["pipe", "pipe", "pipe"] });
229
+ if (stdin !== void 0) {
230
+ proc.stdin?.write(stdin);
231
+ proc.stdin?.end();
225
232
  }
226
233
  proc.on("error", (error) => {
227
234
  reject(new Error(`docker exec failed: ${error.message}`));
228
235
  });
229
236
  if (opts?.onLine) {
230
- const onLine = opts.onLine;
237
+ const { onLine } = opts;
231
238
  const stdoutTail = new BoundedTail(maxOutputTailChars, "\n");
232
239
  const stderrTail = new BoundedTail(maxOutputTailChars, "");
233
240
  const rl = createInterface({ input: proc.stdout });
@@ -264,28 +271,28 @@ var docker = (options) => {
264
271
  }
265
272
  });
266
273
  },
267
- interactiveExec: (args, opts) => {
268
- return new Promise((resolve2, reject) => {
269
- const dockerArgs = ["exec"];
270
- if ("isTTY" in opts.stdin && opts.stdin.isTTY) {
271
- dockerArgs.push("-it");
272
- } else {
273
- dockerArgs.push("-i");
274
- }
275
- if (opts.cwd) dockerArgs.push("-w", opts.cwd);
276
- dockerArgs.push(containerName, ...args);
277
- const proc = spawn("docker", dockerArgs, {
278
- stdio: [opts.stdin, opts.stdout, opts.stderr]
279
- });
280
- proc.on("error", (error) => {
281
- reject(new Error(`docker exec failed: ${error.message}`));
282
- });
283
- proc.on("close", (code) => {
284
- resolve2({ exitCode: code ?? 0 });
285
- });
274
+ interactiveExec: async (args, opts) => new Promise((resolve2, reject) => {
275
+ const dockerArgs = ["exec"];
276
+ if ("isTTY" in opts.stdin && opts.stdin.isTTY === true) {
277
+ dockerArgs.push("-it");
278
+ } else {
279
+ dockerArgs.push("-i");
280
+ }
281
+ if (opts.cwd !== void 0 && opts.cwd !== "") {
282
+ dockerArgs.push("-w", opts.cwd);
283
+ }
284
+ dockerArgs.push(containerName, ...args);
285
+ const proc = spawn("docker", dockerArgs, {
286
+ stdio: [opts.stdin, opts.stdout, opts.stderr]
286
287
  });
287
- },
288
- copyFileIn: (hostPath, sandboxPath) => new Promise((resolve2, reject) => {
288
+ proc.on("error", (error) => {
289
+ reject(new Error(`docker exec failed: ${error.message}`));
290
+ });
291
+ proc.on("close", (code) => {
292
+ resolve2({ exitCode: code ?? 0 });
293
+ });
294
+ }),
295
+ copyFileIn: async (hostPath, sandboxPath) => new Promise((resolve2, reject) => {
289
296
  execFile(
290
297
  "docker",
291
298
  ["cp", hostPath, `${containerName}:${sandboxPath}`],
@@ -298,7 +305,7 @@ var docker = (options) => {
298
305
  }
299
306
  );
300
307
  }),
301
- copyFileOut: (sandboxPath, hostPath) => new Promise((resolve2, reject) => {
308
+ copyFileOut: async (sandboxPath, hostPath) => new Promise((resolve2, reject) => {
302
309
  execFile(
303
310
  "docker",
304
311
  ["cp", `${containerName}:${sandboxPath}`, hostPath],
@@ -320,7 +327,7 @@ var docker = (options) => {
320
327
  }
321
328
  });
322
329
  };
323
- var checkImageUid = (imageName, expectedUid) => new Promise((resolve2, reject) => {
330
+ var checkImageUid = async (imageName, expectedUid) => new Promise((resolve2, reject) => {
324
331
  execFile(
325
332
  "docker",
326
333
  ["image", "inspect", imageName, "--format", "{{.Config.User}}"],
@@ -333,30 +340,30 @@ var checkImageUid = (imageName, expectedUid) => new Promise((resolve2, reject) =
333
340
  );
334
341
  return;
335
342
  }
336
- const imageUser = (stdout ?? "").toString().trim();
343
+ const imageUser = (stdout ?? "").trim();
337
344
  if (!imageUser) {
338
345
  resolve2();
339
346
  return;
340
347
  }
341
- const uidPart = imageUser.split(":")[0];
342
- const imageUid = parseInt(uidPart, 10);
348
+ const uidPart = imageUser.split(":")[0] ?? "";
349
+ const imageUid = Number.parseInt(uidPart, 10);
343
350
  if (isNaN(imageUid)) {
344
351
  resolve2();
345
352
  return;
346
353
  }
347
- if (imageUid !== expectedUid) {
354
+ if (imageUid === expectedUid) {
355
+ resolve2();
356
+ } else {
348
357
  reject(
349
358
  new Error(
350
359
  `UID mismatch: image '${imageName}' was built with UID ${imageUid}, but the expected UID is ${expectedUid}. Rebuild the image with 'sandcastle docker build-image', or pass containerUid: ${imageUid} to docker() to match the image.`
351
360
  )
352
361
  );
353
- } else {
354
- resolve2();
355
362
  }
356
363
  }
357
364
  );
358
365
  });
359
366
 
360
367
  export { buildImage, docker, removeImage };
361
- //# sourceMappingURL=chunk-NSFQW6ML.js.map
362
- //# sourceMappingURL=chunk-NSFQW6ML.js.map
368
+ //# sourceMappingURL=chunk-U42XXICG.js.map
369
+ //# sourceMappingURL=chunk-U42XXICG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/DockerLifecycle.ts","../src/sandboxes/docker.ts"],"names":["resolve","execFile"],"mappings":";;;;;;;;;;AAWA,IAAM,aAAa,CAAC,IAAA,KAClB,cAAA,CAAO,KAAA,CAAM,CAAC,MAAA,KAAW;AACvB,EAAA,QAAA;AAAA,IACE,QAAA;AAAA,IACA,IAAA;AAAA,IACA,EAAE,SAAA,EAAW,EAAA,GAAK,IAAA,GAAO,IAAA,EAAK;AAAA,IAC9B,CAAC,KAAA,EAAO,MAAA,EAAQ,MAAA,KAAW;AACzB,MAAA,IAAI,KAAA,EAAO;AACT,QAAA,MAAA;AAAA,UACE,cAAA,CAAO,IAAA;AAAA,YACL,IAAI,WAAA,CAAY;AAAA,cACd,OAAA,EAAS,UAAU,IAAA,CAAK,CAAC,CAAC,CAAA,SAAA,EAAY,MAAA,IAAU,MAAM,OAAO,CAAA;AAAA,aAC9D;AAAA;AACH,SACF;AAAA,MACF,CAAA,MAAO;AACL,QAAA,MAAA,CAAO,cAAA,CAAO,OAAA,CAAQ,MAAM,CAAC,CAAA;AAAA,MAC/B;AAAA,IACF;AAAA,GACF;AACF,CAAC,CAAA;AASI,IAAM,aAAa,CACxB,SAAA,EACA,eACA,OAAA,KAKA,cAAA,CAAO,IAAI,aAAa;AACtB,EAAA,MAAM,gBAAgB,MAAA,CAAO,OAAA,CAAQ,SAAS,SAAA,IAAa,EAAE,CAAA,CAAE,OAAA;AAAA,IAC7D,CAAC,CAAC,CAAA,EAAG,CAAC,CAAA,KAAM,CAAC,aAAA,EAAe,CAAA,EAAG,CAAC,CAAA,CAAA,EAAI,CAAC,CAAA,CAAE;AAAA,GACzC;AACA,EAAA,MAAM,aAAa,OAAA,EAAS,UAAA;AAC5B,EAAA,MAA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A,CAAM,GAAG,CAAA,CAAE,CAAC,CAAA,IAAK,EAAA;AAC3C,MAAA,MAAM,QAAA,GAAW,MAAA,CAAO,QAAA,CAAS,OAAA,EAAS,EAAE,CAAA;AAC5C,MAAA,IAAI,KAAA,CAAM,QAAQ,CAAA,EAAG;AAEnB,QAAAA,QAAAA,EAAQ;AACR,QAAA;AAAA,MACF;AACA,MAAA,IAAI,aAAa,WAAA,EAAa;AAC5B,QAAAA,QAAAA,EAAQ;AAAA,MACV,CAAA,MAAO;AACL,QAAA,MAAA;AAAA,UACE,IAAI,KAAA;AAAA,YACF,wBAAwB,SAAS,CAAA,qBAAA,EAAwB,QAAQ,CAAA,0BAAA,EACpC,WAAW,mFAEb,QAAQ,CAAA,gCAAA;AAAA;AACrC,SACF;AAAA,MACF;AAAA,IACF;AAAA,GACF;AACF,CAAC,CAAA","file":"chunk-U42XXICG.js","sourcesContent":["import { Effect } from \"effect\";\nimport { execFile } from \"node:child_process\";\nimport { resolve } from \"node:path\";\nimport { DockerError, ImageNotFoundError } from \"./errors.js\";\nimport { formatVolumeMount } from \"./mountUtils.js\";\nimport type { SelinuxLabel } from \"./mountUtils.js\";\nimport type { LinuxCapability } from \"./LinuxCapability.js\";\n\n// Re-exported so docker.ts gets it with the lifecycle it already imports.\nexport type { LinuxCapability } from \"./LinuxCapability.js\";\n\nconst dockerExec = (args: string[]): Effect.Effect<string, DockerError> =>\n Effect.async((resume) => {\n execFile(\n \"docker\",\n args,\n { maxBuffer: 10 * 1024 * 1024 },\n (error, stdout, stderr) => {\n if (error) {\n resume(\n Effect.fail(\n new DockerError({\n message: `docker ${args[0]} failed: ${stderr || error.message}`,\n }),\n ),\n );\n } else {\n resume(Effect.succeed(stdout));\n }\n },\n );\n });\n\n/**\n * Build the sandcastle Docker image.\n *\n * When `dockerfile` is provided, uses `docker build -f <dockerfile> <cwd>`\n * so COPY instructions resolve relative to the current working directory.\n * Otherwise, uses `docker build <dockerfileDir>` (the default .sandcastle/ directory).\n */\nexport const buildImage = (\n imageName: string,\n dockerfileDir: string,\n options?: {\n readonly dockerfile?: string;\n readonly buildArgs?: Record<string, string>;\n },\n): Effect.Effect<void, DockerError> =>\n Effect.gen(function* () {\n const buildArgFlags = Object.entries(options?.buildArgs ?? {}).flatMap(\n ([k, v]) => [\"--build-arg\", `${k}=${v}`],\n );\n const dockerfile = options?.dockerfile;\n const buildContext =\n dockerfile !== undefined && dockerfile !== \"\"\n ? [\"-f\", resolve(dockerfile), process.cwd()]\n : [resolve(dockerfileDir)];\n yield* dockerExec([\n \"build\",\n \"-t\",\n imageName,\n ...buildArgFlags,\n ...buildContext,\n ]);\n });\n\nexport interface VolumeMount {\n readonly hostPath: string;\n readonly sandboxPath: string;\n readonly readonly?: boolean;\n}\n\nexport interface StartContainerOptions {\n readonly volumeMounts?: readonly VolumeMount[];\n readonly workdir?: string;\n /** Run the container as this uid:gid instead of the Dockerfile's USER. */\n readonly user?: string;\n /** Docker network(s) to attach the container to. Passed as `--network` flags. */\n readonly network?: string | readonly string[];\n /** Supplementary groups to add the container user to. Passed as `--group-add` flags. */\n readonly groups?: readonly (string | number)[];\n /** Linux capabilities to drop from the container. Passed as `--cap-drop` flags. */\n readonly capDrop?: readonly LinuxCapability[];\n /** Host devices to expose to the container. Passed as `--device` flags. */\n readonly devices?: readonly string[];\n /** Limit CPU resources via `--cpus` (e.g. `1.5`). Fractional values allowed. */\n readonly cpus?: number;\n /**\n * SELinux volume label suffix applied to bind mounts (default `\"z\"`).\n *\n * - `\"z\"` — shared label. No-op on non-SELinux systems.\n * - `\"Z\"` — private label; only this container can access the mount.\n * - `false` — disable labeling entirely.\n */\n readonly selinuxLabel?: SelinuxLabel;\n}\n\n/**\n * Start a new container with environment variables injected.\n */\nexport const startContainer = (\n containerName: string,\n imageName: string,\n env: Record<string, string>,\n options?: StartContainerOptions,\n): Effect.Effect<void, DockerError> =>\n Effect.gen(function* () {\n // Check if container already exists\n const existing = yield* dockerExec([\n \"ps\",\n \"-a\",\n \"--filter\",\n `name=^${containerName}$`,\n \"--format\",\n \"{{.Names}}\",\n ]);\n\n if (existing.trim() === containerName) {\n return yield* new DockerError({\n message: `Container '${containerName}' already exists. Run cleanup first.`,\n });\n }\n\n const envFlags = Object.entries(env).flatMap(([k, v]) => [\n \"-e\",\n `${k}=${v}`,\n ]);\n\n const selinuxLabel = options?.selinuxLabel ?? \"z\";\n const volumeFlags = (options?.volumeMounts ?? []).flatMap((mount) => [\n \"-v\",\n formatVolumeMount(mount, selinuxLabel),\n ]);\n\n const workdir = options?.workdir;\n const workdirFlags =\n workdir !== undefined && workdir !== \"\" ? [\"-w\", workdir] : [];\n const user = options?.user;\n const userFlags = user !== undefined && user !== \"\" ? [\"--user\", user] : [];\n const network = options?.network;\n const networks =\n network === undefined || network === \"\" ? [] : [network].flat();\n const networkFlags = networks.flatMap((n) => [\"--network\", n]);\n const groupAddFlags = (options?.groups ?? []).flatMap((g) => [\n \"--group-add\",\n String(g),\n ]);\n const capDropFlags = (options?.capDrop ?? []).flatMap((cap) => [\n \"--cap-drop\",\n cap,\n ]);\n const deviceFlags = (options?.devices ?? []).flatMap((d) => [\n \"--device\",\n d,\n ]);\n const cpusFlags =\n options?.cpus === undefined ? [] : [\"--cpus\", String(options.cpus)];\n\n return yield* dockerExec([\n \"run\",\n \"-d\",\n \"--name\",\n containerName,\n ...envFlags,\n ...volumeFlags,\n ...workdirFlags,\n ...userFlags,\n ...networkFlags,\n ...groupAddFlags,\n ...capDropFlags,\n ...deviceFlags,\n ...cpusFlags,\n imageName,\n ]).pipe(Effect.asVoid);\n });\n\n/**\n * Stop and remove a container without removing the image.\n */\nexport const removeContainer = (\n containerName: string,\n): Effect.Effect<void, DockerError> =>\n Effect.gen(function* () {\n // Stop container (ignore errors if already stopped)\n yield* Effect.ignore(dockerExec([\"stop\", containerName]));\n // Remove container (ignore errors if not found)\n yield* Effect.ignore(dockerExec([\"rm\", containerName]));\n });\n\n/**\n * Remove a Docker image.\n */\nexport const removeImage = (\n imageName: string,\n): Effect.Effect<void, DockerError | ImageNotFoundError> =>\n dockerExec([\"rmi\", imageName]).pipe(\n Effect.asVoid,\n Effect.catchTag(\n \"DockerError\",\n (error): Effect.Effect<never, DockerError | ImageNotFoundError> =>\n error.message.includes(\"No such image\")\n ? Effect.fail(\n new ImageNotFoundError({\n message: `Docker image '${imageName}' does not exist, so there is nothing to remove.`,\n }),\n )\n : Effect.fail(error),\n ),\n );\n","/**\n * Docker sandbox provider — wraps DockerLifecycle into a SandboxProvider.\n *\n * Usage:\n * import { docker } from \"sandcastle/sandboxes/docker\";\n * await run({ agent: claudeCode(\"claude-opus-4-8\"), sandbox: docker() });\n */\n\nimport { execFile, execFileSync, spawn } from \"node:child_process\";\nimport type { StdioOptions } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport { createInterface } from \"node:readline\";\nimport { Effect } from \"effect\";\nimport { startContainer, removeContainer } from \"../DockerLifecycle.js\";\nimport type { LinuxCapability } from \"../DockerLifecycle.js\";\nimport { createBindMountSandboxProvider } from \"../SandboxProvider.js\";\nimport type {\n SandboxProvider,\n BindMountCreateOptions,\n BindMountSandboxHandle,\n ExecResult,\n InteractiveExecOptions,\n} from \"../SandboxProvider.js\";\nimport type { MountConfig } from \"../MountConfig.js\";\nimport type { SelinuxLabel } from \"../mountUtils.js\";\nimport {\n defaultImageName,\n resolveUserMounts,\n processFileMountParents,\n} from \"../mountUtils.js\";\nimport { BoundedTail, MAX_TAIL_CHARS } from \"../boundedTail.js\";\nimport { registerShutdown } from \"../shutdownRegistry.js\";\n\nexport interface DockerOptions {\n /** Docker image name (default: derived from repo directory name). */\n readonly imageName?: string;\n /**\n * The UID of the `agent` user inside the container image (default: host UID via `process.getuid()`, or 1000).\n *\n * Must match the UID baked into the image at build time. Used as the `--user` flag value\n * and checked against the image's configured UID in the pre-flight diagnostic.\n */\n readonly containerUid?: number;\n /**\n * The GID of the `agent` user inside the container image (default: host GID via `process.getgid()`, or 1000).\n *\n * Must match the GID baked into the image at build time. Used as the `--user` flag value.\n */\n readonly containerGid?: number;\n /**\n * SELinux volume label suffix applied to bind mounts.\n *\n * - `\"z\"` — shared label (default). No-op on non-SELinux systems.\n * - `\"Z\"` — private label; only this container can access the mount.\n * - `false` — disable labeling entirely.\n */\n readonly selinuxLabel?: SelinuxLabel;\n /**\n * Additional host directories to bind-mount into the sandbox.\n *\n * Each entry specifies a `hostPath` (tilde-expanded) and `sandboxPath`.\n * If `hostPath` does not exist, sandbox creation fails with a clear error.\n */\n readonly mounts?: readonly MountConfig[];\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 * Docker network(s) to attach the container to.\n *\n * - `\"my-network\"` → `--network my-network`\n * - `[\"net1\", \"net2\"]` → `--network net1 --network net2`\n *\n * When omitted, Docker's default bridge network is used.\n */\n readonly network?: string | readonly string[];\n /**\n * Supplementary groups to add the container user to, via `--group-add`.\n *\n * Accepts group names or numeric GIDs:\n *\n * - `[\"docker\"]` → `--group-add docker`\n * - `[999]` → `--group-add 999`\n * - `[\"docker\", 999]` → `--group-add docker --group-add 999`\n *\n * Useful for granting access to a bind-mounted Docker socket (Docker-outside-of-Docker).\n * When omitted, no `--group-add` flags are added.\n */\n readonly groups?: readonly (string | number)[];\n /**\n * Linux capabilities to drop from the container, via `--cap-drop`.\n *\n * Names are written without the `CAP_` prefix, as `docker run` accepts them,\n * and a misspelt name is a type error:\n *\n * - `[\"NET_RAW\"]` → `--cap-drop NET_RAW` (no raw sockets, so no `ping`)\n * - `[\"NET_RAW\", \"MKNOD\"]` → `--cap-drop NET_RAW --cap-drop MKNOD`\n * - `[\"ALL\"]` → `--cap-drop ALL` (drop every capability)\n *\n * When omitted, no `--cap-drop` flags are added and the container keeps\n * Docker's default capability set.\n */\n readonly capDrop?: readonly LinuxCapability[];\n /**\n * Host devices to expose to the container, via `--device`.\n *\n * Each entry is a full device spec in `host[:container[:permissions]]` form:\n *\n * - `[\"/dev/kvm\"]` → `--device /dev/kvm`\n * - `[\"/dev/sda:/dev/xvda:rwm\"]` → `--device /dev/sda:/dev/xvda:rwm`\n * - `[\"/dev/kvm\", \"/dev/fuse\"]` → `--device /dev/kvm --device /dev/fuse`\n *\n * When omitted, no `--device` flags are added.\n */\n readonly devices?: readonly 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 * Limit the CPU resources available to the container, via `--cpus`.\n *\n * Maps directly to `docker run --cpus`. Accepts fractional values:\n *\n * - `2` → `--cpus 2` (at most 2 CPUs)\n * - `1.5` → `--cpus 1.5` (at most 1.5 CPUs)\n *\n * When omitted, no `--cpus` flag is added and the container is unconstrained.\n */\n readonly cpus?: number;\n}\n\n/**\n * Create a Docker sandbox provider.\n *\n * The returned provider creates Docker containers with bind-mounts\n * for the worktree and git directories.\n */\nexport const docker = (options?: DockerOptions): SandboxProvider => {\n const configuredImageName = options?.imageName;\n const selinuxLabel = options?.selinuxLabel ?? \"z\";\n const maxOutputTailChars = options?.maxOutputTailChars ?? MAX_TAIL_CHARS;\n const sandboxHomedir = \"/home/agent\";\n const userMounts = options?.mounts\n ? resolveUserMounts(options.mounts, sandboxHomedir)\n : [];\n // Validate file mounts and collect parent dirs to create at container start.\n // Throws at construction time if any file mount parent is outside sandboxHomedir.\n const parentDirsToCreate = processFileMountParents(\n userMounts,\n sandboxHomedir,\n );\n\n return createBindMountSandboxProvider({\n name: \"docker\",\n env: options?.env,\n sandboxHomedir,\n create: async (\n createOptions: BindMountCreateOptions,\n ): Promise<BindMountSandboxHandle> => {\n const containerName = `sandcastle-${randomUUID()}`;\n\n const worktreePath =\n createOptions.mounts.find(\n (m) => m.hostPath === createOptions.worktreePath,\n )?.sandboxPath ?? \"/home/agent/workspace\";\n\n // Build volume mount list (internal mounts + user-provided mounts)\n const allMounts = [...createOptions.mounts, ...userMounts];\n const volumeMounts = allMounts.map((m) => ({\n hostPath: m.hostPath,\n sandboxPath: m.sandboxPath,\n readonly: m.readonly,\n }));\n\n // Resolve image name\n const imageName =\n configuredImageName ?? defaultImageName(createOptions.hostRepoPath);\n\n const containerUid = options?.containerUid ?? process.getuid?.() ?? 1000;\n const containerGid = options?.containerGid ?? process.getgid?.() ?? 1000;\n\n // Pre-flight: verify image exists and UID matches\n await checkImageUid(imageName, containerUid);\n\n // Start container\n await Effect.runPromise(\n startContainer(\n containerName,\n imageName,\n {\n ...createOptions.env,\n HOME: \"/home/agent\",\n },\n {\n volumeMounts,\n workdir: worktreePath,\n user: `${containerUid}:${containerGid}`,\n network: options?.network,\n groups: options?.groups,\n capDrop: options?.capDrop,\n devices: options?.devices,\n cpus: options?.cpus,\n selinuxLabel,\n },\n ),\n );\n\n // Create parent directories for file mounts and chown to the container user\n for (const dir of parentDirsToCreate) {\n await new Promise<void>((resolve, reject) => {\n execFile(\n \"docker\",\n [\n \"exec\",\n \"--user\",\n \"0:0\",\n containerName,\n \"sh\",\n \"-c\",\n `mkdir -p \"$1\" && chown \"$2\" \"$1\"`,\n \"sh\",\n dir,\n `${containerUid}:${containerGid}`,\n ],\n (error) => {\n if (error) {\n reject(\n new Error(\n `Failed to create parent directory '${dir}' in container: ${error.message}`,\n ),\n );\n } else {\n resolve();\n }\n },\n );\n });\n }\n\n // Register synchronous container cleanup via the shared shutdown registry\n // so concurrent sandboxes share a single exit/SIGINT/SIGTERM listener\n // instead of tripping Node's MaxListenersExceededWarning.\n const removeContainerSync = () => {\n try {\n execFileSync(\"docker\", [\"rm\", \"-f\", containerName], {\n stdio: \"ignore\",\n });\n } catch {\n /* best-effort */\n }\n };\n const unregisterShutdown = registerShutdown(removeContainerSync);\n\n const handle: BindMountSandboxHandle = {\n worktreePath,\n sandboxId: containerName,\n\n exec: async (\n command: string,\n opts?: {\n onLine?: (line: string) => void;\n cwd?: string;\n sudo?: boolean;\n stdin?: string;\n },\n ): Promise<ExecResult> => {\n const args = [\"exec\"];\n // Elevate by running as root through the engine, not a `sudo`\n // prefix: the image needs no sudo binary, and the whole command\n // (`a && b`, not just `a`) runs as root.\n if (opts?.sudo === true) {\n args.push(\"--user\", \"0:0\");\n }\n if (opts?.stdin !== undefined) {\n args.push(\"-i\");\n }\n if (opts?.cwd !== undefined && opts.cwd !== \"\") {\n args.push(\"-w\", opts.cwd);\n }\n args.push(containerName, \"sh\", \"-c\", command);\n\n return new Promise((resolve, reject) => {\n const stdin = opts?.stdin;\n // Two literal `stdio` tuples, so the types know stdout and stderr\n // are always piped.\n const proc =\n stdin === undefined\n ? spawn(\"docker\", args, { stdio: [\"ignore\", \"pipe\", \"pipe\"] })\n : spawn(\"docker\", args, { stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n\n if (stdin !== undefined) {\n proc.stdin?.write(stdin);\n proc.stdin?.end();\n }\n\n proc.on(\"error\", (error: Error) => {\n reject(new Error(`docker exec failed: ${error.message}`));\n });\n\n if (opts?.onLine) {\n const { onLine } = opts;\n const stdoutTail = new BoundedTail(maxOutputTailChars, \"\\n\");\n const stderrTail = new BoundedTail(maxOutputTailChars, \"\");\n const rl = createInterface({ input: proc.stdout });\n rl.on(\"line\", (line) => {\n stdoutTail.push(line);\n onLine(line);\n });\n proc.stderr.on(\"data\", (chunk: Buffer) => {\n stderrTail.push(chunk.toString());\n });\n proc.on(\"close\", (code: number | null) => {\n resolve({\n stdout: stdoutTail.toString(),\n stderr: stderrTail.toString(),\n exitCode: code ?? 0,\n });\n });\n } else {\n const stdoutChunks: string[] = [];\n const stderrChunks: string[] = [];\n proc.stdout.on(\"data\", (chunk: Buffer) => {\n stdoutChunks.push(chunk.toString());\n });\n proc.stderr.on(\"data\", (chunk: Buffer) => {\n stderrChunks.push(chunk.toString());\n });\n proc.on(\"close\", (code: number | null) => {\n resolve({\n stdout: stdoutChunks.join(\"\"),\n stderr: stderrChunks.join(\"\"),\n exitCode: code ?? 0,\n });\n });\n }\n });\n },\n\n interactiveExec: async (\n args: string[],\n opts: InteractiveExecOptions,\n ): Promise<{ exitCode: number }> =>\n new Promise((resolve, reject) => {\n const dockerArgs = [\"exec\"];\n // Allocate a pseudo-terminal when stdin looks like a TTY\n if (\n \"isTTY\" in opts.stdin &&\n (opts.stdin as { isTTY?: boolean }).isTTY === true\n ) {\n dockerArgs.push(\"-it\");\n } else {\n dockerArgs.push(\"-i\");\n }\n if (opts.cwd !== undefined && opts.cwd !== \"\") {\n dockerArgs.push(\"-w\", opts.cwd);\n }\n dockerArgs.push(containerName, ...args);\n\n const proc = spawn(\"docker\", dockerArgs, {\n stdio: [opts.stdin, opts.stdout, opts.stderr] as StdioOptions,\n });\n\n proc.on(\"error\", (error: Error) => {\n reject(new Error(`docker exec failed: ${error.message}`));\n });\n\n proc.on(\"close\", (code: number | null) => {\n resolve({ exitCode: code ?? 0 });\n });\n }),\n copyFileIn: async (\n hostPath: string,\n sandboxPath: string,\n ): Promise<void> =>\n new Promise((resolve, reject) => {\n execFile(\n \"docker\",\n [\"cp\", hostPath, `${containerName}:${sandboxPath}`],\n (error) => {\n if (error) {\n reject(new Error(`docker cp (in) failed: ${error.message}`));\n } else {\n resolve();\n }\n },\n );\n }),\n\n copyFileOut: async (\n sandboxPath: string,\n hostPath: string,\n ): Promise<void> =>\n new Promise((resolve, reject) => {\n execFile(\n \"docker\",\n [\"cp\", `${containerName}:${sandboxPath}`, hostPath],\n (error) => {\n if (error) {\n reject(new Error(`docker cp (out) failed: ${error.message}`));\n } else {\n resolve();\n }\n },\n );\n }),\n\n close: async (): Promise<void> => {\n unregisterShutdown();\n await Effect.runPromise(removeContainer(containerName));\n },\n };\n\n return handle;\n },\n });\n};\n\nexport type { LinuxCapability } from \"../DockerLifecycle.js\";\n\n// Re-export for backwards compatibility\nexport { defaultImageName } from \"../mountUtils.js\";\n\nconst checkImageUid = async (\n imageName: string,\n expectedUid: number,\n): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n execFile(\n \"docker\",\n [\"image\", \"inspect\", imageName, \"--format\", \"{{.Config.User}}\"],\n (error, stdout) => {\n if (error) {\n reject(\n new Error(\n `Image '${imageName}' not found locally. Build it first with 'sandcastle docker build-image'.`,\n ),\n );\n return;\n }\n const imageUser = (stdout ?? \"\").trim();\n if (!imageUser) {\n // No USER directive in image — skip check\n resolve();\n return;\n }\n const uidPart = imageUser.split(\":\")[0] ?? \"\";\n const imageUid = Number.parseInt(uidPart, 10);\n if (isNaN(imageUid)) {\n // Non-numeric user (e.g. \"agent\") — can't compare, skip check\n resolve();\n return;\n }\n if (imageUid === expectedUid) {\n resolve();\n } else {\n reject(\n new Error(\n `UID mismatch: image '${imageName}' was built with UID ${imageUid}, ` +\n `but the expected UID is ${expectedUid}. ` +\n `Rebuild the image with 'sandcastle docker build-image', ` +\n `or pass containerUid: ${imageUid} to docker() to match the image.`,\n ),\n );\n }\n },\n );\n });\n"]}
@@ -0,0 +1,24 @@
1
+ import { createRequire } from 'node:module';
2
+ import { NativeInteractiveNotSupportedError } from './chunk-LWNC4UTZ.js';
3
+
4
+ createRequire(import.meta.url);
5
+
6
+ // src/nativeSandboxProvider.ts
7
+ var nativeProviders = /* @__PURE__ */ new WeakSet();
8
+ var markNativeSandboxProvider = (provider) => {
9
+ nativeProviders.add(provider);
10
+ return provider;
11
+ };
12
+ var NativeInteractiveNotSupportedError2 = NativeInteractiveNotSupportedError;
13
+ var assertInteractiveSupported = (provider) => {
14
+ if (provider !== void 0 && nativeProviders.has(provider)) {
15
+ throw new NativeInteractiveNotSupportedError2({
16
+ message: `interactive() is not supported on native providers (got ${provider.name}()). Use run(), or pass docker() or noSandbox() to interactive().`,
17
+ provider: provider.name
18
+ });
19
+ }
20
+ };
21
+
22
+ export { NativeInteractiveNotSupportedError2 as NativeInteractiveNotSupportedError, assertInteractiveSupported, markNativeSandboxProvider };
23
+ //# sourceMappingURL=chunk-XCWKLDH4.js.map
24
+ //# sourceMappingURL=chunk-XCWKLDH4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/nativeSandboxProvider.ts"],"names":["NativeInteractiveNotSupportedError"],"mappings":";;;;;;AAUA,IAAM,eAAA,uBAAsB,OAAA,EAAyB;AAG9C,IAAM,yBAAA,GAA4B,CACvC,QAAA,KACM;AACN,EAAA,eAAA,CAAgB,IAAI,QAAQ,CAAA;AAC5B,EAAA,OAAO,QAAA;AACT;AA4BO,IAAMA,mCAAAA,GACX;AAGK,IAAM,0BAAA,GAA6B,CACxC,QAAA,KACS;AACT,EAAA,IAAI,QAAA,KAAa,MAAA,IAAa,eAAA,CAAgB,GAAA,CAAI,QAAQ,CAAA,EAAG;AAC3D,IAAA,MAAM,IAAIA,mCAAAA,CAAmC;AAAA,MAC3C,OAAA,EACE,CAAA,wDAAA,EAA2D,QAAA,CAAS,IAAI,CAAA,iEAAA,CAAA;AAAA,MAE1E,UAAU,QAAA,CAAS;AAAA,KACpB,CAAA;AAAA,EACH;AACF","file":"chunk-XCWKLDH4.js","sourcesContent":["/**\n * Native sandbox providers: bind-mount sandbox providers that contain the\n * agent with the host OS's own process sandbox (Bubblewrap, Seatbelt) instead\n * of a container. They share the \"bind-mount\" tag, so core knows them by a\n * mark set when the provider is constructed.\n */\n\nimport { NativeInteractiveNotSupportedError as NativeInteractiveNotSupportedErrorImpl } from \"./errors.js\";\nimport type { SandboxProvider } from \"./SandboxProvider.js\";\n\nconst nativeProviders = new WeakSet<SandboxProvider>();\n\n/** Marks `provider` as a native sandbox provider, and returns it. */\nexport const markNativeSandboxProvider = <P extends SandboxProvider>(\n provider: P,\n): P => {\n nativeProviders.add(provider);\n return provider;\n};\n\n/**\n * `interactive()` was called with a native sandbox provider (`bwrap()`,\n * `seatbelt()`). Native providers don't run interactive sessions: use `run()`,\n * or pass `docker()` or `noSandbox()` to `interactive()`.\n *\n * Public-facing type for `NativeInteractiveNotSupportedError`. The runtime\n * class is the same `Data.TaggedError` from `errors.ts`, re-declared here as a\n * plain `Error` subclass so that Effect's types stay out of Sandcastle's\n * published `.d.ts` files.\n */\nexport interface NativeInteractiveNotSupportedError extends Error {\n readonly _tag: \"NativeInteractiveNotSupportedError\";\n readonly message: string;\n /** The native sandbox provider `interactive()` was called with. */\n readonly provider: string;\n}\n\ninterface NativeInteractiveNotSupportedErrorConstructor {\n new (args: {\n readonly message: string;\n readonly provider: string;\n }): NativeInteractiveNotSupportedError;\n readonly prototype: NativeInteractiveNotSupportedError;\n}\n\n/** `interactive()` was called with a native sandbox provider. */\nexport const NativeInteractiveNotSupportedError: NativeInteractiveNotSupportedErrorConstructor =\n NativeInteractiveNotSupportedErrorImpl;\n\n/** Throws `NativeInteractiveNotSupportedError` when `provider` is a native sandbox provider. */\nexport const assertInteractiveSupported = (\n provider: SandboxProvider | undefined,\n): void => {\n if (provider !== undefined && nativeProviders.has(provider)) {\n throw new NativeInteractiveNotSupportedError({\n message:\n `interactive() is not supported on native providers (got ${provider.name}()). ` +\n `Use run(), or pass docker() or noSandbox() to interactive().`,\n provider: provider.name,\n });\n }\n};\n"]}
@@ -18,5 +18,5 @@ var createIsolatedSandboxProvider = (config) => ({
18
18
  });
19
19
 
20
20
  export { createBindMountSandboxProvider, createIsolatedSandboxProvider };
21
- //# sourceMappingURL=chunk-BIWNFKGV.js.map
22
- //# sourceMappingURL=chunk-BIWNFKGV.js.map
21
+ //# sourceMappingURL=chunk-XCYK7I45.js.map
22
+ //# sourceMappingURL=chunk-XCYK7I45.js.map