@ai-hero/sandcastle 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +15 -1368
  2. package/dist/LinuxCapability-B_PQfsY_.d.ts +32 -0
  3. package/dist/{SandboxProvider-EkSMuBp8.d.ts → SandboxProvider-Chsi-Zs6.d.ts} +31 -3
  4. package/dist/{chunk-NGBM7T3E.js → chunk-6NQPCXSG.js} +5 -2
  5. package/dist/chunk-6NQPCXSG.js.map +1 -0
  6. package/dist/chunk-7N7AMUYA.js +353 -0
  7. package/dist/chunk-7N7AMUYA.js.map +1 -0
  8. package/dist/chunk-ATA2V2TC.js +112 -0
  9. package/dist/chunk-ATA2V2TC.js.map +1 -0
  10. package/dist/chunk-BIF2X6QB.js +94 -0
  11. package/dist/chunk-BIF2X6QB.js.map +1 -0
  12. package/dist/{chunk-BIWNFKGV.js → chunk-BVZWLFFT.js} +2 -2
  13. package/dist/chunk-BVZWLFFT.js.map +1 -0
  14. package/dist/chunk-EXYXBRCX.js +60 -0
  15. package/dist/chunk-EXYXBRCX.js.map +1 -0
  16. package/dist/chunk-G2R53CVZ.js +3172 -0
  17. package/dist/chunk-G2R53CVZ.js.map +1 -0
  18. package/dist/{chunk-CP3TYXZA.js → chunk-GCLEXPXG.js} +95 -85
  19. package/dist/chunk-GCLEXPXG.js.map +1 -0
  20. package/dist/chunk-H2PEFS4W.js +1244 -0
  21. package/dist/chunk-H2PEFS4W.js.map +1 -0
  22. package/dist/chunk-HSXPRZKG.js +150 -0
  23. package/dist/chunk-HSXPRZKG.js.map +1 -0
  24. package/dist/chunk-IBK2XNSS.js +50 -0
  25. package/dist/chunk-IBK2XNSS.js.map +1 -0
  26. package/dist/chunk-RDW7FNN6.js +792 -0
  27. package/dist/chunk-RDW7FNN6.js.map +1 -0
  28. package/dist/{chunk-DJRHWPEH.js → chunk-S6UHPTRG.js} +284 -352
  29. package/dist/chunk-S6UHPTRG.js.map +1 -0
  30. package/dist/{chunk-VOG34SRF.js → chunk-STB2U7BB.js} +11823 -6977
  31. package/dist/chunk-STB2U7BB.js.map +1 -0
  32. package/dist/chunk-VRXR2T3S.js +24 -0
  33. package/dist/chunk-VRXR2T3S.js.map +1 -0
  34. package/dist/index.d.ts +241 -26
  35. package/dist/index.js +1082 -1679
  36. package/dist/index.js.map +1 -1
  37. package/dist/main.js +1248 -854
  38. package/dist/main.js.map +1 -1
  39. package/dist/sandboxes/bwrap.d.ts +58 -0
  40. package/dist/sandboxes/bwrap.js +296 -0
  41. package/dist/sandboxes/bwrap.js.map +1 -0
  42. package/dist/sandboxes/daytona.d.ts +1 -1
  43. package/dist/sandboxes/daytona.js +203 -98
  44. package/dist/sandboxes/daytona.js.map +1 -1
  45. package/dist/sandboxes/docker.d.ts +18 -4
  46. package/dist/sandboxes/docker.js +7 -4
  47. package/dist/sandboxes/e2b.d.ts +41 -0
  48. package/dist/sandboxes/e2b.js +202 -0
  49. package/dist/sandboxes/e2b.js.map +1 -0
  50. package/dist/sandboxes/modal.d.ts +78 -0
  51. package/dist/sandboxes/modal.js +171 -0
  52. package/dist/sandboxes/modal.js.map +1 -0
  53. package/dist/sandboxes/no-sandbox.d.ts +1 -1
  54. package/dist/sandboxes/no-sandbox.js +2 -2
  55. package/dist/sandboxes/podman.d.ts +18 -4
  56. package/dist/sandboxes/podman.js +72 -56
  57. package/dist/sandboxes/podman.js.map +1 -1
  58. package/dist/sandboxes/seatbelt.d.ts +65 -0
  59. package/dist/sandboxes/seatbelt.js +425 -0
  60. package/dist/sandboxes/seatbelt.js.map +1 -0
  61. package/dist/sandboxes/sprites.d.ts +54 -0
  62. package/dist/sandboxes/sprites.js +198 -0
  63. package/dist/sandboxes/sprites.js.map +1 -0
  64. package/dist/sandboxes/vercel.d.ts +12 -5
  65. package/dist/sandboxes/vercel.js +195 -126
  66. package/dist/sandboxes/vercel.js.map +1 -1
  67. package/dist/templates/parallel-planner/main.mts +13 -22
  68. package/dist/templates/parallel-planner-with-review/main.mts +13 -15
  69. package/package.json +63 -11
  70. package/dist/chunk-62WN33RK.js +0 -104
  71. package/dist/chunk-62WN33RK.js.map +0 -1
  72. package/dist/chunk-BIWNFKGV.js.map +0 -1
  73. package/dist/chunk-CP3TYXZA.js.map +0 -1
  74. package/dist/chunk-DJRHWPEH.js.map +0 -1
  75. package/dist/chunk-NGBM7T3E.js.map +0 -1
  76. package/dist/chunk-VOG34SRF.js.map +0 -1
  77. package/dist/mountUtils-CCA-bbpK.d.ts +0 -25
@@ -0,0 +1,425 @@
1
+ import { createRequire } from 'node:module';
2
+ import { resolveIdentityMounts, copyCreatingParents, collectOutput, hostPathToolchainFromEnv } from '../chunk-HSXPRZKG.js';
3
+ import { markNativeSandboxProvider } from '../chunk-VRXR2T3S.js';
4
+ import { assertSeatbeltUsable, SANDBOX_EXEC } from '../chunk-IBK2XNSS.js';
5
+ import { NodeFileSystem_exports } from '../chunk-S6UHPTRG.js';
6
+ import '../chunk-G2R53CVZ.js';
7
+ import { registerShutdown } from '../chunk-EXYXBRCX.js';
8
+ import { FileSystem_exports, SeatbeltError } from '../chunk-RDW7FNN6.js';
9
+ import { Effect_exports, Option_exports } from '../chunk-STB2U7BB.js';
10
+ import { createBindMountSandboxProvider } from '../chunk-BVZWLFFT.js';
11
+ import { MAX_TAIL_CHARS } from '../chunk-6NQPCXSG.js';
12
+ import { spawn } from 'child_process';
13
+ import { once } from 'events';
14
+ import { homedir } from 'os';
15
+ import { join, posix } from 'path';
16
+
17
+ createRequire(import.meta.url);
18
+ var SYSTEM_READ_ROOTS = [
19
+ "/bin",
20
+ "/sbin",
21
+ "/usr",
22
+ "/System",
23
+ "/Library",
24
+ "/opt",
25
+ "/private/etc",
26
+ "/private/var/db",
27
+ // `/bin/sh` picks the shell it runs from here.
28
+ "/private/var/select"
29
+ ];
30
+ var CONTAINER_ENGINE_HOME_DIRS = [
31
+ ".docker",
32
+ ".colima",
33
+ ".orbstack",
34
+ ".lima",
35
+ ".rd"
36
+ ];
37
+ var CONTAINER_ENGINE_SOCKETS = [
38
+ "/private/var/run/docker.sock",
39
+ "/private/var/run/com.docker.vmnetd.sock"
40
+ ];
41
+ var BASE = String.raw`(version 1)
42
+ (deny default)
43
+
44
+ (allow process-exec)
45
+ (allow process-fork)
46
+ (allow signal (target same-sandbox))
47
+ (allow process-info* (target same-sandbox))
48
+
49
+ (allow sysctl-read
50
+ (sysctl-name "hw.activecpu")
51
+ (sysctl-name "hw.busfrequency_compat")
52
+ (sysctl-name "hw.byteorder")
53
+ (sysctl-name "hw.cacheconfig")
54
+ (sysctl-name "hw.cachelinesize_compat")
55
+ (sysctl-name "hw.cpufamily")
56
+ (sysctl-name "hw.cpufrequency_compat")
57
+ (sysctl-name "hw.cputype")
58
+ (sysctl-name "hw.l1dcachesize_compat")
59
+ (sysctl-name "hw.l1icachesize_compat")
60
+ (sysctl-name "hw.l2cachesize_compat")
61
+ (sysctl-name "hw.l3cachesize_compat")
62
+ (sysctl-name "hw.logicalcpu_max")
63
+ (sysctl-name "hw.machine")
64
+ (sysctl-name "hw.model")
65
+ (sysctl-name "hw.memsize")
66
+ (sysctl-name "hw.ncpu")
67
+ (sysctl-name "hw.nperflevels")
68
+ (sysctl-name-prefix "hw.optional.arm.")
69
+ (sysctl-name-prefix "hw.optional.armv8_")
70
+ (sysctl-name "hw.packages")
71
+ (sysctl-name "hw.pagesize_compat")
72
+ (sysctl-name "hw.pagesize")
73
+ (sysctl-name "hw.physicalcpu")
74
+ (sysctl-name "hw.physicalcpu_max")
75
+ (sysctl-name "hw.logicalcpu")
76
+ (sysctl-name "hw.cpufrequency")
77
+ (sysctl-name "hw.tbfrequency_compat")
78
+ (sysctl-name "hw.vectorunit")
79
+ (sysctl-name "machdep.cpu.brand_string")
80
+ (sysctl-name "kern.argmax")
81
+ (sysctl-name "kern.hostname")
82
+ (sysctl-name "kern.maxfilesperproc")
83
+ (sysctl-name "kern.maxproc")
84
+ (sysctl-name "kern.osproductversion")
85
+ (sysctl-name "kern.osrelease")
86
+ (sysctl-name "kern.ostype")
87
+ (sysctl-name "kern.osvariant_status")
88
+ (sysctl-name "kern.osversion")
89
+ (sysctl-name "kern.secure_kernel")
90
+ (sysctl-name "kern.sysv.semmns")
91
+ (sysctl-name "kern.usrstack64")
92
+ (sysctl-name "kern.version")
93
+ (sysctl-name "sysctl.proc_cputype")
94
+ (sysctl-name "vm.loadavg")
95
+ (sysctl-name-prefix "hw.perflevel")
96
+ (sysctl-name-prefix "kern.proc.pgrp.")
97
+ (sysctl-name-prefix "kern.proc.pid.")
98
+ (sysctl-name-prefix "net.routetable."))
99
+ (allow sysctl-write (sysctl-name "kern.grade_cputype"))
100
+
101
+ (allow iokit-open (iokit-registry-entry-class "RootDomainUserClient"))
102
+ (allow ipc-posix-sem)
103
+ (allow ipc-posix-shm-read* (ipc-posix-name "apple.shm.notification_center"))
104
+ (allow system-mac-syscall (mac-policy-name "vnguard"))
105
+ (allow system-mac-syscall
106
+ (require-all (mac-policy-name "Sandbox") (mac-syscall-number 67)))
107
+ (allow system-fsctl (fsctl-command FSIOC_CAS_BSDFLAGS))
108
+
109
+ (allow mach-lookup
110
+ (global-name "com.apple.system.opendirectoryd.libinfo")
111
+ (global-name "com.apple.system.opendirectoryd.membership")
112
+ (global-name "com.apple.system.DirectoryService.libinfo_v1")
113
+ (global-name "com.apple.system.logger")
114
+ (global-name "com.apple.system.notification_center")
115
+ (global-name "com.apple.bsd.dirhelper")
116
+ (global-name "com.apple.logd")
117
+ (global-name "com.apple.diagnosticd")
118
+ (global-name "com.apple.secinitd")
119
+ (global-name "com.apple.trustd")
120
+ (global-name "com.apple.trustd.agent")
121
+ (global-name "com.apple.SecurityServer")
122
+ (global-name "com.apple.networkd")
123
+ (global-name "com.apple.ocspd")
124
+ (global-name "com.apple.SystemConfiguration.DNSConfiguration")
125
+ (global-name "com.apple.SystemConfiguration.configd")
126
+ (global-name "com.apple.PowerManagement.control"))
127
+
128
+ ; Path lookups: any path's metadata, never its contents.
129
+ (allow file-read-metadata)
130
+ (allow file-read* (literal "/"))
131
+
132
+ ; Devices and terminals.
133
+ (allow pseudo-tty)
134
+ (allow file-read* file-write* file-ioctl
135
+ (literal "/dev/null")
136
+ (literal "/dev/zero")
137
+ (literal "/dev/tty")
138
+ (literal "/dev/ptmx")
139
+ (literal "/dev/dtracehelper")
140
+ (regex #"^/dev/ttys[0-9]+$"))
141
+ (allow file-read* (literal "/dev/random") (literal "/dev/urandom"))
142
+ (allow file-read-data file-write-data (subpath "/dev/fd"))
143
+
144
+ ; Open egress (and host localhost, which the docs say).
145
+ (allow network*)
146
+ (allow system-socket
147
+ (require-all (socket-domain AF_SYSTEM) (socket-protocol 2)))`;
148
+ var isWithin = (path, root) => root === "/" || path === root || path.startsWith(`${root}/`);
149
+ var Params = class {
150
+ entries = [];
151
+ /** A `(param "…")` reference for `value`, under a fresh `prefix_n` key. */
152
+ ref(prefix, value) {
153
+ const key = `${prefix}_${String(this.entries.length)}`;
154
+ this.entries.push([key, value]);
155
+ return `(param "${key}")`;
156
+ }
157
+ };
158
+ var anchoredDirs = (input) => {
159
+ const dirs = new Set(input.writableRoots);
160
+ for (const path of input.protectedPaths) {
161
+ const roots = input.writableRoots.filter((root) => isWithin(path, root));
162
+ let dir = posix.dirname(path);
163
+ while (roots.some((root) => isWithin(dir, root))) {
164
+ dirs.add(dir);
165
+ const parent = posix.dirname(dir);
166
+ if (parent === dir) {
167
+ break;
168
+ }
169
+ dir = parent;
170
+ }
171
+ }
172
+ return [...dirs];
173
+ };
174
+ var allowSubpaths = (operations, refs) => refs.length === 0 ? [] : [
175
+ `(allow ${operations}
176
+ ${refs.map((r) => ` (subpath ${r})`).join("\n")})`
177
+ ];
178
+ var buildSeatbeltPolicy = (input) => {
179
+ const params = new Params();
180
+ const readable = [...new Set(input.readableRoots)].map(
181
+ (p) => params.ref("READ", p)
182
+ );
183
+ const writable = [...new Set(input.writableRoots)].map(
184
+ (p) => params.ref("WRITE", p)
185
+ );
186
+ const engineSockets = CONTAINER_ENGINE_SOCKETS.map(
187
+ (socket) => params.ref("ENGINE", socket)
188
+ );
189
+ const engineDirs = CONTAINER_ENGINE_HOME_DIRS.map(
190
+ (name) => params.ref("ENGINE", posix.join(input.hostHome, name))
191
+ );
192
+ const protectedRefs = [...new Set(input.protectedPaths)].map(
193
+ (p) => params.ref("PROTECTED", p)
194
+ );
195
+ const anchors = anchoredDirs(input).map((p) => params.ref("ANCHOR", p));
196
+ const engineFilters = [
197
+ ...engineSockets.map((r) => ` (literal ${r})`),
198
+ ...engineDirs.map((r) => ` (subpath ${r})`)
199
+ ].join("\n");
200
+ const profile = [
201
+ BASE,
202
+ "; Read-only: the system toolchain and the paths given to read.",
203
+ ...allowSubpaths("file-read* file-map-executable", readable),
204
+ "; Read/write: the worktree, the writable git dirs, the private home and temp dir.",
205
+ ...allowSubpaths("file-read* file-write* file-map-executable", writable),
206
+ "; No way into a container engine, which would be a way out.",
207
+ `(deny file-read* file-write* network-outbound process-exec
208
+ ${engineFilters})`,
209
+ '(deny mach-lookup (xpc-service-name-prefix ""))',
210
+ "; Last, so nothing above reopens them: the read-only git control files,",
211
+ "; and the dirs that hold them, which can't be moved aside.",
212
+ ...protectedRefs.map((r) => `(deny file-write* (subpath ${r}))`),
213
+ ...anchors.map(
214
+ (r) => `(deny file-write-unlink (require-all (vnode-type DIRECTORY) (literal ${r})))`
215
+ ),
216
+ "; Writes through read-only descriptors (F_MAKECOMPRESSED, F_TRANSFEREXTENTS).",
217
+ "(deny system-fcntl (fcntl-command 80 110))",
218
+ ""
219
+ ].join("\n");
220
+ return { profile, params: params.entries };
221
+ };
222
+
223
+ // src/seatbeltSandbox.ts
224
+ var SANDBOX_HOME = "/home/agent";
225
+ var FALLBACK_PATH = "/usr/bin:/bin:/usr/sbin:/sbin";
226
+ var XCODE_SELECT_LINK = "/var/db/xcode_select_link";
227
+ var isWithin2 = (path, root) => path === root || path.startsWith(`${root}/`);
228
+ var seatbeltMounts = (mounts) => resolveIdentityMounts("seatbelt", mounts, SANDBOX_HOME);
229
+ var makePrivateDirs = Effect_exports.gen(function* () {
230
+ const fs = yield* FileSystem_exports.FileSystem;
231
+ const root = yield* fs.realPath(
232
+ yield* fs.makeTempDirectory({ prefix: "sandcastle-seatbelt-" })
233
+ );
234
+ const dirs = { root, home: join(root, "home"), tmp: join(root, "tmp") };
235
+ yield* fs.makeDirectory(dirs.home);
236
+ yield* fs.makeDirectory(dirs.tmp);
237
+ return dirs;
238
+ }).pipe(
239
+ Effect_exports.mapError(
240
+ (e) => new SeatbeltError({
241
+ message: `Couldn't create the seatbelt() sandbox's private dirs: ${e.message}`
242
+ })
243
+ )
244
+ );
245
+ var removePrivateDirs = (dirs) => Effect_exports.gen(function* () {
246
+ const fs = yield* FileSystem_exports.FileSystem;
247
+ yield* fs.remove(dirs.root, { recursive: true }).pipe(Effect_exports.orElse(() => Effect_exports.void));
248
+ });
249
+ var realMount = (fs, mount) => Effect_exports.option(fs.realPath(mount.hostPath)).pipe(
250
+ Effect_exports.map(
251
+ Option_exports.map((hostPath) => ({
252
+ hostPath,
253
+ readonly: mount.readonly === true
254
+ }))
255
+ )
256
+ );
257
+ var sandboxSetup = (options, dirs, userMounts) => Effect_exports.gen(function* () {
258
+ const fs = yield* FileSystem_exports.FileSystem;
259
+ const toolchain = yield* hostPathToolchainFromEnv({
260
+ coveredRoots: SYSTEM_READ_ROOTS,
261
+ deniedRoots: []
262
+ });
263
+ const developerDir = yield* Effect_exports.option(fs.realPath(XCODE_SELECT_LINK));
264
+ const mounts = (yield* Effect_exports.all(
265
+ [...options.mounts, ...userMounts].map((m) => realMount(fs, m))
266
+ )).flatMap((m) => Option_exports.isSome(m) ? [m.value] : []);
267
+ const policy = buildSeatbeltPolicy({
268
+ readableRoots: [
269
+ ...SYSTEM_READ_ROOTS,
270
+ ...Option_exports.toArray(developerDir),
271
+ ...toolchain.readableDirs,
272
+ ...mounts.filter((m) => m.readonly).map((m) => m.hostPath)
273
+ ],
274
+ writableRoots: [
275
+ ...mounts.filter((m) => !m.readonly).map((m) => m.hostPath),
276
+ dirs.home,
277
+ dirs.tmp
278
+ ],
279
+ protectedPaths: mounts.filter((m) => m.readonly).map((m) => m.hostPath),
280
+ hostHome: homedir()
281
+ });
282
+ const env = {
283
+ ...options.env,
284
+ PATH: toolchain.pathEntries.length > 0 ? toolchain.pathEntries.join(":") : FALLBACK_PATH,
285
+ HOME: dirs.home,
286
+ TMPDIR: dirs.tmp
287
+ };
288
+ return { policy, env };
289
+ });
290
+ var sandboxExecArgs = (policy, command) => [
291
+ "-p",
292
+ policy.profile,
293
+ ...policy.params.map(([key, value]) => `-D${key}=${value}`),
294
+ "--",
295
+ "/bin/sh",
296
+ "-c",
297
+ command
298
+ ];
299
+ var toHostPath = (path, dirs, mounts) => {
300
+ const p = posix.normalize(path);
301
+ if (mounts.some((m) => isWithin2(p, m.hostPath))) {
302
+ return p;
303
+ }
304
+ if (isWithin2(p, SANDBOX_HOME)) {
305
+ return join(dirs.home, posix.relative(SANDBOX_HOME, p));
306
+ }
307
+ return p;
308
+ };
309
+
310
+ // src/sandboxes/seatbelt.ts
311
+ var killGroup = (proc) => {
312
+ if (proc.pid === void 0) {
313
+ return;
314
+ }
315
+ try {
316
+ process.kill(-proc.pid, "SIGKILL");
317
+ } catch {
318
+ }
319
+ };
320
+ var WATCHDOG = 'read -r reply || kill -9 -- "-$1" 2>/dev/null';
321
+ var startWatchdog = (pgid) => {
322
+ const watchdog = spawn("/bin/sh", ["-c", WATCHDOG, "sh", String(pgid)], {
323
+ detached: true,
324
+ stdio: ["pipe", "ignore", "ignore"]
325
+ });
326
+ watchdog.on("error", () => void 0);
327
+ watchdog.stdin.on("error", () => void 0);
328
+ return () => {
329
+ watchdog.stdin.end("exit\n");
330
+ };
331
+ };
332
+ var runInSeatbelt = async (command, opts, sandbox) => {
333
+ const { setup, live, maxTailChars } = sandbox;
334
+ const proc = spawn(SANDBOX_EXEC, sandboxExecArgs(setup.policy, command), {
335
+ cwd: opts.cwd,
336
+ env: setup.env,
337
+ detached: true,
338
+ stdio: ["pipe", "pipe", "pipe"]
339
+ });
340
+ const standDown = proc.pid === void 0 ? () => void 0 : startWatchdog(proc.pid);
341
+ live.add(proc);
342
+ proc.on("exit", () => {
343
+ killGroup(proc);
344
+ standDown();
345
+ });
346
+ const output = collectOutput(proc, opts.onLine, maxTailChars);
347
+ proc.stdin.on("error", () => void 0);
348
+ proc.stdin.end(opts.stdin ?? "");
349
+ try {
350
+ await once(proc, "close");
351
+ return { ...output(), exitCode: proc.exitCode ?? 1 };
352
+ } finally {
353
+ live.delete(proc);
354
+ }
355
+ };
356
+ var runOnHost = async (effect) => effect.pipe(Effect_exports.provide(NodeFileSystem_exports.layer), Effect_exports.runPromise);
357
+ var prepare = async (options, userMounts) => Effect_exports.gen(function* () {
358
+ const dirs = yield* makePrivateDirs;
359
+ const setup = yield* sandboxSetup(options, dirs, userMounts);
360
+ return { dirs, setup };
361
+ }).pipe(runOnHost);
362
+ var reportedDirs = (dirs) => ({
363
+ sandboxHomedir: dirs.home,
364
+ sandboxTmpdir: dirs.tmp
365
+ });
366
+ var createHandle = async (options, config) => {
367
+ const { maxTailChars, userMounts } = config;
368
+ const { dirs, setup } = await prepare(options, userMounts);
369
+ const live = /* @__PURE__ */ new Set();
370
+ const killAll = () => {
371
+ for (const proc of live) {
372
+ killGroup(proc);
373
+ }
374
+ };
375
+ const unregisterShutdown = registerShutdown(killAll);
376
+ let closed = false;
377
+ const hostPathOf = (p) => toHostPath(p, dirs, options.mounts);
378
+ return {
379
+ worktreePath: options.worktreePath,
380
+ ...reportedDirs(dirs),
381
+ exec: async (command, opts) => {
382
+ if (opts?.sudo === true) {
383
+ throw new Error(
384
+ "seatbelt() has no root: exec with sudo: true isn't supported in a native sandbox. Use docker() for setup that needs root."
385
+ );
386
+ }
387
+ if (closed) {
388
+ throw new Error("seatbelt() sandbox is closed");
389
+ }
390
+ const cwd = opts?.cwd ?? options.worktreePath;
391
+ return runInSeatbelt(
392
+ command,
393
+ { ...opts, cwd },
394
+ { setup, live, maxTailChars }
395
+ );
396
+ },
397
+ copyFileIn: async (hostPath, sandboxFile) => copyCreatingParents(hostPath, hostPathOf(sandboxFile)).pipe(runOnHost),
398
+ copyFileOut: async (sandboxFile, hostPath) => copyCreatingParents(hostPathOf(sandboxFile), hostPath).pipe(runOnHost),
399
+ close: async () => {
400
+ closed = true;
401
+ const exits = [...live].map(async (proc) => once(proc, "close"));
402
+ killAll();
403
+ await Promise.allSettled(exits);
404
+ unregisterShutdown();
405
+ await removePrivateDirs(dirs).pipe(runOnHost);
406
+ }
407
+ };
408
+ };
409
+ var seatbelt = (options) => {
410
+ const userMounts = seatbeltMounts(options?.mounts ?? []);
411
+ assertSeatbeltUsable();
412
+ const maxTailChars = options?.maxOutputTailChars ?? MAX_TAIL_CHARS;
413
+ return markNativeSandboxProvider(
414
+ createBindMountSandboxProvider({
415
+ name: "seatbelt",
416
+ env: options?.env ?? {},
417
+ sandboxHomedir: SANDBOX_HOME,
418
+ create: async (createOptions) => createHandle(createOptions, { maxTailChars, userMounts })
419
+ })
420
+ );
421
+ };
422
+
423
+ export { seatbelt };
424
+ //# sourceMappingURL=seatbelt.js.map
425
+ //# sourceMappingURL=seatbelt.js.map
@@ -0,0 +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;AAAA,EACjC,SAAA;AAAA,EACA,SAAA;AAAA,EACA,WAAA;AAAA,EACA,OAAA;AAAA,EACA;AACF,CAAA;A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H;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"]}
@@ -0,0 +1,54 @@
1
+ import { I as IsolatedSandboxProvider } from '../SandboxProvider-Chsi-Zs6.js';
2
+
3
+ /**
4
+ * Fly.io Sprites isolated sandbox provider — wraps `@fly/sprites` into a
5
+ * SandboxProvider.
6
+ *
7
+ * Usage:
8
+ * import { sprites } from "@ai-hero/sandcastle/sandboxes/sprites";
9
+ * await run({ agent: claudeCode("claude-opus-4-8"), sandbox: sprites() });
10
+ */
11
+
12
+ /** Options for the Fly.io Sprites sandbox provider. */
13
+ interface SpritesOptions {
14
+ /**
15
+ * Sprites API token.
16
+ *
17
+ * Falls back to the `SPRITES_TOKEN` environment variable, then to
18
+ * `SPRITE_TOKEN` (the name the Sprites CLI uses).
19
+ */
20
+ readonly token?: string;
21
+ /** Environment variables injected by this provider. Merged at launch time with env resolver and agent provider env. */
22
+ readonly env?: Record<string, string>;
23
+ /**
24
+ * Maximum number of characters of streamed `exec` output retained per stream
25
+ * (stdout and stderr) when an `onLine` callback is supplied (default: 64KiB).
26
+ *
27
+ * Output is delivered live to `onLine` regardless; this only bounds the tail
28
+ * returned in `ExecResult`, preventing a long-running agent's output from
29
+ * overflowing V8's max string length and crashing the run.
30
+ */
31
+ readonly maxOutputTailChars?: number;
32
+ }
33
+ /**
34
+ * Create a Fly.io Sprites isolated sandbox provider.
35
+ *
36
+ * Each `create()` makes a new Sprite, and `close()` deletes it. Sprites
37
+ * persist until deleted, so Sandcastle also deletes the Sprite when setup
38
+ * fails, and when the process is interrupted or exits without closing it.
39
+ * The default Sprite image ships `git`, Node and the `claude` CLI; install
40
+ * other agent CLIs in an `onSandboxReady` hook.
41
+ *
42
+ * Requires `@fly/sprites` to be installed as a peer dependency (it asks for
43
+ * Node 24 or later).
44
+ *
45
+ * @example
46
+ * ```ts
47
+ * import { sprites } from "@ai-hero/sandcastle/sandboxes/sprites";
48
+ *
49
+ * const provider = sprites({ env: { MY_VAR: "value" } });
50
+ * ```
51
+ */
52
+ declare const sprites: (options?: SpritesOptions) => IsolatedSandboxProvider;
53
+
54
+ export { type SpritesOptions, sprites };