@ai-hero/sandcastle 0.14.0 → 0.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{SandboxProvider-Chsi-Zs6.d.ts → SandboxProvider-CwRLxIXZ.d.ts} +2 -39
- package/dist/{chunk-BVZWLFFT.js → chunk-4BB7DNPW.js} +3 -3
- package/dist/chunk-4BB7DNPW.js.map +1 -0
- package/dist/chunk-4GZMUHVO.js +60 -0
- package/dist/chunk-4GZMUHVO.js.map +1 -0
- package/dist/{chunk-S6UHPTRG.js → chunk-7JUTKCHL.js} +4 -4
- package/dist/{chunk-S6UHPTRG.js.map → chunk-7JUTKCHL.js.map} +1 -1
- package/dist/chunk-7PHPLDVS.js +284 -0
- package/dist/chunk-7PHPLDVS.js.map +1 -0
- package/dist/{chunk-HSXPRZKG.js → chunk-BXLS4HRY.js} +15 -6
- package/dist/chunk-BXLS4HRY.js.map +1 -0
- package/dist/{chunk-G2R53CVZ.js → chunk-EM4QNWKF.js} +695 -706
- package/dist/chunk-EM4QNWKF.js.map +1 -0
- package/dist/{chunk-STB2U7BB.js → chunk-JEQ4IVQM.js} +384 -264
- package/dist/chunk-JEQ4IVQM.js.map +1 -0
- package/dist/{chunk-VRXR2T3S.js → chunk-L3BU47F6.js} +3 -3
- package/dist/{chunk-VRXR2T3S.js.map → chunk-L3BU47F6.js.map} +1 -1
- package/dist/{chunk-7N7AMUYA.js → chunk-PTJEKJPQ.js} +7 -5
- package/dist/chunk-PTJEKJPQ.js.map +1 -0
- package/dist/{chunk-H2PEFS4W.js → chunk-SAQXFLO2.js} +30 -6
- package/dist/chunk-SAQXFLO2.js.map +1 -0
- package/dist/{chunk-ATA2V2TC.js → chunk-TBVRAXYF.js} +3 -3
- package/dist/{chunk-ATA2V2TC.js.map → chunk-TBVRAXYF.js.map} +1 -1
- package/dist/{chunk-IBK2XNSS.js → chunk-VUOXFCWO.js} +3 -3
- package/dist/{chunk-IBK2XNSS.js.map → chunk-VUOXFCWO.js.map} +1 -1
- package/dist/{chunk-GCLEXPXG.js → chunk-WYOGXC72.js} +46 -84
- package/dist/chunk-WYOGXC72.js.map +1 -0
- package/dist/{chunk-RDW7FNN6.js → chunk-YDQW5IOY.js} +11 -4
- package/dist/chunk-YDQW5IOY.js.map +1 -0
- package/dist/index.d.ts +47 -4
- package/dist/index.js +536 -445
- package/dist/index.js.map +1 -1
- package/dist/main.js +72 -16
- package/dist/main.js.map +1 -1
- package/dist/sandboxes/bwrap.d.ts +1 -1
- package/dist/sandboxes/bwrap.js +9 -17
- package/dist/sandboxes/bwrap.js.map +1 -1
- package/dist/sandboxes/daytona.d.ts +1 -1
- package/dist/sandboxes/daytona.js +82 -79
- package/dist/sandboxes/daytona.js.map +1 -1
- package/dist/sandboxes/docker.d.ts +23 -1
- package/dist/sandboxes/docker.js +6 -5
- package/dist/sandboxes/e2b.d.ts +1 -1
- package/dist/sandboxes/e2b.js +4 -4
- package/dist/sandboxes/modal.d.ts +1 -1
- package/dist/sandboxes/modal.js +1 -1
- package/dist/sandboxes/no-sandbox.d.ts +1 -1
- package/dist/sandboxes/no-sandbox.js +1 -1
- package/dist/sandboxes/podman.d.ts +27 -4
- package/dist/sandboxes/podman.js +18 -45
- package/dist/sandboxes/podman.js.map +1 -1
- package/dist/sandboxes/seatbelt.d.ts +2 -2
- package/dist/sandboxes/seatbelt.js +10 -10
- package/dist/sandboxes/seatbelt.js.map +1 -1
- package/dist/sandboxes/sprites.d.ts +1 -1
- package/dist/sandboxes/sprites.js +25 -4
- package/dist/sandboxes/sprites.js.map +1 -1
- package/dist/sandboxes/vercel.d.ts +10 -1
- package/dist/sandboxes/vercel.js +74 -46
- package/dist/sandboxes/vercel.js.map +1 -1
- package/dist/templates/parallel-planner/main.mts +43 -21
- package/dist/templates/parallel-planner-with-review/main.mts +55 -27
- package/dist/templates/sequential-reviewer/main.mts +1 -1
- package/package.json +7 -3
- package/dist/chunk-7N7AMUYA.js.map +0 -1
- package/dist/chunk-BIF2X6QB.js +0 -94
- package/dist/chunk-BIF2X6QB.js.map +0 -1
- package/dist/chunk-BVZWLFFT.js.map +0 -1
- package/dist/chunk-G2R53CVZ.js.map +0 -1
- package/dist/chunk-GCLEXPXG.js.map +0 -1
- package/dist/chunk-H2PEFS4W.js.map +0 -1
- package/dist/chunk-HSXPRZKG.js.map +0 -1
- package/dist/chunk-RDW7FNN6.js.map +0 -1
- package/dist/chunk-STB2U7BB.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { S as SandboxProvider } from '../SandboxProvider-
|
|
1
|
+
import { S as SandboxProvider } from '../SandboxProvider-CwRLxIXZ.js';
|
|
2
2
|
import { M as MountConfig } from '../MountConfig-CmXclHA5.js';
|
|
3
3
|
import { S as SelinuxLabel, L as LinuxCapability } from '../LinuxCapability-B_PQfsY_.js';
|
|
4
4
|
export { d as defaultImageName } from '../LinuxCapability-B_PQfsY_.js';
|
|
@@ -82,12 +82,13 @@ interface PodmanOptions {
|
|
|
82
82
|
* Names are written without the `CAP_` prefix, as `podman run` accepts them,
|
|
83
83
|
* and a misspelt name is a type error:
|
|
84
84
|
*
|
|
85
|
-
* - `["
|
|
86
|
-
* - `["
|
|
85
|
+
* - `["CHOWN"]` → `--cap-drop CHOWN` (no changing file ownership)
|
|
86
|
+
* - `["CHOWN", "SETUID"]` → `--cap-drop CHOWN --cap-drop SETUID`
|
|
87
87
|
* - `["ALL"]` → `--cap-drop ALL` (drop every capability)
|
|
88
88
|
*
|
|
89
89
|
* When omitted, no `--cap-drop` flags are added and the container keeps
|
|
90
|
-
* Podman's default capability set.
|
|
90
|
+
* Podman's default capability set. Note that Podman's defaults already
|
|
91
|
+
* exclude `NET_RAW` and `MKNOD`, so dropping those has no effect.
|
|
91
92
|
*/
|
|
92
93
|
readonly capDrop?: readonly LinuxCapability[];
|
|
93
94
|
/**
|
|
@@ -124,6 +125,28 @@ interface PodmanOptions {
|
|
|
124
125
|
* When omitted, no `--cpus` flag is added and the container is unconstrained.
|
|
125
126
|
*/
|
|
126
127
|
readonly cpus?: number;
|
|
128
|
+
/**
|
|
129
|
+
* Limit the memory available to the container, via `--memory`.
|
|
130
|
+
*
|
|
131
|
+
* Accepts Podman memory strings:
|
|
132
|
+
*
|
|
133
|
+
* - `"2g"` → `--memory 2g --memory-swap 2g`
|
|
134
|
+
* - `"512m"` → `--memory 512m --memory-swap 512m`
|
|
135
|
+
*
|
|
136
|
+
* `--memory-swap` is set to the same value, making this a hard cap with no
|
|
137
|
+
* swap headroom. When omitted, no memory flags are added and the container
|
|
138
|
+
* is unconstrained.
|
|
139
|
+
*/
|
|
140
|
+
readonly memory?: string;
|
|
141
|
+
/**
|
|
142
|
+
* Limit the number of processes in the container, via `--pids-limit`.
|
|
143
|
+
*
|
|
144
|
+
* - `256` → `--pids-limit 256`
|
|
145
|
+
*
|
|
146
|
+
* Useful against fork bombs in untrusted workloads. When omitted, no
|
|
147
|
+
* `--pids-limit` flag is added.
|
|
148
|
+
*/
|
|
149
|
+
readonly pidsLimit?: number;
|
|
127
150
|
}
|
|
128
151
|
/**
|
|
129
152
|
* Create a Podman sandbox provider.
|
package/dist/sandboxes/podman.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';
|
|
2
|
-
import {
|
|
3
|
-
|
|
2
|
+
import { shellArgsReportingExit, collectEngineExec } from '../chunk-4GZMUHVO.js';
|
|
3
|
+
import { resolveUserMounts, processFileMountParents, formatVolumeMount, defaultImageName } from '../chunk-7PHPLDVS.js';
|
|
4
|
+
export { defaultImageName } from '../chunk-7PHPLDVS.js';
|
|
4
5
|
import { registerShutdown } from '../chunk-EXYXBRCX.js';
|
|
5
|
-
import '../chunk-
|
|
6
|
-
import '../chunk-
|
|
7
|
-
import { createBindMountSandboxProvider } from '../chunk-
|
|
8
|
-
import { MAX_TAIL_CHARS
|
|
6
|
+
import '../chunk-YDQW5IOY.js';
|
|
7
|
+
import '../chunk-JEQ4IVQM.js';
|
|
8
|
+
import { createBindMountSandboxProvider } from '../chunk-4BB7DNPW.js';
|
|
9
|
+
import { MAX_TAIL_CHARS } from '../chunk-6NQPCXSG.js';
|
|
9
10
|
import { execFile, execFileSync, spawn } from 'child_process';
|
|
10
11
|
import { randomUUID } from 'crypto';
|
|
11
|
-
import { createInterface } from 'readline';
|
|
12
12
|
|
|
13
13
|
createRequire(import.meta.url);
|
|
14
14
|
var podman = (options) => {
|
|
@@ -66,6 +66,8 @@ var podman = (options) => {
|
|
|
66
66
|
d
|
|
67
67
|
]);
|
|
68
68
|
const cpusArgs = options?.cpus === void 0 ? [] : ["--cpus", String(options.cpus)];
|
|
69
|
+
const memoryArgs = options?.memory === void 0 ? [] : ["--memory", options.memory, "--memory-swap", options.memory];
|
|
70
|
+
const pidsLimitArgs = options?.pidsLimit === void 0 ? [] : ["--pids-limit", String(options.pidsLimit)];
|
|
69
71
|
await new Promise((resolve, reject) => {
|
|
70
72
|
execFile(
|
|
71
73
|
"podman",
|
|
@@ -81,6 +83,8 @@ var podman = (options) => {
|
|
|
81
83
|
...capDropArgs,
|
|
82
84
|
...deviceArgs,
|
|
83
85
|
...cpusArgs,
|
|
86
|
+
...memoryArgs,
|
|
87
|
+
...pidsLimitArgs,
|
|
84
88
|
"-w",
|
|
85
89
|
worktreePath,
|
|
86
90
|
...envArgs,
|
|
@@ -153,7 +157,7 @@ var podman = (options) => {
|
|
|
153
157
|
if (opts?.cwd !== void 0 && opts.cwd !== "") {
|
|
154
158
|
args.push("-w", opts.cwd);
|
|
155
159
|
}
|
|
156
|
-
args.push(containerName,
|
|
160
|
+
args.push(containerName, ...shellArgsReportingExit(command));
|
|
157
161
|
return new Promise((resolve, reject) => {
|
|
158
162
|
const stdin = opts?.stdin;
|
|
159
163
|
const proc = stdin === void 0 ? spawn("podman", args, { stdio: ["ignore", "pipe", "pipe"] }) : spawn("podman", args, { stdio: ["pipe", "pipe", "pipe"] });
|
|
@@ -164,42 +168,11 @@ var podman = (options) => {
|
|
|
164
168
|
proc.on("error", (error) => {
|
|
165
169
|
reject(new Error(`podman exec failed: ${error.message}`));
|
|
166
170
|
});
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
rl.on("line", (line) => {
|
|
173
|
-
stdoutTail.push(line);
|
|
174
|
-
onLine(line);
|
|
175
|
-
});
|
|
176
|
-
proc.stderr.on("data", (chunk) => {
|
|
177
|
-
stderrTail.push(chunk.toString());
|
|
178
|
-
});
|
|
179
|
-
proc.on("close", (code) => {
|
|
180
|
-
resolve({
|
|
181
|
-
stdout: stdoutTail.toString(),
|
|
182
|
-
stderr: stderrTail.toString(),
|
|
183
|
-
exitCode: code ?? 0
|
|
184
|
-
});
|
|
185
|
-
});
|
|
186
|
-
} else {
|
|
187
|
-
const stdoutChunks = [];
|
|
188
|
-
const stderrChunks = [];
|
|
189
|
-
proc.stdout.on("data", (chunk) => {
|
|
190
|
-
stdoutChunks.push(chunk.toString());
|
|
191
|
-
});
|
|
192
|
-
proc.stderr.on("data", (chunk) => {
|
|
193
|
-
stderrChunks.push(chunk.toString());
|
|
194
|
-
});
|
|
195
|
-
proc.on("close", (code) => {
|
|
196
|
-
resolve({
|
|
197
|
-
stdout: stdoutChunks.join(""),
|
|
198
|
-
stderr: stderrChunks.join(""),
|
|
199
|
-
exitCode: code ?? 0
|
|
200
|
-
});
|
|
201
|
-
});
|
|
202
|
-
}
|
|
171
|
+
collectEngineExec(
|
|
172
|
+
proc,
|
|
173
|
+
{ onLine: opts?.onLine, maxOutputTailChars },
|
|
174
|
+
resolve
|
|
175
|
+
);
|
|
203
176
|
});
|
|
204
177
|
},
|
|
205
178
|
interactiveExec: async (args, opts) => new Promise((resolve, reject) => {
|
|
@@ -220,7 +193,7 @@ var podman = (options) => {
|
|
|
220
193
|
reject(new Error(`podman exec failed: ${error.message}`));
|
|
221
194
|
});
|
|
222
195
|
proc.on("close", (code) => {
|
|
223
|
-
resolve({ exitCode: code ??
|
|
196
|
+
resolve({ exitCode: code ?? 1 });
|
|
224
197
|
});
|
|
225
198
|
}),
|
|
226
199
|
copyFileIn: async (hostPath, sandboxPath) => new Promise((resolve, reject) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/sandboxes/podman.ts"],"names":[],"mappings":";;;;;;;;;;;;;AA6JO,IAAM,MAAA,GAAS,CAAC,OAAA,KAA6C;AAClE,EAAA,MAAM,sBAAsB,OAAA,EAAS,SAAA;AACrC,EAAA,MAAM,YAAA,GAAe,SAAS,YAAA,IAAgB,GAAA;AAC9C,EAAA,MAAM,MAAA,GAAS,SAAS,MAAA,IAAU,SAAA;AAClC,EAAA,MAAM,YAAA,GAAe,SAAS,YAAA,IAAgB,GAAA;AAC9C,EAAA,MAAM,YAAA,GAAe,SAAS,YAAA,IAAgB,GAAA;AAC9C,EAAA,MAAM,kBAAA,GAAqB,SAAS,kBAAA,IAAsB,cAAA;AAC1D,EAAA,MAAM,cAAA,GAAiB,aAAA;AACvB,EAAA,MAAM,UAAA,GAAa,SAAS,MAAA,GACxB,iBAAA,CAAkB,QAAQ,MAAA,EAAQ,cAAc,IAChD,EAAC;AAGL,EAAA,MAAM,kBAAA,GAAqB,uBAAA;AAAA,IACzB,UAAA;AAAA,IACA;AAAA,GACF;AAEA,EAAA,OAAO,8BAAA,CAA+B;AAAA,IACpC,IAAA,EAAM,QAAA;AAAA,IACN,KAAK,OAAA,EAAS,GAAA;AAAA,IACd,cAAA;AAAA,IACA,MAAA,EAAQ,OACN,aAAA,KACoC;AACpC,MAAA,MAAM,aAAA,GAAgB,CAAA,WAAA,EAAc,UAAA,EAAY,CAAA,CAAA;AAEhD,MAAA,MAAM,YAAA,GACJ,cAAc,MAAA,CAAO,IAAA;AAAA,QACnB,CAAC,CAAA,KAAM,CAAA,CAAE,QAAA,KAAa,aAAA,CAAc;AAAA,SACnC,WAAA,IAAe,uBAAA;AAGpB,MAAA,MAAM,YAAY,CAAC,GAAG,aAAA,CAAc,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A;AAAA,EACF;AACF,CAAA;AAEF,IAAM,qBAAqB,YACzB,IAAI,OAAA,CAAc,CAAC,SAAS,MAAA,KAAW;AACrC,EAAA,QAAA;AAAA,IACE,QAAA;AAAA,IACA,CAAC,SAAA,EAAW,MAAA,EAAQ,UAAA,EAAY,MAAM,CAAA;AAAA,IACtC,CAAC,OAAO,MAAA,KAAW;AACjB,MAAA,IAAI,KAAA,EAAO;AACT,QAAA,MAAA,CAAO,oBAAoB,CAAA;AAC3B,QAAA;AAAA,MACF;AACA,MAAA,IAAI;AACF,QAAA,MAAM,QAAA,GAAoB,IAAA,CAAK,KAAA,CAAM,MAAM,CAAA;AAC3C,QAAA,IACE,KAAA,CAAM,OAAA,CAAQ,QAAQ,CAAA,IACtB,QAAA,CAAS,IAAA,CAAK,CAAC,CAAA,KAAM,gBAAA,CAAiB,CAAC,CAAC,CAAA,EACxC;AACA,UAAA,OAAA,EAAQ;AAAA,QACV,CAAA,MAAO;AACL,UAAA,MAAA,CAAO,oBAAoB,CAAA;AAAA,QAC7B;AAAA,MACF,CAAA,CAAA,MAAQ;AACN,QAAA,MAAA,CAAO,oBAAoB,CAAA;AAAA,MAC7B;AAAA,IACF;AAAA,GACF;AACF,CAAC,CAAA;AAGH,IAAM,gBAAA,GAAmB,CAAC,OAAA,KACxB,OAAO,OAAA,KAAY,QAAA,IACnB,OAAA,KAAY,IAAA,IACZ,SAAA,IAAa,OAAA,IACb,OAAA,CAAQ,OAAA,KAAY,IAAA","file":"podman.js","sourcesContent":["/**\n * Podman sandbox provider — creates Podman containers with bind-mounts.\n *\n * Usage:\n * import { podman } from \"sandcastle/sandboxes/podman\";\n * await run({ agent: claudeCode(\"claude-opus-4-8\"), sandbox: podman() });\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 { 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 type { LinuxCapability } from \"../LinuxCapability.js\";\nimport {\n defaultImageName,\n resolveUserMounts,\n formatVolumeMount,\n processFileMountParents,\n} from \"../mountUtils.js\";\nimport { BoundedTail, MAX_TAIL_CHARS } from \"../boundedTail.js\";\nimport { registerShutdown } from \"../shutdownRegistry.js\";\n\nexport type { LinuxCapability } from \"../LinuxCapability.js\";\n\nexport interface PodmanOptions {\n /** Podman image name (default: derived from repo directory name). */\n readonly imageName?: string;\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 * User namespace mode for rootless Podman.\n *\n * - `\"keep-id\"` (default) — maps host UID to `containerUid` inside the\n * container via `--userns=keep-id:uid=N,gid=N`, so both bind-mounted\n * files and image-built files have correct ownership without chown.\n * - `false` — disable; use for rootful Podman setups.\n */\n readonly userns?: \"keep-id\" | false;\n /**\n * The UID of the `agent` user inside the container image (default: 1000).\n *\n * Must match the UID set in the Containerfile. Used with `--userns=keep-id`\n * to map the host user to this UID inside the container.\n */\n readonly containerUid?: number;\n /**\n * The GID of the `agent` user inside the container image (default: 1000).\n *\n * Must match the GID set in the Containerfile. Used with `--userns=keep-id`\n * to map the host group to this GID inside the container.\n */\n readonly containerGid?: number;\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 * Podman 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, Podman's default 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 `podman 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 * Podman'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 * Under rootless Podman, exposing a host device often requires host-side\n * group/permission setup and may interact with `--userns=keep-id`.\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 `podman 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 Podman sandbox provider.\n *\n * The returned provider creates Podman containers with bind-mounts\n * for the worktree and git directories. Calls the `podman` binary\n * on PATH directly. On macOS/Windows, verifies that a Podman Machine\n * is running before container creation.\n */\nexport const podman = (options?: PodmanOptions): SandboxProvider => {\n const configuredImageName = options?.imageName;\n const selinuxLabel = options?.selinuxLabel ?? \"z\";\n const userns = options?.userns ?? \"keep-id\";\n const containerUid = options?.containerUid ?? 1000;\n const containerGid = options?.containerGid ?? 1000;\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: \"podman\",\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 strings with optional SELinux label (internal + user mounts)\n const allMounts = [...createOptions.mounts, ...userMounts];\n const volumeMounts = allMounts.map((m) =>\n formatVolumeMount(m, selinuxLabel),\n );\n\n // Resolve image name\n const imageName =\n configuredImageName ?? defaultImageName(createOptions.hostRepoPath);\n\n // Pre-flight: check Podman Machine on macOS/Windows\n if (process.platform === \"darwin\" || process.platform === \"win32\") {\n await checkPodmanMachine();\n }\n\n // Pre-flight: verify image exists locally\n await checkImageExists(imageName);\n\n const env = { ...createOptions.env, HOME: \"/home/agent\" };\n const envArgs = Object.entries(env).flatMap(([key, value]) => [\n \"-e\",\n `${key}=${value}`,\n ]);\n const volumeArgs = volumeMounts.flatMap((v) => [\"-v\", v]);\n const usernsArgs =\n userns === false\n ? []\n : [`--userns=keep-id:uid=${containerUid},gid=${containerGid}`];\n const userArgs = [\"--user\", `${containerUid}:${containerGid}`];\n const network = options?.network;\n const networks =\n network === undefined || network === \"\" ? [] : [network].flat();\n const networkArgs = networks.flatMap((n) => [\"--network\", n]);\n const groupArgs = (options?.groups ?? []).flatMap((g) => [\n \"--group-add\",\n String(g),\n ]);\n const capDropArgs = (options?.capDrop ?? []).flatMap((cap) => [\n \"--cap-drop\",\n cap,\n ]);\n const deviceArgs = (options?.devices ?? []).flatMap((d) => [\n \"--device\",\n d,\n ]);\n const cpusArgs =\n options?.cpus === undefined ? [] : [\"--cpus\", String(options.cpus)];\n\n // Start container via podman run\n await new Promise<void>((resolve, reject) => {\n execFile(\n \"podman\",\n [\n \"run\",\n \"-d\",\n \"--name\",\n containerName,\n ...userArgs,\n ...usernsArgs,\n ...networkArgs,\n ...groupArgs,\n ...capDropArgs,\n ...deviceArgs,\n ...cpusArgs,\n \"-w\",\n worktreePath,\n ...envArgs,\n ...volumeArgs,\n \"--entrypoint\",\n \"sleep\",\n imageName,\n \"infinity\",\n ],\n (error) => {\n if (error) {\n reject(new Error(`podman run failed: ${error.message}`));\n } else {\n resolve();\n }\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 \"podman\",\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 // `--time 0`: PID 1 is `sleep infinity`, which ignores SIGTERM, so a\n // plain `rm -f` waits out the 10 s StopTimeout before SIGKILL. The 5 s\n // timeout below would kill that `rm` mid-stop and leave the container\n // in `Stopping` indefinitely.\n const removeContainerSync = () => {\n try {\n execFileSync(\"podman\", [\"rm\", \"-f\", \"--time\", \"0\", containerName], {\n stdio: \"ignore\",\n timeout: 5000,\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(\"podman\", args, { stdio: [\"ignore\", \"pipe\", \"pipe\"] })\n : spawn(\"podman\", 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(`podman 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 podmanArgs = [\"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 podmanArgs.push(\"-it\");\n } else {\n podmanArgs.push(\"-i\");\n }\n if (opts.cwd !== undefined && opts.cwd !== \"\") {\n podmanArgs.push(\"-w\", opts.cwd);\n }\n podmanArgs.push(containerName, ...args);\n\n const proc = spawn(\"podman\", podmanArgs, {\n stdio: [opts.stdin, opts.stdout, opts.stderr] as StdioOptions,\n });\n\n proc.on(\"error\", (error: Error) => {\n reject(new Error(`podman 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 \"podman\",\n [\"cp\", hostPath, `${containerName}:${sandboxPath}`],\n (error) => {\n if (error) {\n reject(new Error(`podman 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 \"podman\",\n [\"cp\", `${containerName}:${sandboxPath}`, hostPath],\n (error) => {\n if (error) {\n reject(new Error(`podman cp (out) failed: ${error.message}`));\n } else {\n resolve();\n }\n },\n );\n }),\n\n close: async (): Promise<void> => {\n unregisterShutdown();\n await new Promise<void>((resolve, reject) => {\n execFile(\n \"podman\",\n [\"rm\", \"-f\", \"--time\", \"0\", containerName],\n (error) => {\n if (error) {\n reject(new Error(`podman rm failed: ${error.message}`));\n } else {\n resolve();\n }\n },\n );\n });\n },\n };\n\n return handle;\n },\n });\n};\n\n// Re-export for backwards compatibility\nexport { defaultImageName } from \"../mountUtils.js\";\n\nconst checkImageExists = async (imageName: string): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n execFile(\"podman\", [\"image\", \"inspect\", imageName], (error) => {\n if (error) {\n reject(\n new Error(\n `Image '${imageName}' not found locally. Build it first with 'podman build -t ${imageName} .'`,\n ),\n );\n } else {\n resolve();\n }\n });\n });\n\nconst podmanMachineError = () =>\n new Error(\n \"Podman Machine is not running. Run 'podman machine init && podman machine start' first.\",\n );\n\nconst checkPodmanMachine = async (): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n execFile(\n \"podman\",\n [\"machine\", \"list\", \"--format\", \"json\"],\n (error, stdout) => {\n if (error) {\n reject(podmanMachineError());\n return;\n }\n try {\n const machines: unknown = JSON.parse(stdout);\n if (\n Array.isArray(machines) &&\n machines.some((m) => isRunningMachine(m))\n ) {\n resolve();\n } else {\n reject(podmanMachineError());\n }\n } catch {\n reject(podmanMachineError());\n }\n },\n );\n });\n\n/** One entry of `podman machine list --format json` that reports it is running. */\nconst isRunningMachine = (machine: unknown): boolean =>\n typeof machine === \"object\" &&\n machine !== null &&\n \"Running\" in machine &&\n machine.Running === true;\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/sandboxes/podman.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAuLO,IAAM,MAAA,GAAS,CAAC,OAAA,KAA6C;AAClE,EAAA,MAAM,sBAAsB,OAAA,EAAS,SAAA;AACrC,EAAA,MAAM,YAAA,GAAe,SAAS,YAAA,IAAgB,GAAA;AAC9C,EAAA,MAAM,MAAA,GAAS,SAAS,MAAA,IAAU,SAAA;AAClC,EAAA,MAAM,YAAA,GAAe,SAAS,YAAA,IAAgB,GAAA;AAC9C,EAAA,MAAM,YAAA,GAAe,SAAS,YAAA,IAAgB,GAAA;AAC9C,EAAA,MAAM,kBAAA,GAAqB,SAAS,kBAAA,IAAsB,cAAA;AAC1D,EAAA,MAAM,cAAA,GAAiB,aAAA;AACvB,EAAA,MAAM,UAAA,GAAa,SAAS,MAAA,GACxB,iBAAA,CAAkB,QAAQ,MAAA,EAAQ,cAAc,IAChD,EAAC;AAGL,EAAA,MAAM,kBAAA,GAAqB,uBAAA;AAAA,IACzB,UAAA;AAAA,IACA;AAAA,GACF;AAEA,EAAA,OAAO,8BAAA,CAA+B;AAAA,IACpC,IAAA,EAAM,QAAA;AAAA,IACN,KAAK,OAAA,EAAS,GAAA;AAAA,IACd,cAAA;AAAA,IACA,MAAA,EAAQ,OACN,aAAA,KACoC;AACpC,MAAA,MAAM,aAAA,GAAgB,CAAA,WAAA,EAAc,UAAA,EAAY,CAAA,CAAA;AAEhD,MAAA,MAAM,YAAA,GACJ,cAAc,MAAA,CAAO,IAAA;AAAA,QACnB,CAAC,CAAA,KAAM,CAAA,CAAE,QAAA,KAAa,aAAA,CAAc;AAAA,SACnC,WAAA,IAAe,uBAAA;AAGpB,MAAA,MAAM,YAAY,CAAC,GAAG,aAAA,CAAc,MAAA,EAAQ,GAAG,UAAU,CAAA;AAC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AAM,kBAAA,GAAqB,MACzB,IAAI,KAAA;AAAA,EACF;AACF,CAAA;AAEF,IAAM,qBAAqB,YACzB,IAAI,OAAA,CAAc,CAAC,SAAS,MAAA,KAAW;AACrC,EAAA,QAAA;AAAA,IACE,QAAA;AAAA,IACA,CAAC,SAAA,EAAW,MAAA,EAAQ,UAAA,EAAY,MAAM,CAAA;AAAA,IACtC,CAAC,OAAO,MAAA,KAAW;AACjB,MAAA,IAAI,KAAA,EAAO;AACT,QAAA,MAAA,CAAO,oBAAoB,CAAA;AAC3B,QAAA;AAAA,MACF;AACA,MAAA,IAAI;AACF,QAAA,MAAM,QAAA,GAAoB,IAAA,CAAK,KAAA,CAAM,MAAM,CAAA;AAC3C,QAAA,IACE,KAAA,CAAM,OAAA,CAAQ,QAAQ,CAAA,IACtB,QAAA,CAAS,IAAA,CAAK,CAAC,CAAA,KAAM,gBAAA,CAAiB,CAAC,CAAC,CAAA,EACxC;AACA,UAAA,OAAA,EAAQ;AAAA,QACV,CAAA,MAAO;AACL,UAAA,MAAA,CAAO,oBAAoB,CAAA;AAAA,QAC7B;AAAA,MACF,CAAA,CAAA,MAAQ;AACN,QAAA,MAAA,CAAO,oBAAoB,CAAA;AAAA,MAC7B;AAAA,IACF;AAAA,GACF;AACF,CAAC,CAAA;AAGH,IAAM,gBAAA,GAAmB,CAAC,OAAA,KACxB,OAAO,OAAA,KAAY,QAAA,IACnB,OAAA,KAAY,IAAA,IACZ,SAAA,IAAa,OAAA,IACb,OAAA,CAAQ,OAAA,KAAY,IAAA","file":"podman.js","sourcesContent":["/**\n * Podman sandbox provider — creates Podman containers with bind-mounts.\n *\n * Usage:\n * import { podman } from \"sandcastle/sandboxes/podman\";\n * await run({ agent: claudeCode(\"claude-opus-4-8\"), sandbox: podman() });\n */\n\nimport { execFile, execFileSync, spawn } from \"node:child_process\";\nimport type { StdioOptions } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport { createBindMountSandboxProvider } from \"../SandboxProvider.js\";\nimport {\n collectEngineExec,\n shellArgsReportingExit,\n} from \"./engineExitStatus.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 type { LinuxCapability } from \"../LinuxCapability.js\";\nimport {\n defaultImageName,\n resolveUserMounts,\n formatVolumeMount,\n processFileMountParents,\n} from \"../mountUtils.js\";\nimport { MAX_TAIL_CHARS } from \"../boundedTail.js\";\nimport { registerShutdown } from \"../shutdownRegistry.js\";\n\nexport type { LinuxCapability } from \"../LinuxCapability.js\";\n\nexport interface PodmanOptions {\n /** Podman image name (default: derived from repo directory name). */\n readonly imageName?: string;\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 * User namespace mode for rootless Podman.\n *\n * - `\"keep-id\"` (default) — maps host UID to `containerUid` inside the\n * container via `--userns=keep-id:uid=N,gid=N`, so both bind-mounted\n * files and image-built files have correct ownership without chown.\n * - `false` — disable; use for rootful Podman setups.\n */\n readonly userns?: \"keep-id\" | false;\n /**\n * The UID of the `agent` user inside the container image (default: 1000).\n *\n * Must match the UID set in the Containerfile. Used with `--userns=keep-id`\n * to map the host user to this UID inside the container.\n */\n readonly containerUid?: number;\n /**\n * The GID of the `agent` user inside the container image (default: 1000).\n *\n * Must match the GID set in the Containerfile. Used with `--userns=keep-id`\n * to map the host group to this GID inside the container.\n */\n readonly containerGid?: number;\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 * Podman 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, Podman's default 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 `podman run` accepts them,\n * and a misspelt name is a type error:\n *\n * - `[\"CHOWN\"]` → `--cap-drop CHOWN` (no changing file ownership)\n * - `[\"CHOWN\", \"SETUID\"]` → `--cap-drop CHOWN --cap-drop SETUID`\n * - `[\"ALL\"]` → `--cap-drop ALL` (drop every capability)\n *\n * When omitted, no `--cap-drop` flags are added and the container keeps\n * Podman's default capability set. Note that Podman's defaults already\n * exclude `NET_RAW` and `MKNOD`, so dropping those has no effect.\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 * Under rootless Podman, exposing a host device often requires host-side\n * group/permission setup and may interact with `--userns=keep-id`.\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 `podman 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 * Limit the memory available to the container, via `--memory`.\n *\n * Accepts Podman memory strings:\n *\n * - `\"2g\"` → `--memory 2g --memory-swap 2g`\n * - `\"512m\"` → `--memory 512m --memory-swap 512m`\n *\n * `--memory-swap` is set to the same value, making this a hard cap with no\n * swap headroom. When omitted, no memory flags are added and the container\n * is unconstrained.\n */\n readonly memory?: string;\n /**\n * Limit the number of processes in the container, via `--pids-limit`.\n *\n * - `256` → `--pids-limit 256`\n *\n * Useful against fork bombs in untrusted workloads. When omitted, no\n * `--pids-limit` flag is added.\n */\n readonly pidsLimit?: number;\n}\n\n/**\n * Create a Podman sandbox provider.\n *\n * The returned provider creates Podman containers with bind-mounts\n * for the worktree and git directories. Calls the `podman` binary\n * on PATH directly. On macOS/Windows, verifies that a Podman Machine\n * is running before container creation.\n */\nexport const podman = (options?: PodmanOptions): SandboxProvider => {\n const configuredImageName = options?.imageName;\n const selinuxLabel = options?.selinuxLabel ?? \"z\";\n const userns = options?.userns ?? \"keep-id\";\n const containerUid = options?.containerUid ?? 1000;\n const containerGid = options?.containerGid ?? 1000;\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: \"podman\",\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 strings with optional SELinux label (internal + user mounts)\n const allMounts = [...createOptions.mounts, ...userMounts];\n const volumeMounts = allMounts.map((m) =>\n formatVolumeMount(m, selinuxLabel),\n );\n\n // Resolve image name\n const imageName =\n configuredImageName ?? defaultImageName(createOptions.hostRepoPath);\n\n // Pre-flight: check Podman Machine on macOS/Windows\n if (process.platform === \"darwin\" || process.platform === \"win32\") {\n await checkPodmanMachine();\n }\n\n // Pre-flight: verify image exists locally\n await checkImageExists(imageName);\n\n const env = { ...createOptions.env, HOME: \"/home/agent\" };\n const envArgs = Object.entries(env).flatMap(([key, value]) => [\n \"-e\",\n `${key}=${value}`,\n ]);\n const volumeArgs = volumeMounts.flatMap((v) => [\"-v\", v]);\n const usernsArgs =\n userns === false\n ? []\n : [`--userns=keep-id:uid=${containerUid},gid=${containerGid}`];\n const userArgs = [\"--user\", `${containerUid}:${containerGid}`];\n const network = options?.network;\n const networks =\n network === undefined || network === \"\" ? [] : [network].flat();\n const networkArgs = networks.flatMap((n) => [\"--network\", n]);\n const groupArgs = (options?.groups ?? []).flatMap((g) => [\n \"--group-add\",\n String(g),\n ]);\n const capDropArgs = (options?.capDrop ?? []).flatMap((cap) => [\n \"--cap-drop\",\n cap,\n ]);\n const deviceArgs = (options?.devices ?? []).flatMap((d) => [\n \"--device\",\n d,\n ]);\n const cpusArgs =\n options?.cpus === undefined ? [] : [\"--cpus\", String(options.cpus)];\n const memoryArgs =\n options?.memory === undefined\n ? []\n : [\"--memory\", options.memory, \"--memory-swap\", options.memory];\n const pidsLimitArgs =\n options?.pidsLimit === undefined\n ? []\n : [\"--pids-limit\", String(options.pidsLimit)];\n\n // Start container via podman run\n await new Promise<void>((resolve, reject) => {\n execFile(\n \"podman\",\n [\n \"run\",\n \"-d\",\n \"--name\",\n containerName,\n ...userArgs,\n ...usernsArgs,\n ...networkArgs,\n ...groupArgs,\n ...capDropArgs,\n ...deviceArgs,\n ...cpusArgs,\n ...memoryArgs,\n ...pidsLimitArgs,\n \"-w\",\n worktreePath,\n ...envArgs,\n ...volumeArgs,\n \"--entrypoint\",\n \"sleep\",\n imageName,\n \"infinity\",\n ],\n (error) => {\n if (error) {\n reject(new Error(`podman run failed: ${error.message}`));\n } else {\n resolve();\n }\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 \"podman\",\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 // `--time 0`: PID 1 is `sleep infinity`, which ignores SIGTERM, so a\n // plain `rm -f` waits out the 10 s StopTimeout before SIGKILL. The 5 s\n // timeout below would kill that `rm` mid-stop and leave the container\n // in `Stopping` indefinitely.\n const removeContainerSync = () => {\n try {\n execFileSync(\"podman\", [\"rm\", \"-f\", \"--time\", \"0\", containerName], {\n stdio: \"ignore\",\n timeout: 5000,\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, ...shellArgsReportingExit(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(\"podman\", args, { stdio: [\"ignore\", \"pipe\", \"pipe\"] })\n : spawn(\"podman\", 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(`podman exec failed: ${error.message}`));\n });\n\n collectEngineExec(\n proc,\n { onLine: opts?.onLine, maxOutputTailChars },\n resolve,\n );\n });\n },\n\n interactiveExec: async (\n args: string[],\n opts: InteractiveExecOptions,\n ): Promise<{ exitCode: number }> =>\n new Promise((resolve, reject) => {\n const podmanArgs = [\"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 podmanArgs.push(\"-it\");\n } else {\n podmanArgs.push(\"-i\");\n }\n if (opts.cwd !== undefined && opts.cwd !== \"\") {\n podmanArgs.push(\"-w\", opts.cwd);\n }\n podmanArgs.push(containerName, ...args);\n\n const proc = spawn(\"podman\", podmanArgs, {\n stdio: [opts.stdin, opts.stdout, opts.stderr] as StdioOptions,\n });\n\n proc.on(\"error\", (error: Error) => {\n reject(new Error(`podman exec failed: ${error.message}`));\n });\n\n proc.on(\"close\", (code: number | null) => {\n resolve({ exitCode: code ?? 1 });\n });\n }),\n copyFileIn: async (\n hostPath: string,\n sandboxPath: string,\n ): Promise<void> =>\n new Promise((resolve, reject) => {\n execFile(\n \"podman\",\n [\"cp\", hostPath, `${containerName}:${sandboxPath}`],\n (error) => {\n if (error) {\n reject(new Error(`podman 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 \"podman\",\n [\"cp\", `${containerName}:${sandboxPath}`, hostPath],\n (error) => {\n if (error) {\n reject(new Error(`podman cp (out) failed: ${error.message}`));\n } else {\n resolve();\n }\n },\n );\n }),\n\n close: async (): Promise<void> => {\n unregisterShutdown();\n await new Promise<void>((resolve, reject) => {\n execFile(\n \"podman\",\n [\"rm\", \"-f\", \"--time\", \"0\", containerName],\n (error) => {\n if (error) {\n reject(new Error(`podman rm failed: ${error.message}`));\n } else {\n resolve();\n }\n },\n );\n });\n },\n };\n\n return handle;\n },\n });\n};\n\n// Re-export for backwards compatibility\nexport { defaultImageName } from \"../mountUtils.js\";\n\nconst checkImageExists = async (imageName: string): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n execFile(\"podman\", [\"image\", \"inspect\", imageName], (error) => {\n if (error) {\n reject(\n new Error(\n `Image '${imageName}' not found locally. Build it first with 'podman build -t ${imageName} .'`,\n ),\n );\n } else {\n resolve();\n }\n });\n });\n\nconst podmanMachineError = () =>\n new Error(\n \"Podman Machine is not running. Run 'podman machine init && podman machine start' first.\",\n );\n\nconst checkPodmanMachine = async (): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n execFile(\n \"podman\",\n [\"machine\", \"list\", \"--format\", \"json\"],\n (error, stdout) => {\n if (error) {\n reject(podmanMachineError());\n return;\n }\n try {\n const machines: unknown = JSON.parse(stdout);\n if (\n Array.isArray(machines) &&\n machines.some((m) => isRunningMachine(m))\n ) {\n resolve();\n } else {\n reject(podmanMachineError());\n }\n } catch {\n reject(podmanMachineError());\n }\n },\n );\n });\n\n/** One entry of `podman machine list --format json` that reports it is running. */\nconst isRunningMachine = (machine: unknown): boolean =>\n typeof machine === \"object\" &&\n machine !== null &&\n \"Running\" in machine &&\n machine.Running === true;\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { B as BindMountSandboxProvider } from '../SandboxProvider-
|
|
1
|
+
import { B as BindMountSandboxProvider } from '../SandboxProvider-CwRLxIXZ.js';
|
|
2
2
|
import { M as MountConfig } from '../MountConfig-CmXclHA5.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -46,7 +46,7 @@ interface SeatbeltOptions {
|
|
|
46
46
|
* aside. It can't signal host processes, but Seatbelt can't fully hide them.
|
|
47
47
|
* The private home is exposed to Sandcastle as `/home/agent`: copies to and
|
|
48
48
|
* from paths under it land in the private dir. Both private dirs are removed
|
|
49
|
-
* on close, and every process an `exec` started is killed when it exits, on
|
|
49
|
+
* on close and on shutdown (SIGINT, SIGTERM, exit), and every process an `exec` started is killed when it exits, on
|
|
50
50
|
* close, on shutdown and when this Node process is hard-killed (a detached
|
|
51
51
|
* host watchdog per `exec` does that). The toolchain comes from the host
|
|
52
52
|
* `PATH`: each `PATH` dir (never the home dir or an ancestor of it) and the
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';
|
|
2
|
-
import { resolveIdentityMounts, copyCreatingParents, collectOutput, hostPathToolchainFromEnv } from '../chunk-
|
|
3
|
-
import { markNativeSandboxProvider } from '../chunk-
|
|
4
|
-
import { assertSeatbeltUsable, SANDBOX_EXEC } from '../chunk-
|
|
5
|
-
import { NodeFileSystem_exports } from '../chunk-
|
|
6
|
-
import '../chunk-
|
|
7
|
-
import
|
|
8
|
-
import { FileSystem_exports, SeatbeltError } from '../chunk-
|
|
9
|
-
import { Effect_exports, Option_exports } from '../chunk-
|
|
10
|
-
import { createBindMountSandboxProvider } from '../chunk-
|
|
2
|
+
import { resolveIdentityMounts, registerNativeSandboxShutdown, copyCreatingParents, collectOutput, hostPathToolchainFromEnv } from '../chunk-BXLS4HRY.js';
|
|
3
|
+
import { markNativeSandboxProvider } from '../chunk-L3BU47F6.js';
|
|
4
|
+
import { assertSeatbeltUsable, SANDBOX_EXEC } from '../chunk-VUOXFCWO.js';
|
|
5
|
+
import { NodeFileSystem_exports } from '../chunk-7JUTKCHL.js';
|
|
6
|
+
import '../chunk-7PHPLDVS.js';
|
|
7
|
+
import '../chunk-EXYXBRCX.js';
|
|
8
|
+
import { FileSystem_exports, SeatbeltError } from '../chunk-YDQW5IOY.js';
|
|
9
|
+
import { Effect_exports, Option_exports } from '../chunk-JEQ4IVQM.js';
|
|
10
|
+
import { createBindMountSandboxProvider } from '../chunk-4BB7DNPW.js';
|
|
11
11
|
import { MAX_TAIL_CHARS } from '../chunk-6NQPCXSG.js';
|
|
12
12
|
import { spawn } from 'child_process';
|
|
13
13
|
import { once } from 'events';
|
|
@@ -372,7 +372,7 @@ var createHandle = async (options, config) => {
|
|
|
372
372
|
killGroup(proc);
|
|
373
373
|
}
|
|
374
374
|
};
|
|
375
|
-
const unregisterShutdown =
|
|
375
|
+
const unregisterShutdown = registerNativeSandboxShutdown(killAll, dirs);
|
|
376
376
|
let closed = false;
|
|
377
377
|
const hostPathOf = (p) => toHostPath(p, dirs, options.mounts);
|
|
378
378
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/seatbeltProfile.ts","../../src/seatbeltSandbox.ts","../../src/sandboxes/seatbelt.ts"],"names":["isWithin","posix"],"mappings":";;;;;;;;;;;;;;;;;AAiDO,IAAM,iBAAA,GAAuC;AAAA,EAClD,MAAA;AAAA,EACA,OAAA;AAAA,EACA,MAAA;AAAA,EACA,SAAA;AAAA,EACA,UAAA;AAAA,EACA,MAAA;AAAA,EACA,cAAA;AAAA,EACA,iBAAA;AAAA;AAAA,EAEA;AACF,CAAA;AAGA,IAAM,0BAAA,GAA6B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AAA,EAAQ,OAAO,aAAA,KACb,YAAA,CAAa,eAAe,EAAE,YAAA,EAAc,YAAY;AAAA,KAC3D;AAAA,GACH;AACF","file":"seatbelt.js","sourcesContent":["/**\n * Builds the Seatbelt (SBPL) profile a `seatbelt()` sandbox runs under, and\n * the `-D` parameters that carry its paths. Pure and provider-agnostic: it\n * takes paths and returns text. No path is ever written into the profile\n * text: every one is a `(param \"…\")` passed to `sandbox-exec` with `-D`, so\n * there is nothing to escape.\n *\n * Hand-rolled, with no dependency on the projects its rule shapes come from:\n *\n * - OpenAI Codex (Apache-2.0, https://github.com/openai/codex,\n * codex-rs/sandboxing/src/seatbelt_base_policy.sbpl,\n * seatbelt_read_only_platform_defaults.sbpl, seatbelt_network_policy.sbpl\n * and seatbelt.rs): the deny-default base, the sysctl list (no\n * `kern.proc.all`), the platform defaults, the `-D` parameter pattern, the\n * `file-write-unlink` denies on protected ancestors, and the fcntl and XPC\n * denies.\n * - Google Gemini CLI (Apache-2.0, https://github.com/google-gemini/gemini-cli,\n * packages/cli/src/utils/sandbox-macos-*.sb): the Docker, Colima and\n * OrbStack socket denies.\n * - Microsoft MXC (MIT, https://github.com/microsoft/mxc,\n * docs/backends/seatbelt/seatbelt-backend.md): the read-only system\n * baseline and the developer dir.\n */\n\nimport { posix } from \"node:path\";\n\n/** What a `seatbelt()` sandbox may read and write. Every path is a real host path. */\nexport interface SeatbeltPolicyInput {\n /** Dirs the sandbox may read (and map executable code from), but not write. */\n readonly readableRoots: readonly string[];\n /** Dirs the sandbox may read and write: the worktree, writable git dirs, private dirs. */\n readonly writableRoots: readonly string[];\n /**\n * Files and dirs that stay read-only even inside a writable root (the\n * #1261 git control files). Their ancestors inside a writable root can't\n * be renamed or removed either, so they can't be moved aside.\n */\n readonly protectedPaths: readonly string[];\n /** The host home dir, for the container-engine socket denies. */\n readonly hostHome: string;\n}\n\n/** A Seatbelt profile and the `-D` parameters its `(param …)`s name. */\nexport interface SeatbeltPolicy {\n readonly profile: string;\n readonly params: readonly (readonly [key: string, value: string])[];\n}\n\n/** The system dirs every sandbox may read: MXC's baseline, Homebrew and `/opt`. */\nexport const SYSTEM_READ_ROOTS: readonly string[] = [\n \"/bin\",\n \"/sbin\",\n \"/usr\",\n \"/System\",\n \"/Library\",\n \"/opt\",\n \"/private/etc\",\n \"/private/var/db\",\n // `/bin/sh` picks the shell it runs from here.\n \"/private/var/select\",\n];\n\n/** Container-engine sockets and state under the host home, never reachable. */\nconst CONTAINER_ENGINE_HOME_DIRS = [\n \".docker\",\n \".colima\",\n \".orbstack\",\n \".lima\",\n \".rd\",\n];\n\nconst CONTAINER_ENGINE_SOCKETS = [\n \"/private/var/run/docker.sock\",\n \"/private/var/run/com.docker.vmnetd.sock\",\n];\n\n/** Deny-default, processes, sysctls and system services (after Codex's base policy). */\nconst BASE = String.raw`(version 1)\n(deny default)\n\n(allow process-exec)\n(allow process-fork)\n(allow signal (target same-sandbox))\n(allow process-info* (target same-sandbox))\n\n(allow sysctl-read\n (sysctl-name \"hw.activecpu\")\n (sysctl-name \"hw.busfrequency_compat\")\n (sysctl-name \"hw.byteorder\")\n (sysctl-name \"hw.cacheconfig\")\n (sysctl-name \"hw.cachelinesize_compat\")\n (sysctl-name \"hw.cpufamily\")\n (sysctl-name \"hw.cpufrequency_compat\")\n (sysctl-name \"hw.cputype\")\n (sysctl-name \"hw.l1dcachesize_compat\")\n (sysctl-name \"hw.l1icachesize_compat\")\n (sysctl-name \"hw.l2cachesize_compat\")\n (sysctl-name \"hw.l3cachesize_compat\")\n (sysctl-name \"hw.logicalcpu_max\")\n (sysctl-name \"hw.machine\")\n (sysctl-name \"hw.model\")\n (sysctl-name \"hw.memsize\")\n (sysctl-name \"hw.ncpu\")\n (sysctl-name \"hw.nperflevels\")\n (sysctl-name-prefix \"hw.optional.arm.\")\n (sysctl-name-prefix \"hw.optional.armv8_\")\n (sysctl-name \"hw.packages\")\n (sysctl-name \"hw.pagesize_compat\")\n (sysctl-name \"hw.pagesize\")\n (sysctl-name \"hw.physicalcpu\")\n (sysctl-name \"hw.physicalcpu_max\")\n (sysctl-name \"hw.logicalcpu\")\n (sysctl-name \"hw.cpufrequency\")\n (sysctl-name \"hw.tbfrequency_compat\")\n (sysctl-name \"hw.vectorunit\")\n (sysctl-name \"machdep.cpu.brand_string\")\n (sysctl-name \"kern.argmax\")\n (sysctl-name \"kern.hostname\")\n (sysctl-name \"kern.maxfilesperproc\")\n (sysctl-name \"kern.maxproc\")\n (sysctl-name \"kern.osproductversion\")\n (sysctl-name \"kern.osrelease\")\n (sysctl-name \"kern.ostype\")\n (sysctl-name \"kern.osvariant_status\")\n (sysctl-name \"kern.osversion\")\n (sysctl-name \"kern.secure_kernel\")\n (sysctl-name \"kern.sysv.semmns\")\n (sysctl-name \"kern.usrstack64\")\n (sysctl-name \"kern.version\")\n (sysctl-name \"sysctl.proc_cputype\")\n (sysctl-name \"vm.loadavg\")\n (sysctl-name-prefix \"hw.perflevel\")\n (sysctl-name-prefix \"kern.proc.pgrp.\")\n (sysctl-name-prefix \"kern.proc.pid.\")\n (sysctl-name-prefix \"net.routetable.\"))\n(allow sysctl-write (sysctl-name \"kern.grade_cputype\"))\n\n(allow iokit-open (iokit-registry-entry-class \"RootDomainUserClient\"))\n(allow ipc-posix-sem)\n(allow ipc-posix-shm-read* (ipc-posix-name \"apple.shm.notification_center\"))\n(allow system-mac-syscall (mac-policy-name \"vnguard\"))\n(allow system-mac-syscall\n (require-all (mac-policy-name \"Sandbox\") (mac-syscall-number 67)))\n(allow system-fsctl (fsctl-command FSIOC_CAS_BSDFLAGS))\n\n(allow mach-lookup\n (global-name \"com.apple.system.opendirectoryd.libinfo\")\n (global-name \"com.apple.system.opendirectoryd.membership\")\n (global-name \"com.apple.system.DirectoryService.libinfo_v1\")\n (global-name \"com.apple.system.logger\")\n (global-name \"com.apple.system.notification_center\")\n (global-name \"com.apple.bsd.dirhelper\")\n (global-name \"com.apple.logd\")\n (global-name \"com.apple.diagnosticd\")\n (global-name \"com.apple.secinitd\")\n (global-name \"com.apple.trustd\")\n (global-name \"com.apple.trustd.agent\")\n (global-name \"com.apple.SecurityServer\")\n (global-name \"com.apple.networkd\")\n (global-name \"com.apple.ocspd\")\n (global-name \"com.apple.SystemConfiguration.DNSConfiguration\")\n (global-name \"com.apple.SystemConfiguration.configd\")\n (global-name \"com.apple.PowerManagement.control\"))\n\n; Path lookups: any path's metadata, never its contents.\n(allow file-read-metadata)\n(allow file-read* (literal \"/\"))\n\n; Devices and terminals.\n(allow pseudo-tty)\n(allow file-read* file-write* file-ioctl\n (literal \"/dev/null\")\n (literal \"/dev/zero\")\n (literal \"/dev/tty\")\n (literal \"/dev/ptmx\")\n (literal \"/dev/dtracehelper\")\n (regex #\"^/dev/ttys[0-9]+$\"))\n(allow file-read* (literal \"/dev/random\") (literal \"/dev/urandom\"))\n(allow file-read-data file-write-data (subpath \"/dev/fd\"))\n\n; Open egress (and host localhost, which the docs say).\n(allow network*)\n(allow system-socket\n (require-all (socket-domain AF_SYSTEM) (socket-protocol 2)))`;\n\nconst isWithin = (path: string, root: string): boolean =>\n root === \"/\" || path === root || path.startsWith(`${root}/`);\n\n/** Hands out `-D` parameter names, and records their values. */\nclass Params {\n readonly entries: [string, string][] = [];\n\n /** A `(param \"…\")` reference for `value`, under a fresh `prefix_n` key. */\n ref(prefix: string, value: string): string {\n const key = `${prefix}_${String(this.entries.length)}`;\n this.entries.push([key, value]);\n return `(param \"${key}\")`;\n }\n}\n\n/**\n * The dirs that must not be renamed or removed: each writable root, and each\n * ancestor of a protected path up to the writable root that holds it.\n */\nconst anchoredDirs = (input: SeatbeltPolicyInput): string[] => {\n const dirs = new Set(input.writableRoots);\n for (const path of input.protectedPaths) {\n const roots = input.writableRoots.filter((root) => isWithin(path, root));\n let dir = posix.dirname(path);\n while (roots.some((root) => isWithin(dir, root))) {\n dirs.add(dir);\n const parent = posix.dirname(dir);\n if (parent === dir) {\n break;\n }\n dir = parent;\n }\n }\n return [...dirs];\n};\n\n/** One `(allow …)` over `paths` as subpaths, or nothing for no paths. */\nconst allowSubpaths = (\n operations: string,\n refs: readonly string[],\n): string[] =>\n refs.length === 0\n ? []\n : [\n `(allow ${operations}\\n${refs.map((r) => ` (subpath ${r})`).join(\"\\n\")})`,\n ];\n\n/** Builds the profile and parameters for one `seatbelt()` sandbox. */\nexport const buildSeatbeltPolicy = (\n input: SeatbeltPolicyInput,\n): SeatbeltPolicy => {\n const params = new Params();\n const readable = [...new Set(input.readableRoots)].map((p) =>\n params.ref(\"READ\", p),\n );\n const writable = [...new Set(input.writableRoots)].map((p) =>\n params.ref(\"WRITE\", p),\n );\n const engineSockets = CONTAINER_ENGINE_SOCKETS.map((socket) =>\n params.ref(\"ENGINE\", socket),\n );\n const engineDirs = CONTAINER_ENGINE_HOME_DIRS.map((name) =>\n params.ref(\"ENGINE\", posix.join(input.hostHome, name)),\n );\n const protectedRefs = [...new Set(input.protectedPaths)].map((p) =>\n params.ref(\"PROTECTED\", p),\n );\n const anchors = anchoredDirs(input).map((p) => params.ref(\"ANCHOR\", p));\n\n const engineFilters = [\n ...engineSockets.map((r) => ` (literal ${r})`),\n ...engineDirs.map((r) => ` (subpath ${r})`),\n ].join(\"\\n\");\n\n const profile = [\n BASE,\n \"; Read-only: the system toolchain and the paths given to read.\",\n ...allowSubpaths(\"file-read* file-map-executable\", readable),\n \"; Read/write: the worktree, the writable git dirs, the private home and temp dir.\",\n ...allowSubpaths(\"file-read* file-write* file-map-executable\", writable),\n \"; No way into a container engine, which would be a way out.\",\n `(deny file-read* file-write* network-outbound process-exec\\n${engineFilters})`,\n '(deny mach-lookup (xpc-service-name-prefix \"\"))',\n \"; Last, so nothing above reopens them: the read-only git control files,\",\n \"; and the dirs that hold them, which can't be moved aside.\",\n ...protectedRefs.map((r) => `(deny file-write* (subpath ${r}))`),\n ...anchors.map(\n (r) =>\n `(deny file-write-unlink (require-all (vnode-type DIRECTORY) (literal ${r})))`,\n ),\n \"; Writes through read-only descriptors (F_MAKECOMPRESSED, F_TRANSFEREXTENTS).\",\n \"(deny system-fcntl (fcntl-command 80 110))\",\n \"\",\n ].join(\"\\n\");\n\n return { profile, params: params.entries };\n};\n","/**\n * The pieces of the `seatbelt()` provider (src/sandboxes/seatbelt.ts) that\n * don't run processes: a sandbox's private dirs, the Seatbelt policy and\n * child env for a sandbox, and the in-sandbox to host path mapping. Used only\n * by `seatbelt()`.\n */\n\nimport { homedir } from \"node:os\";\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 { resolveIdentityMounts } from \"./identityMounts.js\";\nimport type { IdentityMount, MountConfig } from \"./identityMounts.js\";\nimport { SYSTEM_READ_ROOTS, buildSeatbeltPolicy } from \"./seatbeltProfile.js\";\nimport type { SeatbeltPolicy } from \"./seatbeltProfile.js\";\nimport { SeatbeltError } from \"./errors.js\";\n\n/** The construction check, from its own module (it runs a process, synchronously). */\nexport { SANDBOX_EXEC, assertSeatbeltUsable } from \"./seatbeltPreflight.js\";\nexport type { IdentityMount, MountConfig } from \"./identityMounts.js\";\n/** Output collection and file copies, shared by the native sandbox providers. */\nexport { collectOutput, copyCreatingParents } from \"./nativeSandboxIo.js\";\n\n/**\n * The private home's logical path. Seatbelt can't remap paths, so `HOME` in\n * the sandbox is the private dir's real path; copies to and from paths under\n * this one are translated to it.\n */\nexport const SANDBOX_HOME = \"/home/agent\";\n\nconst FALLBACK_PATH = \"/usr/bin:/bin:/usr/sbin:/sbin\";\n\n/** Where `xcode-select` points: the developer dir `/usr/bin/git` and friends run from. */\nconst XCODE_SELECT_LINK = \"/var/db/xcode_select_link\";\n\nconst isWithin = (path: string, root: string): boolean =>\n path === root || path.startsWith(`${root}/`);\n\n/**\n * Checks `seatbelt()`'s `mounts` option: each mount, after resolution, must\n * sit at its own host path. Throws at construction otherwise.\n */\nexport const seatbeltMounts = (\n mounts: readonly MountConfig[],\n): IdentityMount[] => resolveIdentityMounts(\"seatbelt\", mounts, SANDBOX_HOME);\n\n/** The real host dirs behind a sandbox's private home and temp dir. */\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, at their real paths. */\nexport const makePrivateDirs: Effect.Effect<\n PrivateDirs,\n SeatbeltError,\n FileSystem.FileSystem\n> = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n // Seatbelt matches real paths (/private/var/…, not /var/…).\n const root = yield* fs.realPath(\n yield* fs.makeTempDirectory({ prefix: \"sandcastle-seatbelt-\" }),\n );\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 SeatbeltError({\n message: `Couldn't create the seatbelt() 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/** What every exec of one sandbox shares: its policy and its env. */\nexport interface SandboxSetup {\n readonly policy: SeatbeltPolicy;\n readonly env: Record<string, string>;\n}\n\n/** A mount at its real host path, or none when the path doesn't exist. */\nconst realMount = (\n fs: FileSystem.FileSystem,\n mount: { readonly hostPath: string; readonly readonly?: boolean },\n): Effect.Effect<Option.Option<IdentityMount>> =>\n Effect.option(fs.realPath(mount.hostPath)).pipe(\n Effect.map(\n Option.map((hostPath) => ({\n hostPath,\n readonly: mount.readonly === true,\n })),\n ),\n );\n\n/** The policy and env shared by every exec of one sandbox. */\nexport const sandboxSetup = (\n options: BindMountCreateOptions,\n dirs: PrivateDirs,\n userMounts: readonly IdentityMount[],\n): Effect.Effect<SandboxSetup, never, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const toolchain = yield* hostPathToolchainFromEnv({\n coveredRoots: SYSTEM_READ_ROOTS,\n deniedRoots: [],\n });\n const developerDir = yield* Effect.option(fs.realPath(XCODE_SELECT_LINK));\n const mounts = (yield* Effect.all(\n [...options.mounts, ...userMounts].map((m) => realMount(fs, m)),\n )).flatMap((m) => (Option.isSome(m) ? [m.value] : []));\n const policy = buildSeatbeltPolicy({\n readableRoots: [\n ...SYSTEM_READ_ROOTS,\n ...Option.toArray(developerDir),\n ...toolchain.readableDirs,\n ...mounts.filter((m) => m.readonly).map((m) => m.hostPath),\n ],\n writableRoots: [\n ...mounts.filter((m) => !m.readonly).map((m) => m.hostPath),\n dirs.home,\n dirs.tmp,\n ],\n protectedPaths: mounts.filter((m) => m.readonly).map((m) => m.hostPath),\n hostHome: homedir(),\n });\n const env = {\n ...options.env,\n PATH:\n toolchain.pathEntries.length > 0\n ? toolchain.pathEntries.join(\":\")\n : FALLBACK_PATH,\n HOME: dirs.home,\n TMPDIR: dirs.tmp,\n };\n return { policy, env };\n });\n\n/** The `sandbox-exec` arguments that run `sh -c command` under `policy`. */\nexport const sandboxExecArgs = (\n policy: SeatbeltPolicy,\n command: string,\n): string[] => [\n \"-p\",\n policy.profile,\n ...policy.params.map(([key, value]) => `-D${key}=${value}`),\n \"--\",\n \"/bin/sh\",\n \"-c\",\n command,\n];\n\n/**\n * Maps an in-sandbox path to the host file behind it. Paths are host paths,\n * except the logical private home, `/home/agent`, which is the private dir.\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 return p;\n};\n","/**\n * Seatbelt sandbox provider — a native sandbox provider for macOS.\n *\n * Usage:\n * import { seatbelt } from \"@ai-hero/sandcastle/sandboxes/seatbelt\";\n * await run({ agent: claudeCode(\"claude-opus-4-8\"), sandbox: seatbelt() });\n *\n * Each `exec` runs under the system `sandbox-exec` with a deny-by-default\n * profile: the system toolchain read-only, the worktree and git dirs\n * read/write at their host paths, a private home and temp dir, the host\n * network, 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 SANDBOX_EXEC,\n SANDBOX_HOME,\n assertSeatbeltUsable,\n collectOutput,\n copyCreatingParents,\n makePrivateDirs,\n removePrivateDirs,\n sandboxExecArgs,\n sandboxSetup,\n seatbeltMounts,\n toHostPath,\n} from \"../seatbeltSandbox.js\";\nimport type {\n IdentityMount,\n MountConfig,\n PrivateDirs,\n SandboxSetup,\n} from \"../seatbeltSandbox.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 { registerShutdown } from \"../shutdownRegistry.js\";\n\n/** Options for {@link seatbelt}. */\nexport interface SeatbeltOptions {\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`; `seatbelt()` throws\n * otherwise. `readonly` defaults to `false`.\n */\n readonly mounts?: readonly MountConfig[];\n}\n\ntype ExecOptions = Parameters<BindMountSandboxHandle[\"exec\"]>[1];\n\n/** SIGKILLs every process in `proc`'s process group. Synchronous, for shutdown. */\nconst killGroup = (proc: ChildProcess): void => {\n if (proc.pid === undefined) {\n return;\n }\n try {\n process.kill(-proc.pid, \"SIGKILL\");\n } catch {\n // The group is already gone.\n }\n};\n\n/**\n * A host shell, outside the sandbox, holding the read end of a pipe from\n * this Node process. If the pipe ends without `exit` (this process died,\n * however it died: nothing in it runs on SIGKILL), it SIGKILLs process\n * group `$1`.\n */\nconst WATCHDOG = 'read -r reply || kill -9 -- \"-$1\" 2>/dev/null';\n\n/**\n * Starts the watchdog for one exec's process group. Detached, so it leads\n * its own session: whatever kills this process's group or terminal can't\n * take it too, and the sandbox can't signal it. Returns how to stand it down\n * once the exec has ended and its group is killed.\n */\nconst startWatchdog = (pgid: number): (() => void) => {\n const watchdog = spawn(\"/bin/sh\", [\"-c\", WATCHDOG, \"sh\", String(pgid)], {\n detached: true,\n stdio: [\"pipe\", \"ignore\", \"ignore\"],\n });\n watchdog.on(\"error\", () => undefined);\n watchdog.stdin.on(\"error\", () => undefined);\n return () => {\n watchdog.stdin.end(\"exit\\n\");\n };\n};\n\n/**\n * Runs `sh -c command` under `sandbox-exec` and resolves when it exits. The\n * child leads its own process group: Seatbelt has no PID namespace, so the\n * group is how everything it started gets killed: when it exits, on close,\n * and, through a watchdog, when this Node process is hard-killed.\n */\nconst runInSeatbelt = async (\n command: string,\n opts: ExecOptions & { readonly cwd: string },\n sandbox: {\n setup: SandboxSetup;\n live: Set<ChildProcess>;\n maxTailChars: number;\n },\n): Promise<ExecResult> => {\n const { setup, live, maxTailChars } = sandbox;\n const proc = spawn(SANDBOX_EXEC, sandboxExecArgs(setup.policy, command), {\n cwd: opts.cwd,\n env: setup.env,\n detached: true,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n // Started in the same tick as the exec, so there's no moment when a hard\n // kill of this process would leave the group unwatched.\n const standDown =\n proc.pid === undefined ? (): void => undefined : startWatchdog(proc.pid);\n live.add(proc);\n // Like a fresh bwrap per exec: nothing it started outlives it.\n proc.on(\"exit\", () => {\n killGroup(proc);\n standDown();\n });\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(proc);\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 policy and env every exec shares. */\nconst prepare = async (\n options: BindMountCreateOptions,\n userMounts: readonly IdentityMount[],\n): Promise<{ dirs: PrivateDirs; setup: SandboxSetup }> =>\n Effect.gen(function* () {\n const dirs = yield* makePrivateDirs;\n const setup = yield* sandboxSetup(options, dirs, userMounts);\n return { dirs, setup };\n }).pipe(runOnHost);\n\n/**\n * Seatbelt can't remap paths: commands inside see the private dirs at their\n * real host paths, so the handle reports those for core to build paths from.\n */\nconst reportedDirs = (\n dirs: PrivateDirs,\n): Pick<BindMountSandboxHandle, \"sandboxHomedir\" | \"sandboxTmpdir\"> => ({\n sandboxHomedir: dirs.home,\n sandboxTmpdir: dirs.tmp,\n});\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, setup } = await prepare(options, userMounts);\n const live = new Set<ChildProcess>();\n const killAll = (): void => {\n for (const proc of live) {\n killGroup(proc);\n }\n };\n const unregisterShutdown = registerShutdown(killAll);\n let closed = false;\n const hostPathOf = (p: string): string => toHostPath(p, dirs, options.mounts);\n\n return {\n worktreePath: options.worktreePath,\n ...reportedDirs(dirs),\n exec: async (command, opts) => {\n if (opts?.sudo === true) {\n throw new Error(\n \"seatbelt() 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(\"seatbelt() sandbox is closed\");\n }\n const cwd = opts?.cwd ?? options.worktreePath;\n return runInSeatbelt(\n command,\n { ...opts, cwd },\n { setup, live, maxTailChars },\n );\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 exits = [...live].map(async (proc) => once(proc, \"close\"));\n killAll();\n await Promise.allSettled(exits);\n unregisterShutdown();\n await removePrivateDirs(dirs).pipe(runOnHost);\n },\n };\n};\n\n/**\n * Create a Seatbelt sandbox provider (macOS 14 or later).\n *\n * Each `exec` runs under the system `/usr/bin/sandbox-exec` with a\n * deny-by-default profile. The agent runs the host's own toolchain,\n * read-only, and can write only the worktree, the git dirs Sandcastle\n * mounts, a private temp dir (`TMPDIR`) and a private home (`HOME`). The git\n * control files stay read-only, and the dirs holding them can't be moved\n * aside. It can't signal host processes, but Seatbelt can't fully hide them.\n * The private home is exposed to Sandcastle as `/home/agent`: copies to and\n * from paths under it land in the private dir. Both private dirs are removed\n * on close, and every process an `exec` started is killed when it exits, on\n * close, on shutdown and when this Node process is hard-killed (a detached\n * host watchdog per `exec` does that). 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 `mounts`. The network is\n * open, including the host's localhost. It has no root: `exec` with\n * `sudo: true` rejects.\n *\n * Checks once per process that Seatbelt is usable, and throws\n * `NativeSandboxUnavailableError` if it isn't: on a non-macOS OS, on macOS\n * older than 14, or when `sandbox-exec` is missing or fails (for instance\n * inside another Seatbelt sandbox). It never falls back to running\n * unsandboxed.\n */\nexport const seatbelt = (\n options?: SeatbeltOptions,\n): BindMountSandboxProvider => {\n // Reject a sandboxPath/hostPath mismatch before the preflight, so the\n // config error surfaces on every OS.\n const userMounts = seatbeltMounts(options?.mounts ?? []);\n assertSeatbeltUsable();\n const maxTailChars = options?.maxOutputTailChars ?? MAX_TAIL_CHARS;\n return markNativeSandboxProvider(\n createBindMountSandboxProvider({\n name: \"seatbelt\",\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/seatbeltProfile.ts","../../src/seatbeltSandbox.ts","../../src/sandboxes/seatbelt.ts"],"names":["isWithin","posix"],"mappings":";;;;;;;;;;;;;;;;;AAiDO,IAAM,iBAAA,GAAuC;AAAA,EAClD,MAAA;AAAA,EACA,OAAA;AAAA,EACA,MAAA;AAAA,EACA,SAAA;AAAA,EACA,UAAA;AAAA,EACA,MAAA;AAAA,EACA,cAAA;AAAA,EACA,iBAAA;AAAA;AAAA,EAEA;AACF,CAAA;AAGA,IAAM,0BAAA,GAA6B;AAAA,EACjC,SAAA;AAAA,EACA,SAAA;AAAA,EACA,WAAA;AAAA,EACA,OAAA;AAAA,EACA;AACF,CAAA;AAEA,IAAM,wBAAA,GAA2B;AAAA,EAC/B,8BAAA;AAAA,EACA;AACF,CAAA;AAGA,IAAM,OAAO,MAAA,CAAO,GAAA,CAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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UAAA,CAAW,WAAW,CAAA,EAAG,QAAQ,CAAA,CAAE,IAAA,CAAK,SAAS,CAAA;AAAA,IACvE,OAAO,YAAY;AACjB,MAAA,MAAA,GAAS,IAAA;AACT,MAAA,MAAM,KAAA,GAAQ,CAAC,GAAG,IAAI,CAAA,CAAE,GAAA,CAAI,OAAO,IAAA,KAAS,IAAA,CAAK,IAAA,EAAM,OAAO,CAAC,CAAA;AAC/D,MAAA,OAAA,EAAQ;AACR,MAAA,MAAM,OAAA,CAAQ,WAAW,KAAK,CAAA;AAC9B,MAAA,kBAAA,EAAmB;AACnB,MAAA,MAAM,iBAAA,CAAkB,IAAI,CAAA,CAAE,IAAA,CAAK,SAAS,CAAA;AAAA,IAC9C;AAAA,GACF;AACF,CAAA;AA2BO,IAAM,QAAA,GAAW,CACtB,OAAA,KAC6B;AAG7B,EAAA,MAAM,UAAA,GAAa,cAAA,CAAe,OAAA,EAAS,MAAA,IAAU,EAAE,CAAA;AACvD,EAAA,oBAAA,EAAqB;AACrB,EAAA,MAAM,YAAA,GAAe,SAAS,kBAAA,IAAsB,cAAA;AACpD,EAAA,OAAO,yBAAA;AAAA,IACL,8BAAA,CAA+B;AAAA,MAC7B,IAAA,EAAM,UAAA;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":"seatbelt.js","sourcesContent":["/**\n * Builds the Seatbelt (SBPL) profile a `seatbelt()` sandbox runs under, and\n * the `-D` parameters that carry its paths. Pure and provider-agnostic: it\n * takes paths and returns text. No path is ever written into the profile\n * text: every one is a `(param \"…\")` passed to `sandbox-exec` with `-D`, so\n * there is nothing to escape.\n *\n * Hand-rolled, with no dependency on the projects its rule shapes come from:\n *\n * - OpenAI Codex (Apache-2.0, https://github.com/openai/codex,\n * codex-rs/sandboxing/src/seatbelt_base_policy.sbpl,\n * seatbelt_read_only_platform_defaults.sbpl, seatbelt_network_policy.sbpl\n * and seatbelt.rs): the deny-default base, the sysctl list (no\n * `kern.proc.all`), the platform defaults, the `-D` parameter pattern, the\n * `file-write-unlink` denies on protected ancestors, and the fcntl and XPC\n * denies.\n * - Google Gemini CLI (Apache-2.0, https://github.com/google-gemini/gemini-cli,\n * packages/cli/src/utils/sandbox-macos-*.sb): the Docker, Colima and\n * OrbStack socket denies.\n * - Microsoft MXC (MIT, https://github.com/microsoft/mxc,\n * docs/backends/seatbelt/seatbelt-backend.md): the read-only system\n * baseline and the developer dir.\n */\n\nimport { posix } from \"node:path\";\n\n/** What a `seatbelt()` sandbox may read and write. Every path is a real host path. */\nexport interface SeatbeltPolicyInput {\n /** Dirs the sandbox may read (and map executable code from), but not write. */\n readonly readableRoots: readonly string[];\n /** Dirs the sandbox may read and write: the worktree, writable git dirs, private dirs. */\n readonly writableRoots: readonly string[];\n /**\n * Files and dirs that stay read-only even inside a writable root (the\n * #1261 git control files). Their ancestors inside a writable root can't\n * be renamed or removed either, so they can't be moved aside.\n */\n readonly protectedPaths: readonly string[];\n /** The host home dir, for the container-engine socket denies. */\n readonly hostHome: string;\n}\n\n/** A Seatbelt profile and the `-D` parameters its `(param …)`s name. */\nexport interface SeatbeltPolicy {\n readonly profile: string;\n readonly params: readonly (readonly [key: string, value: string])[];\n}\n\n/** The system dirs every sandbox may read: MXC's baseline, Homebrew and `/opt`. */\nexport const SYSTEM_READ_ROOTS: readonly string[] = [\n \"/bin\",\n \"/sbin\",\n \"/usr\",\n \"/System\",\n \"/Library\",\n \"/opt\",\n \"/private/etc\",\n \"/private/var/db\",\n // `/bin/sh` picks the shell it runs from here.\n \"/private/var/select\",\n];\n\n/** Container-engine sockets and state under the host home, never reachable. */\nconst CONTAINER_ENGINE_HOME_DIRS = [\n \".docker\",\n \".colima\",\n \".orbstack\",\n \".lima\",\n \".rd\",\n];\n\nconst CONTAINER_ENGINE_SOCKETS = [\n \"/private/var/run/docker.sock\",\n \"/private/var/run/com.docker.vmnetd.sock\",\n];\n\n/** Deny-default, processes, sysctls and system services (after Codex's base policy). */\nconst BASE = String.raw`(version 1)\n(deny default)\n\n(allow process-exec)\n(allow process-fork)\n(allow signal (target same-sandbox))\n(allow process-info* (target same-sandbox))\n\n(allow sysctl-read\n (sysctl-name \"hw.activecpu\")\n (sysctl-name \"hw.busfrequency_compat\")\n (sysctl-name \"hw.byteorder\")\n (sysctl-name \"hw.cacheconfig\")\n (sysctl-name \"hw.cachelinesize_compat\")\n (sysctl-name \"hw.cpufamily\")\n (sysctl-name \"hw.cpufrequency_compat\")\n (sysctl-name \"hw.cputype\")\n (sysctl-name \"hw.l1dcachesize_compat\")\n (sysctl-name \"hw.l1icachesize_compat\")\n (sysctl-name \"hw.l2cachesize_compat\")\n (sysctl-name \"hw.l3cachesize_compat\")\n (sysctl-name \"hw.logicalcpu_max\")\n (sysctl-name \"hw.machine\")\n (sysctl-name \"hw.model\")\n (sysctl-name \"hw.memsize\")\n (sysctl-name \"hw.ncpu\")\n (sysctl-name \"hw.nperflevels\")\n (sysctl-name-prefix \"hw.optional.arm.\")\n (sysctl-name-prefix \"hw.optional.armv8_\")\n (sysctl-name \"hw.packages\")\n (sysctl-name \"hw.pagesize_compat\")\n (sysctl-name \"hw.pagesize\")\n (sysctl-name \"hw.physicalcpu\")\n (sysctl-name \"hw.physicalcpu_max\")\n (sysctl-name \"hw.logicalcpu\")\n (sysctl-name \"hw.cpufrequency\")\n (sysctl-name \"hw.tbfrequency_compat\")\n (sysctl-name \"hw.vectorunit\")\n (sysctl-name \"machdep.cpu.brand_string\")\n (sysctl-name \"kern.argmax\")\n (sysctl-name \"kern.hostname\")\n (sysctl-name \"kern.maxfilesperproc\")\n (sysctl-name \"kern.maxproc\")\n (sysctl-name \"kern.osproductversion\")\n (sysctl-name \"kern.osrelease\")\n (sysctl-name \"kern.ostype\")\n (sysctl-name \"kern.osvariant_status\")\n (sysctl-name \"kern.osversion\")\n (sysctl-name \"kern.secure_kernel\")\n (sysctl-name \"kern.sysv.semmns\")\n (sysctl-name \"kern.usrstack64\")\n (sysctl-name \"kern.version\")\n (sysctl-name \"sysctl.proc_cputype\")\n (sysctl-name \"vm.loadavg\")\n (sysctl-name-prefix \"hw.perflevel\")\n (sysctl-name-prefix \"kern.proc.pgrp.\")\n (sysctl-name-prefix \"kern.proc.pid.\")\n (sysctl-name-prefix \"net.routetable.\"))\n(allow sysctl-write (sysctl-name \"kern.grade_cputype\"))\n\n(allow iokit-open (iokit-registry-entry-class \"RootDomainUserClient\"))\n(allow ipc-posix-sem)\n(allow ipc-posix-shm-read* (ipc-posix-name \"apple.shm.notification_center\"))\n(allow system-mac-syscall (mac-policy-name \"vnguard\"))\n(allow system-mac-syscall\n (require-all (mac-policy-name \"Sandbox\") (mac-syscall-number 67)))\n(allow system-fsctl (fsctl-command FSIOC_CAS_BSDFLAGS))\n\n(allow mach-lookup\n (global-name \"com.apple.system.opendirectoryd.libinfo\")\n (global-name \"com.apple.system.opendirectoryd.membership\")\n (global-name \"com.apple.system.DirectoryService.libinfo_v1\")\n (global-name \"com.apple.system.logger\")\n (global-name \"com.apple.system.notification_center\")\n (global-name \"com.apple.bsd.dirhelper\")\n (global-name \"com.apple.logd\")\n (global-name \"com.apple.diagnosticd\")\n (global-name \"com.apple.secinitd\")\n (global-name \"com.apple.trustd\")\n (global-name \"com.apple.trustd.agent\")\n (global-name \"com.apple.SecurityServer\")\n (global-name \"com.apple.networkd\")\n (global-name \"com.apple.ocspd\")\n (global-name \"com.apple.SystemConfiguration.DNSConfiguration\")\n (global-name \"com.apple.SystemConfiguration.configd\")\n (global-name \"com.apple.PowerManagement.control\"))\n\n; Path lookups: any path's metadata, never its contents.\n(allow file-read-metadata)\n(allow file-read* (literal \"/\"))\n\n; Devices and terminals.\n(allow pseudo-tty)\n(allow file-read* file-write* file-ioctl\n (literal \"/dev/null\")\n (literal \"/dev/zero\")\n (literal \"/dev/tty\")\n (literal \"/dev/ptmx\")\n (literal \"/dev/dtracehelper\")\n (regex #\"^/dev/ttys[0-9]+$\"))\n(allow file-read* (literal \"/dev/random\") (literal \"/dev/urandom\"))\n(allow file-read-data file-write-data (subpath \"/dev/fd\"))\n\n; Open egress (and host localhost, which the docs say).\n(allow network*)\n(allow system-socket\n (require-all (socket-domain AF_SYSTEM) (socket-protocol 2)))`;\n\nconst isWithin = (path: string, root: string): boolean =>\n root === \"/\" || path === root || path.startsWith(`${root}/`);\n\n/** Hands out `-D` parameter names, and records their values. */\nclass Params {\n readonly entries: [string, string][] = [];\n\n /** A `(param \"…\")` reference for `value`, under a fresh `prefix_n` key. */\n ref(prefix: string, value: string): string {\n const key = `${prefix}_${String(this.entries.length)}`;\n this.entries.push([key, value]);\n return `(param \"${key}\")`;\n }\n}\n\n/**\n * The dirs that must not be renamed or removed: each writable root, and each\n * ancestor of a protected path up to the writable root that holds it.\n */\nconst anchoredDirs = (input: SeatbeltPolicyInput): string[] => {\n const dirs = new Set(input.writableRoots);\n for (const path of input.protectedPaths) {\n const roots = input.writableRoots.filter((root) => isWithin(path, root));\n let dir = posix.dirname(path);\n while (roots.some((root) => isWithin(dir, root))) {\n dirs.add(dir);\n const parent = posix.dirname(dir);\n if (parent === dir) {\n break;\n }\n dir = parent;\n }\n }\n return [...dirs];\n};\n\n/** One `(allow …)` over `paths` as subpaths, or nothing for no paths. */\nconst allowSubpaths = (\n operations: string,\n refs: readonly string[],\n): string[] =>\n refs.length === 0\n ? []\n : [\n `(allow ${operations}\\n${refs.map((r) => ` (subpath ${r})`).join(\"\\n\")})`,\n ];\n\n/** Builds the profile and parameters for one `seatbelt()` sandbox. */\nexport const buildSeatbeltPolicy = (\n input: SeatbeltPolicyInput,\n): SeatbeltPolicy => {\n const params = new Params();\n const readable = [...new Set(input.readableRoots)].map((p) =>\n params.ref(\"READ\", p),\n );\n const writable = [...new Set(input.writableRoots)].map((p) =>\n params.ref(\"WRITE\", p),\n );\n const engineSockets = CONTAINER_ENGINE_SOCKETS.map((socket) =>\n params.ref(\"ENGINE\", socket),\n );\n const engineDirs = CONTAINER_ENGINE_HOME_DIRS.map((name) =>\n params.ref(\"ENGINE\", posix.join(input.hostHome, name)),\n );\n const protectedRefs = [...new Set(input.protectedPaths)].map((p) =>\n params.ref(\"PROTECTED\", p),\n );\n const anchors = anchoredDirs(input).map((p) => params.ref(\"ANCHOR\", p));\n\n const engineFilters = [\n ...engineSockets.map((r) => ` (literal ${r})`),\n ...engineDirs.map((r) => ` (subpath ${r})`),\n ].join(\"\\n\");\n\n const profile = [\n BASE,\n \"; Read-only: the system toolchain and the paths given to read.\",\n ...allowSubpaths(\"file-read* file-map-executable\", readable),\n \"; Read/write: the worktree, the writable git dirs, the private home and temp dir.\",\n ...allowSubpaths(\"file-read* file-write* file-map-executable\", writable),\n \"; No way into a container engine, which would be a way out.\",\n `(deny file-read* file-write* network-outbound process-exec\\n${engineFilters})`,\n '(deny mach-lookup (xpc-service-name-prefix \"\"))',\n \"; Last, so nothing above reopens them: the read-only git control files,\",\n \"; and the dirs that hold them, which can't be moved aside.\",\n ...protectedRefs.map((r) => `(deny file-write* (subpath ${r}))`),\n ...anchors.map(\n (r) =>\n `(deny file-write-unlink (require-all (vnode-type DIRECTORY) (literal ${r})))`,\n ),\n \"; Writes through read-only descriptors (F_MAKECOMPRESSED, F_TRANSFEREXTENTS).\",\n \"(deny system-fcntl (fcntl-command 80 110))\",\n \"\",\n ].join(\"\\n\");\n\n return { profile, params: params.entries };\n};\n","/**\n * The pieces of the `seatbelt()` provider (src/sandboxes/seatbelt.ts) that\n * don't run processes: a sandbox's private dirs, the Seatbelt policy and\n * child env for a sandbox, and the in-sandbox to host path mapping. Used only\n * by `seatbelt()`.\n */\n\nimport { homedir } from \"node:os\";\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 { resolveIdentityMounts } from \"./identityMounts.js\";\nimport type { IdentityMount, MountConfig } from \"./identityMounts.js\";\nimport { SYSTEM_READ_ROOTS, buildSeatbeltPolicy } from \"./seatbeltProfile.js\";\nimport type { SeatbeltPolicy } from \"./seatbeltProfile.js\";\nimport { SeatbeltError } from \"./errors.js\";\n\n/** The construction check, from its own module (it runs a process, synchronously). */\nexport { SANDBOX_EXEC, assertSeatbeltUsable } from \"./seatbeltPreflight.js\";\nexport type { IdentityMount, MountConfig } from \"./identityMounts.js\";\n/** Output collection and file copies, shared by the native sandbox providers. */\nexport { collectOutput, copyCreatingParents } from \"./nativeSandboxIo.js\";\n\n/**\n * The private home's logical path. Seatbelt can't remap paths, so `HOME` in\n * the sandbox is the private dir's real path; copies to and from paths under\n * this one are translated to it.\n */\nexport const SANDBOX_HOME = \"/home/agent\";\n\nconst FALLBACK_PATH = \"/usr/bin:/bin:/usr/sbin:/sbin\";\n\n/** Where `xcode-select` points: the developer dir `/usr/bin/git` and friends run from. */\nconst XCODE_SELECT_LINK = \"/var/db/xcode_select_link\";\n\nconst isWithin = (path: string, root: string): boolean =>\n path === root || path.startsWith(`${root}/`);\n\n/**\n * Checks `seatbelt()`'s `mounts` option: each mount, after resolution, must\n * sit at its own host path. Throws at construction otherwise.\n */\nexport const seatbeltMounts = (\n mounts: readonly MountConfig[],\n): IdentityMount[] => resolveIdentityMounts(\"seatbelt\", mounts, SANDBOX_HOME);\n\n/** The real host dirs behind a sandbox's private home and temp dir. */\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, at their real paths. */\nexport const makePrivateDirs: Effect.Effect<\n PrivateDirs,\n SeatbeltError,\n FileSystem.FileSystem\n> = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n // Seatbelt matches real paths (/private/var/…, not /var/…).\n const root = yield* fs.realPath(\n yield* fs.makeTempDirectory({ prefix: \"sandcastle-seatbelt-\" }),\n );\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 SeatbeltError({\n message: `Couldn't create the seatbelt() 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/** What every exec of one sandbox shares: its policy and its env. */\nexport interface SandboxSetup {\n readonly policy: SeatbeltPolicy;\n readonly env: Record<string, string>;\n}\n\n/** A mount at its real host path, or none when the path doesn't exist. */\nconst realMount = (\n fs: FileSystem.FileSystem,\n mount: { readonly hostPath: string; readonly readonly?: boolean },\n): Effect.Effect<Option.Option<IdentityMount>> =>\n Effect.option(fs.realPath(mount.hostPath)).pipe(\n Effect.map(\n Option.map((hostPath) => ({\n hostPath,\n readonly: mount.readonly === true,\n })),\n ),\n );\n\n/** The policy and env shared by every exec of one sandbox. */\nexport const sandboxSetup = (\n options: BindMountCreateOptions,\n dirs: PrivateDirs,\n userMounts: readonly IdentityMount[],\n): Effect.Effect<SandboxSetup, never, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const toolchain = yield* hostPathToolchainFromEnv({\n coveredRoots: SYSTEM_READ_ROOTS,\n deniedRoots: [],\n });\n const developerDir = yield* Effect.option(fs.realPath(XCODE_SELECT_LINK));\n const mounts = (yield* Effect.all(\n [...options.mounts, ...userMounts].map((m) => realMount(fs, m)),\n )).flatMap((m) => (Option.isSome(m) ? [m.value] : []));\n const policy = buildSeatbeltPolicy({\n readableRoots: [\n ...SYSTEM_READ_ROOTS,\n ...Option.toArray(developerDir),\n ...toolchain.readableDirs,\n ...mounts.filter((m) => m.readonly).map((m) => m.hostPath),\n ],\n writableRoots: [\n ...mounts.filter((m) => !m.readonly).map((m) => m.hostPath),\n dirs.home,\n dirs.tmp,\n ],\n protectedPaths: mounts.filter((m) => m.readonly).map((m) => m.hostPath),\n hostHome: homedir(),\n });\n const env = {\n ...options.env,\n PATH:\n toolchain.pathEntries.length > 0\n ? toolchain.pathEntries.join(\":\")\n : FALLBACK_PATH,\n HOME: dirs.home,\n TMPDIR: dirs.tmp,\n };\n return { policy, env };\n });\n\n/** The `sandbox-exec` arguments that run `sh -c command` under `policy`. */\nexport const sandboxExecArgs = (\n policy: SeatbeltPolicy,\n command: string,\n): string[] => [\n \"-p\",\n policy.profile,\n ...policy.params.map(([key, value]) => `-D${key}=${value}`),\n \"--\",\n \"/bin/sh\",\n \"-c\",\n command,\n];\n\n/**\n * Maps an in-sandbox path to the host file behind it. Paths are host paths,\n * except the logical private home, `/home/agent`, which is the private dir.\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 return p;\n};\n","/**\n * Seatbelt sandbox provider — a native sandbox provider for macOS.\n *\n * Usage:\n * import { seatbelt } from \"@ai-hero/sandcastle/sandboxes/seatbelt\";\n * await run({ agent: claudeCode(\"claude-opus-4-8\"), sandbox: seatbelt() });\n *\n * Each `exec` runs under the system `sandbox-exec` with a deny-by-default\n * profile: the system toolchain read-only, the worktree and git dirs\n * read/write at their host paths, a private home and temp dir, the host\n * network, 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 SANDBOX_EXEC,\n SANDBOX_HOME,\n assertSeatbeltUsable,\n collectOutput,\n copyCreatingParents,\n makePrivateDirs,\n removePrivateDirs,\n sandboxExecArgs,\n sandboxSetup,\n seatbeltMounts,\n toHostPath,\n} from \"../seatbeltSandbox.js\";\nimport type {\n IdentityMount,\n MountConfig,\n PrivateDirs,\n SandboxSetup,\n} from \"../seatbeltSandbox.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 seatbelt}. */\nexport interface SeatbeltOptions {\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`; `seatbelt()` throws\n * otherwise. `readonly` defaults to `false`.\n */\n readonly mounts?: readonly MountConfig[];\n}\n\ntype ExecOptions = Parameters<BindMountSandboxHandle[\"exec\"]>[1];\n\n/** SIGKILLs every process in `proc`'s process group. Synchronous, for shutdown. */\nconst killGroup = (proc: ChildProcess): void => {\n if (proc.pid === undefined) {\n return;\n }\n try {\n process.kill(-proc.pid, \"SIGKILL\");\n } catch {\n // The group is already gone.\n }\n};\n\n/**\n * A host shell, outside the sandbox, holding the read end of a pipe from\n * this Node process. If the pipe ends without `exit` (this process died,\n * however it died: nothing in it runs on SIGKILL), it SIGKILLs process\n * group `$1`.\n */\nconst WATCHDOG = 'read -r reply || kill -9 -- \"-$1\" 2>/dev/null';\n\n/**\n * Starts the watchdog for one exec's process group. Detached, so it leads\n * its own session: whatever kills this process's group or terminal can't\n * take it too, and the sandbox can't signal it. Returns how to stand it down\n * once the exec has ended and its group is killed.\n */\nconst startWatchdog = (pgid: number): (() => void) => {\n const watchdog = spawn(\"/bin/sh\", [\"-c\", WATCHDOG, \"sh\", String(pgid)], {\n detached: true,\n stdio: [\"pipe\", \"ignore\", \"ignore\"],\n });\n watchdog.on(\"error\", () => undefined);\n watchdog.stdin.on(\"error\", () => undefined);\n return () => {\n watchdog.stdin.end(\"exit\\n\");\n };\n};\n\n/**\n * Runs `sh -c command` under `sandbox-exec` and resolves when it exits. The\n * child leads its own process group: Seatbelt has no PID namespace, so the\n * group is how everything it started gets killed: when it exits, on close,\n * and, through a watchdog, when this Node process is hard-killed.\n */\nconst runInSeatbelt = async (\n command: string,\n opts: ExecOptions & { readonly cwd: string },\n sandbox: {\n setup: SandboxSetup;\n live: Set<ChildProcess>;\n maxTailChars: number;\n },\n): Promise<ExecResult> => {\n const { setup, live, maxTailChars } = sandbox;\n const proc = spawn(SANDBOX_EXEC, sandboxExecArgs(setup.policy, command), {\n cwd: opts.cwd,\n env: setup.env,\n detached: true,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n // Started in the same tick as the exec, so there's no moment when a hard\n // kill of this process would leave the group unwatched.\n const standDown =\n proc.pid === undefined ? (): void => undefined : startWatchdog(proc.pid);\n live.add(proc);\n // Like a fresh bwrap per exec: nothing it started outlives it.\n proc.on(\"exit\", () => {\n killGroup(proc);\n standDown();\n });\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(proc);\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 policy and env every exec shares. */\nconst prepare = async (\n options: BindMountCreateOptions,\n userMounts: readonly IdentityMount[],\n): Promise<{ dirs: PrivateDirs; setup: SandboxSetup }> =>\n Effect.gen(function* () {\n const dirs = yield* makePrivateDirs;\n const setup = yield* sandboxSetup(options, dirs, userMounts);\n return { dirs, setup };\n }).pipe(runOnHost);\n\n/**\n * Seatbelt can't remap paths: commands inside see the private dirs at their\n * real host paths, so the handle reports those for core to build paths from.\n */\nconst reportedDirs = (\n dirs: PrivateDirs,\n): Pick<BindMountSandboxHandle, \"sandboxHomedir\" | \"sandboxTmpdir\"> => ({\n sandboxHomedir: dirs.home,\n sandboxTmpdir: dirs.tmp,\n});\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, setup } = await prepare(options, userMounts);\n const live = new Set<ChildProcess>();\n const killAll = (): void => {\n for (const proc of live) {\n killGroup(proc);\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 ...reportedDirs(dirs),\n exec: async (command, opts) => {\n if (opts?.sudo === true) {\n throw new Error(\n \"seatbelt() 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(\"seatbelt() sandbox is closed\");\n }\n const cwd = opts?.cwd ?? options.worktreePath;\n return runInSeatbelt(\n command,\n { ...opts, cwd },\n { setup, live, maxTailChars },\n );\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 exits = [...live].map(async (proc) => once(proc, \"close\"));\n killAll();\n await Promise.allSettled(exits);\n unregisterShutdown();\n await removePrivateDirs(dirs).pipe(runOnHost);\n },\n };\n};\n\n/**\n * Create a Seatbelt sandbox provider (macOS 14 or later).\n *\n * Each `exec` runs under the system `/usr/bin/sandbox-exec` with a\n * deny-by-default profile. The agent runs the host's own toolchain,\n * read-only, and can write only the worktree, the git dirs Sandcastle\n * mounts, a private temp dir (`TMPDIR`) and a private home (`HOME`). The git\n * control files stay read-only, and the dirs holding them can't be moved\n * aside. It can't signal host processes, but Seatbelt can't fully hide them.\n * The private home is exposed to Sandcastle as `/home/agent`: copies to and\n * from paths under it land in the private dir. Both private dirs are removed\n * on close and on shutdown (SIGINT, SIGTERM, exit), and every process an `exec` started is killed when it exits, on\n * close, on shutdown and when this Node process is hard-killed (a detached\n * host watchdog per `exec` does that). 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 `mounts`. The network is\n * open, including the host's localhost. It has no root: `exec` with\n * `sudo: true` rejects.\n *\n * Checks once per process that Seatbelt is usable, and throws\n * `NativeSandboxUnavailableError` if it isn't: on a non-macOS OS, on macOS\n * older than 14, or when `sandbox-exec` is missing or fails (for instance\n * inside another Seatbelt sandbox). It never falls back to running\n * unsandboxed.\n */\nexport const seatbelt = (\n options?: SeatbeltOptions,\n): BindMountSandboxProvider => {\n // Reject a sandboxPath/hostPath mismatch before the preflight, so the\n // config error surfaces on every OS.\n const userMounts = seatbeltMounts(options?.mounts ?? []);\n assertSeatbeltUsable();\n const maxTailChars = options?.maxOutputTailChars ?? MAX_TAIL_CHARS;\n return markNativeSandboxProvider(\n createBindMountSandboxProvider({\n name: \"seatbelt\",\n env: options?.env ?? {},\n sandboxHomedir: SANDBOX_HOME,\n create: async (createOptions) =>\n createHandle(createOptions, { maxTailChars, userMounts }),\n }),\n );\n};\n"]}
|