@ai-hero/sandcastle 0.13.0 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +3 -3
  2. package/dist/{SandboxProvider-YCL97qco.d.ts → SandboxProvider-CwRLxIXZ.d.ts} +5 -41
  3. package/dist/{chunk-XCYK7I45.js → chunk-4BB7DNPW.js} +3 -3
  4. package/dist/chunk-4BB7DNPW.js.map +1 -0
  5. package/dist/chunk-4GZMUHVO.js +60 -0
  6. package/dist/chunk-4GZMUHVO.js.map +1 -0
  7. package/dist/{chunk-A4C2FG74.js → chunk-7JUTKCHL.js} +43 -42
  8. package/dist/chunk-7JUTKCHL.js.map +1 -0
  9. package/dist/chunk-7PHPLDVS.js +284 -0
  10. package/dist/chunk-7PHPLDVS.js.map +1 -0
  11. package/dist/{chunk-NMQ5Z6YG.js → chunk-BXLS4HRY.js} +15 -4
  12. package/dist/chunk-BXLS4HRY.js.map +1 -0
  13. package/dist/chunk-EM4QNWKF.js +3161 -0
  14. package/dist/chunk-EM4QNWKF.js.map +1 -0
  15. package/dist/chunk-EXYXBRCX.js +60 -0
  16. package/dist/chunk-EXYXBRCX.js.map +1 -0
  17. package/dist/{chunk-LWNC4UTZ.js → chunk-JEQ4IVQM.js} +1520 -5375
  18. package/dist/chunk-JEQ4IVQM.js.map +1 -0
  19. package/dist/{chunk-XCWKLDH4.js → chunk-L3BU47F6.js} +3 -3
  20. package/dist/{chunk-XCWKLDH4.js.map → chunk-L3BU47F6.js.map} +1 -1
  21. package/dist/{chunk-7N7AMUYA.js → chunk-PTJEKJPQ.js} +7 -5
  22. package/dist/chunk-PTJEKJPQ.js.map +1 -0
  23. package/dist/chunk-SAQXFLO2.js +1268 -0
  24. package/dist/chunk-SAQXFLO2.js.map +1 -0
  25. package/dist/{chunk-767EAJVT.js → chunk-TBVRAXYF.js} +3 -3
  26. package/dist/{chunk-767EAJVT.js.map → chunk-TBVRAXYF.js.map} +1 -1
  27. package/dist/{chunk-J5J5YJ5S.js → chunk-VUOXFCWO.js} +3 -3
  28. package/dist/{chunk-J5J5YJ5S.js.map → chunk-VUOXFCWO.js.map} +1 -1
  29. package/dist/{chunk-U42XXICG.js → chunk-WYOGXC72.js} +47 -82
  30. package/dist/chunk-WYOGXC72.js.map +1 -0
  31. package/dist/chunk-YDQW5IOY.js +799 -0
  32. package/dist/chunk-YDQW5IOY.js.map +1 -0
  33. package/dist/index.d.ts +51 -4
  34. package/dist/index.js +892 -2018
  35. package/dist/index.js.map +1 -1
  36. package/dist/main.js +322 -251
  37. package/dist/main.js.map +1 -1
  38. package/dist/sandboxes/bwrap.d.ts +1 -1
  39. package/dist/sandboxes/bwrap.js +9 -14
  40. package/dist/sandboxes/bwrap.js.map +1 -1
  41. package/dist/sandboxes/daytona.d.ts +1 -1
  42. package/dist/sandboxes/daytona.js +183 -136
  43. package/dist/sandboxes/daytona.js.map +1 -1
  44. package/dist/sandboxes/docker.d.ts +23 -1
  45. package/dist/sandboxes/docker.js +7 -3
  46. package/dist/sandboxes/e2b.d.ts +41 -0
  47. package/dist/sandboxes/e2b.js +202 -0
  48. package/dist/sandboxes/e2b.js.map +1 -0
  49. package/dist/sandboxes/modal.d.ts +78 -0
  50. package/dist/sandboxes/modal.js +171 -0
  51. package/dist/sandboxes/modal.js.map +1 -0
  52. package/dist/sandboxes/no-sandbox.d.ts +1 -1
  53. package/dist/sandboxes/no-sandbox.js +1 -1
  54. package/dist/sandboxes/podman.d.ts +27 -4
  55. package/dist/sandboxes/podman.js +19 -43
  56. package/dist/sandboxes/podman.js.map +1 -1
  57. package/dist/sandboxes/seatbelt.d.ts +2 -2
  58. package/dist/sandboxes/seatbelt.js +10 -7
  59. package/dist/sandboxes/seatbelt.js.map +1 -1
  60. package/dist/sandboxes/sprites.d.ts +54 -0
  61. package/dist/sandboxes/sprites.js +219 -0
  62. package/dist/sandboxes/sprites.js.map +1 -0
  63. package/dist/sandboxes/vercel.d.ts +10 -1
  64. package/dist/sandboxes/vercel.js +74 -46
  65. package/dist/sandboxes/vercel.js.map +1 -1
  66. package/dist/templates/parallel-planner/main.mts +43 -21
  67. package/dist/templates/parallel-planner-with-review/main.mts +55 -27
  68. package/dist/templates/sequential-reviewer/main.mts +1 -1
  69. package/package.json +36 -4
  70. package/dist/chunk-4EIVTSOZ.js +0 -93
  71. package/dist/chunk-4EIVTSOZ.js.map +0 -1
  72. package/dist/chunk-7N7AMUYA.js.map +0 -1
  73. package/dist/chunk-A4C2FG74.js.map +0 -1
  74. package/dist/chunk-LWNC4UTZ.js.map +0 -1
  75. package/dist/chunk-NMQ5Z6YG.js.map +0 -1
  76. package/dist/chunk-U42XXICG.js.map +0 -1
  77. package/dist/chunk-XCYK7I45.js.map +0 -1
@@ -1 +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;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;AAAA;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,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 { 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;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;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;AAAA;AAAA;;AAAA;AAAA;AA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A,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"]}
@@ -0,0 +1,54 @@
1
+ import { I as IsolatedSandboxProvider } from '../SandboxProvider-CwRLxIXZ.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 };
@@ -0,0 +1,219 @@
1
+ import { createRequire } from 'node:module';
2
+ import { registerShutdown } from '../chunk-EXYXBRCX.js';
3
+ import { Effect_exports, Config_exports } from '../chunk-JEQ4IVQM.js';
4
+ import { createIsolatedSandboxProvider } from '../chunk-4BB7DNPW.js';
5
+ import { MAX_TAIL_CHARS, BoundedTail } from '../chunk-6NQPCXSG.js';
6
+ import { randomUUID } from 'crypto';
7
+ import { mkdir, writeFile, stat, readFile, readdir } from 'fs/promises';
8
+ import { posix, dirname, join, relative } from 'path';
9
+ import { once } from 'events';
10
+ import { spawn } from 'child_process';
11
+
12
+ createRequire(import.meta.url);
13
+ var shellEscape = (s) => `'${s.replaceAll("'", String.raw`'\''`)}'`;
14
+ var outputSink = (separator, maxChars, onLine) => {
15
+ const chunks = [];
16
+ const tail = new BoundedTail(maxChars, separator);
17
+ let partial = "";
18
+ const emit = (line) => {
19
+ tail.push(line);
20
+ onLine?.(line);
21
+ };
22
+ return {
23
+ push: (chunk) => {
24
+ if (maxChars === void 0) {
25
+ chunks.push(chunk.toString());
26
+ return;
27
+ }
28
+ if (onLine === void 0) {
29
+ tail.push(chunk.toString());
30
+ return;
31
+ }
32
+ const lines = (partial + chunk.toString()).split("\n");
33
+ partial = lines.pop() ?? "";
34
+ for (const line of lines) {
35
+ emit(line);
36
+ }
37
+ },
38
+ flush: () => {
39
+ if (partial !== "") {
40
+ emit(partial);
41
+ partial = "";
42
+ }
43
+ },
44
+ toString: () => maxChars === void 0 ? chunks.join("") : tail.toString()
45
+ };
46
+ };
47
+ var stripUrlQueries = (text) => text.replaceAll(
48
+ /(?<url>(?:wss?|https?):\/\/[^\s?#)]*)[?#][^\s)]*/giu,
49
+ "$<url>"
50
+ );
51
+ var connectionError = (command, error) => {
52
+ const sdkError = error instanceof Error ? error : new Error(String(error));
53
+ const cause = new Error(stripUrlQueries(sdkError.message));
54
+ cause.name = sdkError.name;
55
+ cause.stack = sdkError.stack === void 0 ? void 0 : stripUrlQueries(sdkError.stack);
56
+ return new Error(
57
+ `sprites(): the connection failed: ${command} (${cause.message})`,
58
+ { cause }
59
+ );
60
+ };
61
+ var execInSprite = async (sprite, request) => {
62
+ const { command, onLine, maxOutputTailChars } = request;
63
+ const line = request.sudo === true ? `sudo sh -c ${shellEscape(command)}` : command;
64
+ const proc = sprite.spawn("sh", ["-c", line], {
65
+ cwd: request.cwd,
66
+ env: request.env
67
+ });
68
+ const streamed = onLine !== void 0;
69
+ const stdout = outputSink(
70
+ "\n",
71
+ streamed ? maxOutputTailChars : void 0,
72
+ onLine
73
+ );
74
+ const stderr = outputSink("", streamed ? maxOutputTailChars : void 0);
75
+ proc.stdout.on("data", stdout.push);
76
+ proc.stderr.on("data", stderr.push);
77
+ proc.once("spawn", () => {
78
+ proc.stdin.end(request.stdin ?? "");
79
+ });
80
+ proc.on("error", () => void 0);
81
+ const [exitArgs] = await Promise.all([
82
+ once(proc, "exit"),
83
+ once(proc.stdout, "end"),
84
+ once(proc.stderr, "end")
85
+ ]).catch((error) => {
86
+ throw connectionError(command, error);
87
+ });
88
+ const exitCode = exitArgs?.[0];
89
+ stdout.flush();
90
+ if (typeof exitCode !== "number" || exitCode < 0) {
91
+ throw new Error(
92
+ `sprites(): the connection closed before the command exited: ${command}`
93
+ );
94
+ }
95
+ return { stdout: stdout.toString(), stderr: stderr.toString(), exitCode };
96
+ };
97
+ var DELETE_SCRIPT = "fetch(process.argv[1], { method: 'DELETE', headers: { Authorization: 'Bearer ' + process.env.SANDCASTLE_SPRITES_TOKEN } }).catch(() => {});";
98
+ var registerSpriteDeletion = (baseURL, token, name) => registerShutdown(() => {
99
+ const url = `${baseURL}/v1/sprites/${encodeURIComponent(name)}`;
100
+ spawn(process.execPath, ["-e", DELETE_SCRIPT, url], {
101
+ detached: true,
102
+ stdio: "ignore",
103
+ windowsHide: true,
104
+ env: { ...process.env, SANDCASTLE_SPRITES_TOKEN: token }
105
+ }).unref();
106
+ });
107
+
108
+ // src/sandboxes/sprites.ts
109
+ var SPRITE_HOME = "/home/sprite";
110
+ var SPRITES_REPO_PATH = posix.join(SPRITE_HOME, "workspace");
111
+ var setOrUndefined = (value) => value === "" ? void 0 : value;
112
+ var envTokens = Effect_exports.all([
113
+ Config_exports.string("SPRITES_TOKEN").pipe(Config_exports.withDefault("")),
114
+ Config_exports.string("SPRITE_TOKEN").pipe(Config_exports.withDefault(""))
115
+ ]);
116
+ var resolveToken = async (options) => {
117
+ const [plural, singular] = await Effect_exports.runPromise(envTokens);
118
+ const token = setOrUndefined(options?.token) ?? setOrUndefined(plural) ?? setOrUndefined(singular);
119
+ if (token === void 0) {
120
+ throw new Error(
121
+ "sprites(): no Sprites token. Set SPRITES_TOKEN (or SPRITE_TOKEN), or pass the token option."
122
+ );
123
+ }
124
+ return token;
125
+ };
126
+ var copyIntoSprite = async (sprite, hostPath, sandboxPath) => {
127
+ const fs = sprite.filesystem();
128
+ const info = await stat(hostPath);
129
+ if (!info.isDirectory()) {
130
+ await fs.writeFile(sandboxPath, await readFile(hostPath));
131
+ return;
132
+ }
133
+ const entries = await readdir(hostPath, {
134
+ withFileTypes: true,
135
+ recursive: true
136
+ });
137
+ const files = entries.filter((entry) => entry.isFile()).map((entry) => join(entry.parentPath, entry.name));
138
+ await Promise.all(
139
+ files.map(async (file) => {
140
+ const parts = relative(hostPath, file).split(/[\\/]/u);
141
+ await fs.writeFile(
142
+ posix.join(sandboxPath, ...parts),
143
+ await readFile(file)
144
+ );
145
+ })
146
+ );
147
+ };
148
+ var isSpriteNotFound = (error) => error instanceof Error && "statusCode" in error && error.statusCode === 404;
149
+ var makeHandle = (sprite, { env, maxOutputTailChars, unregisterShutdown }) => ({
150
+ worktreePath: SPRITES_REPO_PATH,
151
+ // A Sprite is addressed by its name in the Sprites API and CLI.
152
+ sandboxId: sprite.name,
153
+ exec: async (command, opts) => execInSprite(sprite, {
154
+ ...opts,
155
+ command,
156
+ cwd: opts?.cwd ?? SPRITES_REPO_PATH,
157
+ env,
158
+ maxOutputTailChars
159
+ }),
160
+ copyIn: async (hostPath, sandboxPath) => copyIntoSprite(sprite, hostPath, sandboxPath),
161
+ copyFileOut: async (sandboxPath, hostPath) => {
162
+ const buffer = await sprite.filesystem().readFile(sandboxPath, null);
163
+ await mkdir(dirname(hostPath), { recursive: true });
164
+ await writeFile(hostPath, buffer);
165
+ },
166
+ close: async () => {
167
+ await sprite.delete().catch((error) => {
168
+ if (!isSpriteNotFound(error)) {
169
+ throw error;
170
+ }
171
+ });
172
+ unregisterShutdown();
173
+ }
174
+ });
175
+ var makeWorktreeDir = async (sprite) => {
176
+ const result = await execInSprite(sprite, {
177
+ command: `mkdir -p ${SPRITES_REPO_PATH}`,
178
+ cwd: SPRITE_HOME,
179
+ env: {},
180
+ maxOutputTailChars: MAX_TAIL_CHARS
181
+ });
182
+ if (result.exitCode !== 0) {
183
+ throw new Error(
184
+ `sprites(): could not create ${SPRITES_REPO_PATH}: ${result.stderr.trim()}`
185
+ );
186
+ }
187
+ };
188
+ var sprites = (options) => createIsolatedSandboxProvider({
189
+ name: "sprites",
190
+ env: options?.env,
191
+ create: async ({ env }) => {
192
+ const token = await resolveToken(options);
193
+ const { SpritesClient } = await import('@fly/sprites');
194
+ const client = new SpritesClient(token);
195
+ const name = `sandcastle-${randomUUID()}`;
196
+ const unregisterShutdown = registerSpriteDeletion(
197
+ client.baseURL,
198
+ token,
199
+ name
200
+ );
201
+ try {
202
+ const sprite = await client.createSprite(name);
203
+ await makeWorktreeDir(sprite);
204
+ return makeHandle(sprite, {
205
+ env,
206
+ maxOutputTailChars: options?.maxOutputTailChars ?? MAX_TAIL_CHARS,
207
+ unregisterShutdown
208
+ });
209
+ } catch (error) {
210
+ await client.deleteSprite(name).catch(() => void 0);
211
+ unregisterShutdown();
212
+ throw error;
213
+ }
214
+ }
215
+ });
216
+
217
+ export { sprites };
218
+ //# sourceMappingURL=sprites.js.map
219
+ //# sourceMappingURL=sprites.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/sandboxes/spritesExec.ts","../../src/sandboxes/spritesShutdown.ts","../../src/sandboxes/sprites.ts"],"names":[],"mappings":";;;;;;;;;;;;AAsBA,IAAM,WAAA,GAAc,CAAC,CAAA,KACnB,CAAA,CAAA,EAAI,EAAE,UAAA,CAAW,GAAA,EAAK,MAAA,CAAO,GAAA,CAAA,IAAA,CAAS,C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` for the Fly.io Sprites provider (`sprites.ts`): runs a command over\n * the `@fly/sprites` exec WebSocket and streams its stdout lines.\n */\n\nimport { once } from \"node:events\";\nimport type { ExecResult } from \"../SandboxProvider.js\";\nimport { BoundedTail } from \"../boundedTail.js\";\nimport type { Sprite } from \"@fly/sprites\";\n\n/** What one `exec` in a Sprite needs. */\nexport interface SpriteExecRequest {\n readonly command: string;\n readonly cwd: string;\n readonly env: Record<string, string>;\n readonly onLine?: (line: string) => void;\n readonly sudo?: boolean;\n readonly stdin?: string;\n /** Bound on the stdout and stderr tails of a streamed `exec`. */\n readonly maxOutputTailChars: number;\n}\n\nconst shellEscape = (s: string): string =>\n `'${s.replaceAll(\"'\", String.raw`'\\''`)}'`;\n\n/**\n * A sink for one output stream. Streamed: each complete line goes to\n * `onLine` at once and into a bounded tail, and `flush()` hands over a last\n * line that has no trailing newline. Buffered: the whole output is kept.\n */\nconst outputSink = (\n separator: string,\n maxChars: number | undefined,\n onLine?: (line: string) => void,\n) => {\n const chunks: string[] = [];\n const tail = new BoundedTail(maxChars, separator);\n let partial = \"\";\n const emit = (line: string): void => {\n tail.push(line);\n onLine?.(line);\n };\n return {\n push: (chunk: Buffer): void => {\n if (maxChars === undefined) {\n chunks.push(chunk.toString());\n return;\n }\n if (onLine === undefined) {\n tail.push(chunk.toString());\n return;\n }\n const lines = (partial + chunk.toString()).split(\"\\n\");\n partial = lines.pop() ?? \"\";\n for (const line of lines) {\n emit(line);\n }\n },\n flush: (): void => {\n if (partial !== \"\") {\n emit(partial);\n partial = \"\";\n }\n },\n toString: (): string =>\n maxChars === undefined ? chunks.join(\"\") : tail.toString(),\n };\n};\n\n/** Drop the query string from every URL in `text`. */\nconst stripUrlQueries = (text: string): string =>\n text.replaceAll(\n /(?<url>(?:wss?|https?):\\/\\/[^\\s?#)]*)[?#][^\\s)]*/giu,\n \"$<url>\",\n );\n\n/**\n * The error for a failed exec connection. The SDK's error names the exec URL,\n * whose query string carries the command's env, so the error and its `cause`\n * keep only the URL's path.\n */\nconst connectionError = (command: string, error: unknown): Error => {\n const sdkError = error instanceof Error ? error : new Error(String(error));\n const cause = new Error(stripUrlQueries(sdkError.message));\n cause.name = sdkError.name;\n cause.stack =\n sdkError.stack === undefined ? undefined : stripUrlQueries(sdkError.stack);\n return new Error(\n `sprites(): the connection failed: ${command} (${cause.message})`,\n { cause },\n );\n};\n\n/**\n * Run a command in the Sprite. stdin is always sent and closed (empty when\n * unset), so a command that reads it gets EOF rather than waiting. With\n * `onLine`, stdout lines are delivered live as they arrive; without it, the\n * whole stdout comes back, as sync-out needs.\n */\nexport const execInSprite = async (\n sprite: Sprite,\n request: SpriteExecRequest,\n): Promise<ExecResult> => {\n const { command, onLine, maxOutputTailChars } = request;\n const line =\n request.sudo === true ? `sudo sh -c ${shellEscape(command)}` : command;\n const proc = sprite.spawn(\"sh\", [\"-c\", line], {\n cwd: request.cwd,\n env: request.env,\n });\n const streamed = onLine !== undefined;\n const stdout = outputSink(\n \"\\n\",\n streamed ? maxOutputTailChars : undefined,\n onLine,\n );\n const stderr = outputSink(\"\", streamed ? maxOutputTailChars : undefined);\n proc.stdout.on(\"data\", stdout.push);\n proc.stderr.on(\"data\", stderr.push);\n proc.once(\"spawn\", () => {\n proc.stdin.end(request.stdin ?? \"\");\n });\n // A late error, after the command has exited, must not crash the process.\n proc.on(\"error\", () => undefined);\n // `once` rejects if the command emits \"error\" (a failed connection) first.\n // The SDK ends both streams on exit; wait for them so no chunk is missed.\n const [exitArgs]: unknown[][] = await Promise.all([\n once(proc, \"exit\"),\n once(proc.stdout, \"end\"),\n once(proc.stderr, \"end\"),\n ]).catch((error: unknown) => {\n throw connectionError(command, error);\n });\n const exitCode = exitArgs?.[0];\n stdout.flush();\n if (typeof exitCode !== \"number\" || exitCode < 0) {\n throw new Error(\n `sprites(): the connection closed before the command exited: ${command}`,\n );\n }\n return { stdout: stdout.toString(), stderr: stderr.toString(), exitCode };\n};\n","/**\n * Interrupt teardown for the Fly.io Sprites provider (`sprites.ts`). Sprites\n * persist until deleted, so a run interrupted before `close()` would leave\n * its Sprite running.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { registerShutdown } from \"../shutdownRegistry.js\";\n\n/** Deletes the Sprite at `process.argv[1]`, with the token from the env. */\nconst DELETE_SCRIPT =\n \"fetch(process.argv[1], { method: 'DELETE', headers: { Authorization: 'Bearer ' + process.env.SANDCASTLE_SPRITES_TOKEN } }).catch(() => {});\";\n\n/**\n * Register a teardown that deletes the Sprite `name` if the process is\n * interrupted (`SIGINT`/`SIGTERM`) or exits before it is unregistered.\n * Shutdown teardowns are synchronous and the process exits as soon as they\n * return, so the delete can't be awaited: it runs in a detached child process,\n * which outlives this one and finishes it.\n *\n * @returns An idempotent function that unregisters the teardown.\n */\nexport const registerSpriteDeletion = (\n baseURL: string,\n token: string,\n name: string,\n): (() => void) =>\n registerShutdown(() => {\n const url = `${baseURL}/v1/sprites/${encodeURIComponent(name)}`;\n spawn(process.execPath, [\"-e\", DELETE_SCRIPT, url], {\n detached: true,\n stdio: \"ignore\",\n windowsHide: true,\n env: { ...process.env, SANDCASTLE_SPRITES_TOKEN: token },\n }).unref();\n });\n","/**\n * Fly.io Sprites isolated sandbox provider — wraps `@fly/sprites` into a\n * SandboxProvider.\n *\n * Usage:\n * import { sprites } from \"@ai-hero/sandcastle/sandboxes/sprites\";\n * await run({ agent: claudeCode(\"claude-opus-4-8\"), sandbox: sprites() });\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { mkdir, readdir, readFile, stat, writeFile } from \"node:fs/promises\";\nimport { dirname, join, posix, relative } from \"node:path\";\nimport { Config, Effect } from \"effect\";\nimport { createIsolatedSandboxProvider } from \"../SandboxProvider.js\";\nimport type {\n ExecResult,\n IsolatedSandboxHandle,\n IsolatedSandboxProvider,\n} from \"../SandboxProvider.js\";\nimport { MAX_TAIL_CHARS } from \"../boundedTail.js\";\nimport { execInSprite } from \"./spritesExec.js\";\nimport { registerSpriteDeletion } from \"./spritesShutdown.js\";\nimport type { Sprite } from \"@fly/sprites\";\n\n/** The Sprite user's home: the worktree's parent, which the user can write. */\nconst SPRITE_HOME = \"/home/sprite\";\n\n/** Worktree path inside the Sprite. */\nconst SPRITES_REPO_PATH = posix.join(SPRITE_HOME, \"workspace\");\n\n/** Options for the Fly.io Sprites sandbox provider. */\nexport interface SpritesOptions {\n /**\n * Sprites API token.\n *\n * Falls back to the `SPRITES_TOKEN` environment variable, then to\n * `SPRITE_TOKEN` (the name the Sprites CLI uses).\n */\n readonly token?: string;\n\n /** Environment variables injected by this provider. Merged at launch time with env resolver and agent provider env. */\n readonly env?: Record<string, string>;\n\n /**\n * Maximum number of characters of streamed `exec` output retained per stream\n * (stdout and stderr) when an `onLine` callback is supplied (default: 64KiB).\n *\n * Output is delivered live to `onLine` regardless; this only bounds the tail\n * returned in `ExecResult`, preventing a long-running agent's output from\n * overflowing V8's max string length and crashing the run.\n */\n readonly maxOutputTailChars?: number;\n}\n\n/** An option or env var counts as unset when it is missing or empty. */\nconst setOrUndefined = (value: string | undefined): string | undefined =>\n value === \"\" ? undefined : value;\n\n/** `SPRITES_TOKEN` then `SPRITE_TOKEN` from the environment, \"\" when unset. */\nconst envTokens = Effect.all([\n Config.string(\"SPRITES_TOKEN\").pipe(Config.withDefault(\"\")),\n Config.string(\"SPRITE_TOKEN\").pipe(Config.withDefault(\"\")),\n]);\n\n/** The token: the option, then `SPRITES_TOKEN`, then `SPRITE_TOKEN`. */\nconst resolveToken = async (\n options: SpritesOptions | undefined,\n): Promise<string> => {\n const [plural, singular] = await Effect.runPromise(envTokens);\n const token =\n setOrUndefined(options?.token) ??\n setOrUndefined(plural) ??\n setOrUndefined(singular);\n if (token === undefined) {\n throw new Error(\n \"sprites(): no Sprites token. Set SPRITES_TOKEN (or SPRITE_TOKEN), or pass the token option.\",\n );\n }\n return token;\n};\n\n/** Copy a host file, or every file under a host directory, into the Sprite. */\nconst copyIntoSprite = async (\n sprite: Sprite,\n hostPath: string,\n sandboxPath: string,\n): Promise<void> => {\n const fs = sprite.filesystem();\n const info = await stat(hostPath);\n if (!info.isDirectory()) {\n await fs.writeFile(sandboxPath, await readFile(hostPath));\n return;\n }\n const entries = await readdir(hostPath, {\n withFileTypes: true,\n recursive: true,\n });\n const files = entries\n .filter((entry) => entry.isFile())\n .map((entry) => join(entry.parentPath, entry.name));\n // `writeFile` creates the parent folders in the Sprite.\n await Promise.all(\n files.map(async (file) => {\n const parts = relative(hostPath, file).split(/[\\\\/]/u);\n await fs.writeFile(\n posix.join(sandboxPath, ...parts),\n await readFile(file),\n );\n }),\n );\n};\n\n/**\n * Whether `error` is the Sprites API's answer to deleting a Sprite that\n * doesn't exist: the SDK's `APIError` with status 404 (body\n * `{\"error\":\"sprite not found\"}`).\n */\nconst isSpriteNotFound = (error: unknown): boolean =>\n error instanceof Error && \"statusCode\" in error && error.statusCode === 404;\n\n/** What a handle needs beyond its Sprite. */\ninterface HandleContext {\n readonly env: Record<string, string>;\n readonly maxOutputTailChars: number;\n readonly unregisterShutdown: () => void;\n}\n\n/** The Sandcastle handle over a Sprite whose worktree folder exists. */\nconst makeHandle = (\n sprite: Sprite,\n { env, maxOutputTailChars, unregisterShutdown }: HandleContext,\n): IsolatedSandboxHandle => ({\n worktreePath: SPRITES_REPO_PATH,\n // A Sprite is addressed by its name in the Sprites API and CLI.\n sandboxId: sprite.name,\n\n exec: async (command, opts): Promise<ExecResult> =>\n execInSprite(sprite, {\n ...opts,\n command,\n cwd: opts?.cwd ?? SPRITES_REPO_PATH,\n env,\n maxOutputTailChars,\n }),\n\n copyIn: async (hostPath, sandboxPath): Promise<void> =>\n copyIntoSprite(sprite, hostPath, sandboxPath),\n\n copyFileOut: async (sandboxPath, hostPath): Promise<void> => {\n const buffer = await sprite.filesystem().readFile(sandboxPath, null);\n await mkdir(dirname(hostPath), { recursive: true });\n await writeFile(hostPath, buffer);\n },\n\n close: async (): Promise<void> => {\n await sprite.delete().catch((error: unknown) => {\n // Already gone (deleted out-of-band, expired or reaped): closed.\n if (!isSpriteNotFound(error)) {\n throw error;\n }\n });\n // Only once the delete has gone through: if it threw, the exit teardown\n // tries again.\n unregisterShutdown();\n },\n});\n\n/** Create the worktree folder as the Sprite user, so sync-in can replace it. */\nconst makeWorktreeDir = async (sprite: Sprite): Promise<void> => {\n const result = await execInSprite(sprite, {\n command: `mkdir -p ${SPRITES_REPO_PATH}`,\n cwd: SPRITE_HOME,\n env: {},\n maxOutputTailChars: MAX_TAIL_CHARS,\n });\n if (result.exitCode !== 0) {\n throw new Error(\n `sprites(): could not create ${SPRITES_REPO_PATH}: ${result.stderr.trim()}`,\n );\n }\n};\n\n/**\n * Create a Fly.io Sprites isolated sandbox provider.\n *\n * Each `create()` makes a new Sprite, and `close()` deletes it. Sprites\n * persist until deleted, so Sandcastle also deletes the Sprite when setup\n * fails, and when the process is interrupted or exits without closing it.\n * The default Sprite image ships `git`, Node and the `claude` CLI; install\n * other agent CLIs in an `onSandboxReady` hook.\n *\n * Requires `@fly/sprites` to be installed as a peer dependency (it asks for\n * Node 24 or later).\n *\n * @example\n * ```ts\n * import { sprites } from \"@ai-hero/sandcastle/sandboxes/sprites\";\n *\n * const provider = sprites({ env: { MY_VAR: \"value\" } });\n * ```\n */\nexport const sprites = (options?: SpritesOptions): IsolatedSandboxProvider =>\n createIsolatedSandboxProvider({\n name: \"sprites\",\n env: options?.env,\n create: async ({ env }): Promise<IsolatedSandboxHandle> => {\n const token = await resolveToken(options);\n // Dynamic import so the peer dependency is only loaded at runtime\n const { SpritesClient } = await import(\"@fly/sprites\");\n const client = new SpritesClient(token);\n const name = `sandcastle-${randomUUID()}`;\n // Registered before the create request, so an interrupt while it is in\n // flight still deletes the Sprite (deleting a missing name is a no-op).\n const unregisterShutdown = registerSpriteDeletion(\n client.baseURL,\n token,\n name,\n );\n try {\n const sprite = await client.createSprite(name);\n await makeWorktreeDir(sprite);\n return makeHandle(sprite, {\n env,\n maxOutputTailChars: options?.maxOutputTailChars ?? MAX_TAIL_CHARS,\n unregisterShutdown,\n });\n } catch (error) {\n // No handle exists yet, so neither Sandcastle's teardown nor\n // `close()` can reach the Sprite, and it would persist.\n await client.deleteSprite(name).catch(() => undefined);\n unregisterShutdown();\n throw error;\n }\n },\n });\n"]}
@@ -1,4 +1,4 @@
1
- import { I as IsolatedSandboxProvider } from '../SandboxProvider-YCL97qco.js';
1
+ import { I as IsolatedSandboxProvider } from '../SandboxProvider-CwRLxIXZ.js';
2
2
 
3
3
  /**
4
4
  * Vercel isolated sandbox provider — wraps `@vercel/sandbox` into a SandboxProvider.
@@ -86,6 +86,15 @@ interface VercelOptions {
86
86
  * Maps to the `runtime` option.
87
87
  */
88
88
  readonly template?: string;
89
+ /**
90
+ * Whether Vercel keeps the sandbox's filesystem when it stops (default:
91
+ * `false`).
92
+ *
93
+ * Vercel snapshots a persistent sandbox each time it stops, and the snapshot
94
+ * counts against your snapshot storage. Sandcastle makes one sandbox per
95
+ * run, so it turns this off unless you set it.
96
+ */
97
+ readonly persistent?: boolean;
89
98
  /** Environment variables injected by this provider. Merged at launch time with env resolver and agent provider env. */
90
99
  readonly env?: Record<string, string>;
91
100
  /**