{"_id":"@chenshaohui6988/sandcastle","_rev":"5-53c027d13f4afd0636e74e445e4577b5","name":"@chenshaohui6988/sandcastle","dist-tags":{"latest":"0.13.2"},"versions":{"0.11.0":{"name":"@chenshaohui6988/sandcastle","version":"0.11.0","keywords":["cli","sandbox","docker","ai","agent"],"license":"MIT","_id":"@chenshaohui6988/sandcastle@0.11.0","maintainers":[{"name":"chenshaohui6988","email":"chenshaohui6988@163.com"}],"homepage":"https://github.com/mattpocock/sandcastle#readme","bugs":{"url":"https://github.com/mattpocock/sandcastle/issues"},"bin":{"sandcastle":"dist/main.js"},"dist":{"shasum":"c5c4f7f57f71fdd243794a2aa818322a5fee19b5","tarball":"https://registry.npmjs.org/@chenshaohui6988/sandcastle/-/sandcastle-0.11.0.tgz","fileCount":64,"integrity":"sha512-C+liqOjYj3jo+Eimi2FBrRxfxKfwdff2XJ6t8Yvg/FwyR35Gi1dH/E4+Ae4Itwou5e8YVssl9hLOwJoBwXW6BA==","signatures":[{"sig":"MEUCIAwwn8SihieDdCwqIq2GMI5jaW+pZfdS5NFk3TaKNINIAiEA4379sCuBKCSBjEiIn6MJDPM/cIj5YQvg7BVtEG0+QJQ=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":14872075},"main":"./dist/index.js","type":"module","types":"./dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js"},"./sandboxes/docker":{"types":"./dist/sandboxes/docker.d.ts","import":"./dist/sandboxes/docker.js"},"./sandboxes/podman":{"types":"./dist/sandboxes/podman.d.ts","import":"./dist/sandboxes/podman.js"},"./sandboxes/vercel":{"types":"./dist/sandboxes/vercel.d.ts","import":"./dist/sandboxes/vercel.js"},"./sandboxes/daytona":{"types":"./dist/sandboxes/daytona.d.ts","import":"./dist/sandboxes/daytona.js"},"./sandboxes/no-sandbox":{"types":"./dist/sandboxes/no-sandbox.d.ts","import":"./dist/sandboxes/no-sandbox.js"}},"gitHead":"2d93226d37da129c54d4ecfd5b370122b48b31b2","scripts":{"test":"vitest run","build":"tsup","format":"prettier --write .","prepare":"husky","release":"changeset publish","postbuild":"rm -rf dist/templates && cp -r src/templates dist/templates && node scripts/check-public-types-effect-free.mjs","typecheck":"tsgo --noEmit","sandcastle":"npm run build && tsx .sandcastle/run.ts","test:watch":"vitest","test-podman":"npm run build && tsx --env-file=.sandcastle/.env .sandcastle/test-podman.ts","test-vercel":"npm run build && tsx --env-file=.sandcastle/.env .sandcastle/test-vercel.ts","format:check":"prettier --check .","test-interactive":"npm run build && tsx --env-file=.sandcastle/.env .sandcastle/test-interactive.ts"},"_npmUser":{"name":"chenshaohui6988","email":"chenshaohui6988@163.com"},"repository":{"url":"git+https://github.com/mattpocock/sandcastle.git","type":"git"},"_npmVersion":"10.9.2","description":"CLI for orchestrating AI agents in isolated sandbox environments","directories":{},"_nodeVersion":"23.11.0","dependencies":{"@clack/prompts":"^1.1.0"},"publishConfig":{"access":"public"},"_hasShrinkwrap":false,"packageManager":"npm@10.9.2","devDependencies":{"tsx":"^4.21.0","zod":"^4.4.3","tsup":"^8.5.1","husky":"^9.1.7","effect":"^3.20.0","vitest":"^3.2.0","prettier":"^3.5.3","typescript":"^6.0.3","@effect/cli":"^0.74.0","@types/node":"^25.5.0","lint-staged":"^15.5.1","@daytona/sdk":"^0.164.0","@changesets/cli":"^2.30.0","@effect/printer":"^0.48.0","@effect/platform":"^0.95.0","@effect/printer-ansi":"^0.48.0","@effect/platform-node":"^0.105.0","@typescript/native-preview":"^7.0.0-dev.20260317.1"},"peerDependencies":{"@daytona/sdk":"^0.164.0","@vercel/sandbox":">=1.0.0"},"peerDependenciesMeta":{"@daytona/sdk":{"optional":true},"@vercel/sandbox":{"optional":true}},"_npmOperationalInternal":{"tmp":"tmp/sandcastle_0.11.0_1782272977592_0.32001718776517296","host":"s3://npm-registry-packages-npm-production"}},"0.12.0":{"name":"@chenshaohui6988/sandcastle","version":"0.12.0","keywords":["cli","sandbox","docker","ai","agent"],"license":"MIT","_id":"@chenshaohui6988/sandcastle@0.12.0","maintainers":[{"name":"chenshaohui6988","email":"chenshaohui6988@163.com"}],"homepage":"https://github.com/mattpocock/sandcastle#readme","bugs":{"url":"https://github.com/mattpocock/sandcastle/issues"},"bin":{"sandcastle":"dist/main.js"},"dist":{"shasum":"ecffe72a5e1ca823d919b248bee8207b2ce2a3f4","tarball":"https://registry.npmjs.org/@chenshaohui6988/sandcastle/-/sandcastle-0.12.0.tgz","fileCount":64,"integrity":"sha512-PhSUPs0SG6vnqhJafEZThReUUJo4poWykt7EcBr5O4Xp5DVC43RWipiAYlv/mOjkbGY7UJk9yS8mE6//k/lt5w==","signatures":[{"sig":"MEUCIHAV3rYR4SohjTEnIog4+JYp1dZJhzgQ7F0coVXgPISsAiEA+pcy+FTfZdN0B82dbc34Ohu0t0FSi2UjsPFRe4olcVI=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":14878301},"main":"./dist/index.js","type":"module","types":"./dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js"},"./sandboxes/docker":{"types":"./dist/sandboxes/docker.d.ts","import":"./dist/sandboxes/docker.js"},"./sandboxes/podman":{"types":"./dist/sandboxes/podman.d.ts","import":"./dist/sandboxes/podman.js"},"./sandboxes/vercel":{"types":"./dist/sandboxes/vercel.d.ts","import":"./dist/sandboxes/vercel.js"},"./sandboxes/daytona":{"types":"./dist/sandboxes/daytona.d.ts","import":"./dist/sandboxes/daytona.js"},"./sandboxes/no-sandbox":{"types":"./dist/sandboxes/no-sandbox.d.ts","import":"./dist/sandboxes/no-sandbox.js"}},"gitHead":"17a90408a3d481d2ce597d7eca24cfe61d79cbb5","scripts":{"test":"vitest run","build":"tsup","format":"prettier --write .","prepare":"husky","release":"changeset publish","postbuild":"rm -rf dist/templates && cp -r src/templates dist/templates && node scripts/check-public-types-effect-free.mjs","typecheck":"tsgo --noEmit","sandcastle":"npm run build && tsx .sandcastle/run.ts","test:watch":"vitest","test-podman":"npm run build && tsx --env-file=.sandcastle/.env .sandcastle/test-podman.ts","test-vercel":"npm run build && tsx --env-file=.sandcastle/.env .sandcastle/test-vercel.ts","format:check":"prettier --check .","test-interactive":"npm run build && tsx --env-file=.sandcastle/.env .sandcastle/test-interactive.ts"},"_npmUser":{"name":"chenshaohui6988","email":"chenshaohui6988@163.com"},"repository":{"url":"git+https://github.com/mattpocock/sandcastle.git","type":"git"},"_npmVersion":"10.9.2","description":"CLI for orchestrating AI agents in isolated sandbox environments","directories":{},"_nodeVersion":"23.11.0","dependencies":{"@clack/prompts":"^1.1.0"},"publishConfig":{"access":"public"},"_hasShrinkwrap":false,"packageManager":"npm@10.9.2","devDependencies":{"tsx":"^4.21.0","zod":"^4.4.3","tsup":"^8.5.1","husky":"^9.1.7","effect":"^3.20.0","vitest":"^3.2.0","prettier":"^3.5.3","typescript":"^6.0.3","@effect/cli":"^0.74.0","@types/node":"^25.5.0","lint-staged":"^15.5.1","@daytona/sdk":"^0.164.0","@changesets/cli":"^2.30.0","@effect/printer":"^0.48.0","@effect/platform":"^0.95.0","@effect/printer-ansi":"^0.48.0","@effect/platform-node":"^0.105.0","@typescript/native-preview":"^7.0.0-dev.20260317.1"},"peerDependencies":{"@daytona/sdk":"^0.164.0","@vercel/sandbox":">=1.0.0"},"peerDependenciesMeta":{"@daytona/sdk":{"optional":true},"@vercel/sandbox":{"optional":true}},"_npmOperationalInternal":{"tmp":"tmp/sandcastle_0.12.0_1782287554228_0.041677549183325446","host":"s3://npm-registry-packages-npm-production"}},"0.13.0":{"name":"@chenshaohui6988/sandcastle","version":"0.13.0","keywords":["cli","sandbox","docker","ai","agent"],"license":"MIT","_id":"@chenshaohui6988/sandcastle@0.13.0","maintainers":[{"name":"chenshaohui6988","email":"chenshaohui6988@163.com"}],"homepage":"https://github.com/mattpocock/sandcastle#readme","bugs":{"url":"https://github.com/mattpocock/sandcastle/issues"},"bin":{"sandcastle":"dist/main.js"},"dist":{"shasum":"ae2682b74299395166f7b47ef226976846de945a","tarball":"https://registry.npmjs.org/@chenshaohui6988/sandcastle/-/sandcastle-0.13.0.tgz","fileCount":64,"integrity":"sha512-M2tG3ZC3w9vOFnBqD34/7zQuapBGIS68cs4u6+Zc20krqeLV942BLiRoHLo0Ltt1stWP9va9j0Se5FphyAUx+A==","signatures":[{"sig":"MEUCIEprFdza7hj/19ZsYb9cZLsWo6O436z3e2jtoVgHexYhAiEAw7zfFgLZ7iWSCyBhFMyxW197SPSKoA20n4hqZvs/Dn4=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":15073926},"main":"./dist/index.js","type":"module","types":"./dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js"},"./sandboxes/docker":{"types":"./dist/sandboxes/docker.d.ts","import":"./dist/sandboxes/docker.js"},"./sandboxes/podman":{"types":"./dist/sandboxes/podman.d.ts","import":"./dist/sandboxes/podman.js"},"./sandboxes/vercel":{"types":"./dist/sandboxes/vercel.d.ts","import":"./dist/sandboxes/vercel.js"},"./sandboxes/daytona":{"types":"./dist/sandboxes/daytona.d.ts","import":"./dist/sandboxes/daytona.js"},"./sandboxes/no-sandbox":{"types":"./dist/sandboxes/no-sandbox.d.ts","import":"./dist/sandboxes/no-sandbox.js"}},"gitHead":"abc7d8849d04b1bddfe467d3d40b774b7e0664e8","scripts":{"test":"vitest run","build":"tsup","format":"prettier --write .","prepare":"husky","release":"changeset publish","postbuild":"rm -rf dist/templates && cp -r src/templates dist/templates && node scripts/check-public-types-effect-free.mjs","typecheck":"tsgo --noEmit","sandcastle":"npm run build && tsx .sandcastle/run.ts","test:watch":"vitest","test-podman":"npm run build && tsx --env-file=.sandcastle/.env .sandcastle/test-podman.ts","test-vercel":"npm run build && tsx --env-file=.sandcastle/.env .sandcastle/test-vercel.ts","format:check":"prettier --check .","test-interactive":"npm run build && tsx --env-file=.sandcastle/.env .sandcastle/test-interactive.ts"},"_npmUser":{"name":"chenshaohui6988","email":"chenshaohui6988@163.com"},"repository":{"url":"git+https://github.com/mattpocock/sandcastle.git","type":"git"},"_npmVersion":"10.9.2","description":"CLI for orchestrating AI agents in isolated sandbox environments","directories":{},"_nodeVersion":"23.11.0","dependencies":{"@clack/prompts":"^1.1.0"},"publishConfig":{"access":"public"},"_hasShrinkwrap":false,"packageManager":"npm@10.9.2","devDependencies":{"tsx":"^4.21.0","zod":"^4.4.3","tsup":"^8.5.1","husky":"^9.1.7","effect":"^3.20.0","vitest":"^3.2.0","prettier":"^3.5.3","typescript":"^6.0.3","@effect/cli":"^0.74.0","@types/node":"^25.5.0","lint-staged":"^15.5.1","@daytona/sdk":"^0.164.0","@changesets/cli":"^2.30.0","@effect/printer":"^0.48.0","@effect/platform":"^0.95.0","@effect/printer-ansi":"^0.48.0","@effect/platform-node":"^0.105.0","@typescript/native-preview":"^7.0.0-dev.20260317.1"},"peerDependencies":{"@daytona/sdk":"^0.164.0","@vercel/sandbox":">=1.0.0"},"peerDependenciesMeta":{"@daytona/sdk":{"optional":true},"@vercel/sandbox":{"optional":true}},"_npmOperationalInternal":{"tmp":"tmp/sandcastle_0.13.0_1782375484552_0.12889531972070123","host":"s3://npm-registry-packages-npm-production"}},"0.13.1":{"name":"@chenshaohui6988/sandcastle","version":"0.13.1","keywords":["cli","sandbox","docker","ai","agent"],"license":"MIT","_id":"@chenshaohui6988/sandcastle@0.13.1","maintainers":[{"name":"chenshaohui6988","email":"chenshaohui6988@163.com"}],"homepage":"https://github.com/mattpocock/sandcastle#readme","bugs":{"url":"https://github.com/mattpocock/sandcastle/issues"},"bin":{"sandcastle":"dist/main.js"},"dist":{"shasum":"b054d05433f90a2b30eceb3f26f12587df649ae9","tarball":"https://registry.npmjs.org/@chenshaohui6988/sandcastle/-/sandcastle-0.13.1.tgz","fileCount":64,"integrity":"sha512-uQyfD+sDgAVbJ9EO6ebPNQf/X/ymFLcqMsCd5vN72ygdVaGFTZUrGY5ZW/qUhfJAtSxKN7zlx+N0QBkIqaYvnQ==","signatures":[{"sig":"MEYCIQChRbXzEaf9JfF7H8gqcJBG9Da3FDh/qwxUYEbWl2sUBgIhAPiS0xDpym4MlGEz7LhXnDBUcyPsW+iQZIobmGjYOtP6","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":15074085},"main":"./dist/index.js","type":"module","types":"./dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js"},"./sandboxes/docker":{"types":"./dist/sandboxes/docker.d.ts","import":"./dist/sandboxes/docker.js"},"./sandboxes/podman":{"types":"./dist/sandboxes/podman.d.ts","import":"./dist/sandboxes/podman.js"},"./sandboxes/vercel":{"types":"./dist/sandboxes/vercel.d.ts","import":"./dist/sandboxes/vercel.js"},"./sandboxes/daytona":{"types":"./dist/sandboxes/daytona.d.ts","import":"./dist/sandboxes/daytona.js"},"./sandboxes/no-sandbox":{"types":"./dist/sandboxes/no-sandbox.d.ts","import":"./dist/sandboxes/no-sandbox.js"}},"gitHead":"5804e192ac8a2847988ed10fd00886dd0db09717","scripts":{"test":"vitest run","build":"tsup","format":"prettier --write .","prepare":"husky","release":"changeset publish","postbuild":"rm -rf dist/templates && cp -r src/templates dist/templates && node scripts/check-public-types-effect-free.mjs","typecheck":"tsgo --noEmit","sandcastle":"npm run build && tsx .sandcastle/run.ts","test:watch":"vitest","test-podman":"npm run build && tsx --env-file=.sandcastle/.env .sandcastle/test-podman.ts","test-vercel":"npm run build && tsx --env-file=.sandcastle/.env .sandcastle/test-vercel.ts","format:check":"prettier --check .","test-interactive":"npm run build && tsx --env-file=.sandcastle/.env .sandcastle/test-interactive.ts"},"_npmUser":{"name":"chenshaohui6988","email":"chenshaohui6988@163.com"},"repository":{"url":"git+https://github.com/mattpocock/sandcastle.git","type":"git"},"_npmVersion":"10.9.2","description":"CLI for orchestrating AI agents in isolated sandbox environments","directories":{},"_nodeVersion":"23.11.0","dependencies":{"@clack/prompts":"^1.1.0"},"publishConfig":{"access":"public"},"_hasShrinkwrap":false,"packageManager":"npm@10.9.2","devDependencies":{"tsx":"^4.21.0","zod":"^4.4.3","tsup":"^8.5.1","husky":"^9.1.7","effect":"^3.20.0","vitest":"^3.2.0","prettier":"^3.5.3","typescript":"^6.0.3","@effect/cli":"^0.74.0","@types/node":"^25.5.0","lint-staged":"^15.5.1","@daytona/sdk":"^0.164.0","@changesets/cli":"^2.30.0","@effect/printer":"^0.48.0","@effect/platform":"^0.95.0","@effect/printer-ansi":"^0.48.0","@effect/platform-node":"^0.105.0","@typescript/native-preview":"^7.0.0-dev.20260317.1"},"peerDependencies":{"@daytona/sdk":"^0.164.0","@vercel/sandbox":">=1.0.0"},"peerDependenciesMeta":{"@daytona/sdk":{"optional":true},"@vercel/sandbox":{"optional":true}},"_npmOperationalInternal":{"tmp":"tmp/sandcastle_0.13.1_1782376455328_0.3607680854917954","host":"s3://npm-registry-packages-npm-production"}},"0.13.2":{"name":"@chenshaohui6988/sandcastle","version":"0.13.2","description":"CLI for orchestrating AI agents in isolated sandbox environments","type":"module","main":"./dist/index.js","types":"./dist/index.d.ts","exports":{".":{"import":"./dist/index.js","types":"./dist/index.d.ts"},"./sandboxes/docker":{"import":"./dist/sandboxes/docker.js","types":"./dist/sandboxes/docker.d.ts"},"./sandboxes/vercel":{"import":"./dist/sandboxes/vercel.js","types":"./dist/sandboxes/vercel.d.ts"},"./sandboxes/podman":{"import":"./dist/sandboxes/podman.js","types":"./dist/sandboxes/podman.d.ts"},"./sandboxes/daytona":{"import":"./dist/sandboxes/daytona.js","types":"./dist/sandboxes/daytona.d.ts"},"./sandboxes/no-sandbox":{"import":"./dist/sandboxes/no-sandbox.js","types":"./dist/sandboxes/no-sandbox.d.ts"}},"bin":{"sandcastle":"dist/main.js"},"publishConfig":{"access":"public"},"scripts":{"build":"tsup","postbuild":"rm -rf dist/templates && cp -r src/templates dist/templates && node scripts/check-public-types-effect-free.mjs","test":"vitest run","test:watch":"vitest","typecheck":"tsgo --noEmit","format":"prettier --write .","format:check":"prettier --check .","prepare":"husky","release":"changeset publish","sandcastle":"npm run build && tsx .sandcastle/run.ts","test-podman":"npm run build && tsx --env-file=.sandcastle/.env .sandcastle/test-podman.ts","test-vercel":"npm run build && tsx --env-file=.sandcastle/.env .sandcastle/test-vercel.ts","test-interactive":"npm run build && tsx --env-file=.sandcastle/.env .sandcastle/test-interactive.ts"},"keywords":["cli","sandbox","docker","ai","agent"],"packageManager":"npm@10.9.2","repository":{"type":"git","url":"git+https://github.com/mattpocock/sandcastle.git"},"license":"MIT","devDependencies":{"@changesets/cli":"^2.30.0","@daytona/sdk":"^0.164.0","@effect/cli":"^0.74.0","@effect/platform":"^0.95.0","@effect/platform-node":"^0.105.0","@effect/printer":"^0.48.0","@effect/printer-ansi":"^0.48.0","@types/node":"^25.5.0","@typescript/native-preview":"^7.0.0-dev.20260317.1","effect":"^3.20.0","husky":"^9.1.7","lint-staged":"^15.5.1","prettier":"^3.5.3","tsup":"^8.5.1","tsx":"^4.21.0","typescript":"^6.0.3","vitest":"^3.2.0","zod":"^4.4.3"},"dependencies":{"@clack/prompts":"^1.1.0","@langchain/langgraph":"^1.4.6","@langchain/langgraph-checkpoint-sqlite":"^1.0.3"},"peerDependencies":{"@daytona/sdk":"^0.164.0","@vercel/sandbox":">=1.0.0"},"peerDependenciesMeta":{"@vercel/sandbox":{"optional":true},"@daytona/sdk":{"optional":true}},"_id":"@chenshaohui6988/sandcastle@0.13.2","gitHead":"e00ad5abaa1b894751814d0577006c763a2a88cd","bugs":{"url":"https://github.com/mattpocock/sandcastle/issues"},"homepage":"https://github.com/mattpocock/sandcastle#readme","_nodeVersion":"23.11.0","_npmVersion":"10.9.2","dist":{"integrity":"sha512-U7Lq1Nn6nSxboaMG9pS6dJMVx7jeXbGa3+WOG6V70OochKv2jnpRuk14BvHwl8S+vVVPCHY9uwzH/WTPgxoPCQ==","shasum":"16cea48b7ddf6c7e55a884f26274578a3f446afb","tarball":"https://registry.npmjs.org/@chenshaohui6988/sandcastle/-/sandcastle-0.13.2.tgz","fileCount":64,"unpackedSize":15213837,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEQCIHbHWbUmVdcpQ/GPM0wqbepoIwrwTnUup+efI0Xf3dTGAiAT0ntllW1gYWhKbNZgjn5qoPX3zA1O3ptvX7Ze+u6MyA=="}]},"_npmUser":{"name":"chenshaohui6988","email":"chenshaohui6988@163.com"},"directories":{},"maintainers":[{"name":"chenshaohui6988","email":"chenshaohui6988@163.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/sandcastle_0.13.2_1782445382586_0.5793482816303375"},"_hasShrinkwrap":false}},"time":{"created":"2026-06-24T03:49:37.449Z","modified":"2026-06-26T03:43:03.050Z","0.11.0":"2026-06-24T03:49:37.822Z","0.12.0":"2026-06-24T07:52:34.457Z","0.13.0":"2026-06-25T08:18:04.807Z","0.13.1":"2026-06-25T08:34:15.566Z","0.13.2":"2026-06-26T03:43:02.955Z"},"bugs":{"url":"https://github.com/mattpocock/sandcastle/issues"},"license":"MIT","homepage":"https://github.com/mattpocock/sandcastle#readme","keywords":["cli","sandbox","docker","ai","agent"],"repository":{"type":"git","url":"git+https://github.com/mattpocock/sandcastle.git"},"description":"CLI for orchestrating AI agents in isolated sandbox environments","maintainers":[{"name":"chenshaohui6988","email":"chenshaohui6988@163.com"}],"readme":"<div align=\"center\">\n  <picture>\n    <source media=\"(prefers-color-scheme: dark)\" srcset=\"https://res.cloudinary.com/total-typescript/image/upload/v1775033787/readme-sandcastle-ondark_2x.png\">\n    <source media=\"(prefers-color-scheme: light)\" srcset=\"https://res.cloudinary.com/total-typescript/image/upload/v1775033787/readme-sandcastle-onlight_2x.png\">\n    <img alt=\"Sandcastle\" src=\"https://res.cloudinary.com/total-typescript/image/upload/v1775033787/readme-sandcastle-onlight_2x.png\" height=\"200\" style=\"margin-bottom: 20px;\">\n  </picture>\n</div>\n\n## What Is Sandcastle?\n\nA TypeScript library for orchestrating AI coding agents in isolated sandboxes:\n\n1. You invoke agents with a single `sandcastle.run()`.\n2. Sandcastle handles sandboxing the agent with a configurable branch strategy.\n3. The commits made on the branches get merged back.\n\nSandcastle is provider-agnostic — it ships with built-in providers for Docker, Podman, and Vercel, and you can create your own. Great for parallelizing multiple AFK agents, creating review pipelines, or even just orchestrating your own agents.\n\n## Prerequisites\n\n- [Git](https://git-scm.com/)\n- A sandbox provider — Sandcastle needs an isolated environment to run agents in. Built-in options:\n  - [Docker Desktop](https://www.docker.com/) — most common for local development\n  - [Podman](https://podman.io/) — rootless alternative to Docker\n  - [Vercel](https://vercel.com/) — cloud-based Firecracker microVMs via `@vercel/sandbox`\n  - Or [create your own](#custom-sandbox-providers) using `createBindMountSandboxProvider` or `createIsolatedSandboxProvider`\n\n## Quick start\n\nBy the end of this path, you should know three things:\n\n- how to scaffold a Sandcastle runner for a repository\n- how the runner chooses the right agent skill flow before coding\n- when to use single-repo `run()`, PRD-driven `runWorkspaceTask()`, or lower-level `runWorkspace()`\n\n1. Install the package:\n\n```bash\nnpm install --save-dev @chenshaohui6988/sandcastle\n```\n\n2. Run `npx @chenshaohui6988/sandcastle init`. This scaffolds a `.sandcastle` directory with all the files needed.\n\n```bash\nnpx @chenshaohui6988/sandcastle init\n```\n\n3. Edit `.sandcastle/.env` and fill in your default values for `CLAUDE_CODE_OAUTH_TOKEN` (run `claude setup-token` on your host to get one). To use an Anthropic API key instead, uncomment and fill in `ANTHROPIC_API_KEY`.\n\n```bash\ncp .sandcastle/.env.example .sandcastle/.env\n```\n\n4. Run the `.sandcastle/main.ts` (or `main.mts`) file with `npx tsx`\n\n```bash\nnpx tsx .sandcastle/main.ts\n```\n\n```typescript\n// 3. Run the agent via the JS API\nimport { run, claudeCode } from \"@chenshaohui6988/sandcastle\";\nimport { docker } from \"@chenshaohui6988/sandcastle/sandboxes/docker\";\n\nawait run({\n  agent: claudeCode(\"claude-opus-4-8\"),\n  sandbox: docker(), // or podman(), vercel(), or your own provider\n  promptFile: \".sandcastle/prompt.md\",\n});\n```\n\n## Quick Smoke Test\n\nBefore you hand Sandcastle a real task, run a minimal read-only check to confirm the whole pipeline is wired up: the sandbox starts, the agent authenticates, a command runs inside it, and the iteration loop exits cleanly. It is the fastest way to separate a setup problem from a task problem.\n\nDrop this into `.sandcastle/main.ts` (or any scratch file) and run it with `npx tsx`:\n\n```typescript\nimport { run, claudeCode } from \"@chenshaohui6988/sandcastle\";\nimport { docker } from \"@chenshaohui6988/sandcastle/sandboxes/docker\";\n\nconst result = await run({\n  agent: claudeCode(\"claude-opus-4-8\"),\n  sandbox: docker(), // or podman(), noSandbox()\n  prompt:\n    \"Run `echo sandcastle-ok` and report what it printed. \" +\n    \"Do not modify any files. \" +\n    \"Output <promise>COMPLETE</promise> when done.\",\n});\n\nconsole.log(result.completionSignal); // \"<promise>COMPLETE</promise>\"\nconsole.log(result.commits.length); // 0 — the smoke test changes nothing\n```\n\n```bash\nnpx tsx .sandcastle/main.ts\n```\n\nA healthy run typically finishes within a minute and:\n\n- prints the completion signal (`<promise>COMPLETE</promise>`) — the agent started, authenticated, and the loop exited on the signal instead of timing out\n- reports `0` commits — the read-only prompt left your working tree untouched\n\nIf it hangs or throws instead, you have isolated the failure to setup rather than your task. Common causes:\n\n- **Auth** — `CLAUDE_CODE_OAUTH_TOKEN` (or `ANTHROPIC_API_KEY`) missing or invalid in `.sandcastle/.env`\n- **Sandbox** — Docker/Podman is not running, or the image is not built yet (`sandcastle docker build-image`)\n- **Network** — the agent CLI cannot reach its model provider from inside the sandbox\n\nBest practice: keep this check around and re-run it after editing your Dockerfile, rotating tokens, or upgrading Sandcastle. A green smoke test confirms the plumbing before you debug a real run.\n\n## Agent Skill Routing\n\nSandcastle scaffolds `.sandcastle/SKILL_ROUTER.md` as a companion workflow guide. Before an agent starts project work, it should read the router, choose the matching skill flow, and make sure the target repository's `AGENTS.md` or `CLAUDE.md` accurately describes the project-specific rules.\n\nThink of the router as a table of contents for agent work. It does not install every skill, and it does not replace project guidance. It helps the agent answer one question first: \"What kind of work is this?\"\n\nCodex and Claude Code can load skills differently, but the Sandcastle habit is the same: choose first, load second. Codex should keep the selected skills active in its skill profile. Claude Code should have the matching `SKILL.md` directories available under `.claude/skills/` so its native skill discovery can read only the skills needed for the task.\n\nThis is the recommended entry sequence:\n\n1. Run `sandcastle init`.\n2. Review `.sandcastle/SKILL_ROUTER.md`.\n3. Sync the selected skills into the active agent setup.\n4. Update `AGENTS.md` or `CLAUDE.md` when project guidance is missing or stale.\n5. Start implementation only after the workflow is selected.\n\nSee [`sandcastle init`](#sandcastle-init) for the full business flow diagram and best practices.\n\n## Learn The Workflow\n\nSandcastle is easiest to learn as a sequence, not as an API catalog.\n\n### 1. Start With The Smallest Runner\n\nUse `sandcastle init` first. It creates the local runner files under `.sandcastle/` and gives the agent a prompt file to read. Do not start by writing a custom orchestration script unless you already know which lifecycle you need.\n\nAfter init, inspect these files:\n\n| File                          | What to learn from it                                                    |\n| ----------------------------- | ------------------------------------------------------------------------ |\n| `.sandcastle/main.ts`         | Which agent, sandbox provider, branch strategy, and prompt file will run |\n| `.sandcastle/prompt.md`       | What the agent is asked to do each iteration                             |\n| `.sandcastle/SKILL_ROUTER.md` | Which skill flow should be selected before project work starts           |\n| `.sandcastle/workspace.json`  | Which repositories are candidates for multi-repository planning          |\n| `.sandcastle/.env.example`    | Which host-side credentials the selected agent and issue tracker need    |\n\n### 2. Pick The Right Execution Shape\n\nChoose the smallest API that matches the work:\n\n| Situation                                      | Use this                 | Why                                                             |\n| ---------------------------------------------- | ------------------------ | --------------------------------------------------------------- |\n| One prompt, one repository                     | `run()`                  | Starts an agent once or for a bounded number of iterations      |\n| Several agent passes on the same branch        | `createSandbox()`        | Reuses one sandbox for implement-then-review or repair loops    |\n| You need a managed branch before running agent | `createWorktree()`       | Gives you direct control over worktree lifecycle                |\n| One request may touch several repositories     | `runWorkspaceTask()`     | Plans alignment, technical work, repo issues, and execution     |\n| One agent must see several repos at once       | `runWorkspace()`         | Lower-level multi-repo sandbox primitive                        |\n| A local markdown issue should be implemented   | `sandcastle local-issue` | Runs a scoped host-side issue flow without per-repo scaffolding |\n\n### 3. Do A First Practice Run\n\nFor a safe first pass, use a read-only prompt:\n\n```markdown\n# Task\n\nRead this repository's AGENTS.md, CLAUDE.md, and .sandcastle/SKILL_ROUTER.md.\nExplain which skill flow should be used for a small bug fix.\n\n# Done\n\nOutput <promise>COMPLETE</promise> when finished.\n```\n\nRun it with:\n\n```bash\nnpx tsx .sandcastle/main.ts\n```\n\nYou should see the agent explain the selected flow without changing code. A good first result names the likely flow, says whether `AGENTS.md` or `CLAUDE.md` needs an update, and stops before implementation. After that, replace the prompt with a real issue or use the workspace commands for PRD-driven work.\n\n### 4. Avoid Common Mistakes\n\n- Do not copy every available skill into the active agent. Load the skill flow selected by `.sandcastle/SKILL_ROUTER.md`.\n- Do not put project facts in the router. Put build commands, repo boundaries, terminology, and verification rules in `AGENTS.md` or `CLAUDE.md`.\n- Do not start with `runWorkspaceTask()` for a one-repo bug fix. Use `run()` until the task actually needs multi-repo planning.\n- Do not let chat history be the only source of instructions. If future agents need the rule, write it into project guidance.\n- Do not skip the read-only practice run when teaching a new team or a new repository. It confirms the agent can find the router and explain the workflow before it writes code.\n\n### Check Your Understanding\n\nBefore you let an agent write code, you should be able to answer:\n\n- Which file tells the agent how to choose a skill flow?\n- Which file holds project-specific rules?\n- Which API creates reusable sandboxes?\n- Which command turns a PRD into repository-specific issues?\n- Where will generated workspace planning artifacts be written?\n\nIf any answer is unclear, read [`sandcastle init`](#sandcastle-init), [`runWorkspaceTask()`](#runworkspacetask--plan-and-execute-across-repositories), and [`sandcastle workspace plan`](#sandcastle-workspace-plan) before running implementation.\n\n## Sandbox Providers\n\nSandcastle uses a `SandboxProvider` to create isolated environments. The `sandbox` option on `run()`, `interactive()`, and `createSandbox()` accepts any provider, including `noSandbox()` — opt in to running the agent directly on the host when container isolation is undesired. Built-in providers:\n\n| Provider   | Import path                                        | Type       | Accepted by                                                   |\n| ---------- | -------------------------------------------------- | ---------- | ------------------------------------------------------------- |\n| Docker     | `@chenshaohui6988/sandcastle/sandboxes/docker`     | Bind-mount | `run()`, `runWorkspace()`, `createSandbox()`, `interactive()` |\n| Podman     | `@chenshaohui6988/sandcastle/sandboxes/podman`     | Bind-mount | `run()`, `runWorkspace()`, `createSandbox()`, `interactive()` |\n| Vercel     | `@chenshaohui6988/sandcastle/sandboxes/vercel`     | Isolated   | `run()`, `createSandbox()`, `interactive()`                   |\n| No-sandbox | `@chenshaohui6988/sandcastle/sandboxes/no-sandbox` | None       | `run()`, `createSandbox()`, `interactive()`                   |\n\nWorktree methods (`wt.run()`, `wt.interactive()`, `wt.createSandbox()`) accept the same providers as their top-level counterparts. `wt.interactive()` defaults to `noSandbox()` when no sandbox is specified.\n\n```typescript\nimport { docker } from \"@chenshaohui6988/sandcastle/sandboxes/docker\";\nimport { podman } from \"@chenshaohui6988/sandcastle/sandboxes/podman\";\nimport { vercel } from \"@chenshaohui6988/sandcastle/sandboxes/vercel\";\nimport { noSandbox } from \"@chenshaohui6988/sandcastle/sandboxes/no-sandbox\";\n\n// Docker, Podman, and Vercel are interchangeable in run() and createSandbox():\nawait run({\n  agent: claudeCode(\"claude-opus-4-8\"),\n  sandbox: docker(),\n  prompt: \"...\",\n});\n\n// No-sandbox runs the agent directly on the host — accepted by run(),\n// createSandbox(), and interactive(). Skips container isolation entirely:\nawait interactive({\n  agent: claudeCode(\"claude-opus-4-8\"),\n  sandbox: noSandbox(),\n  prompt: \"...\", // optional — omit to launch the TUI with no initial prompt\n  cwd: \"/path/to/other-repo\", // optional — defaults to process.cwd()\n});\n```\n\nYou can also [create your own provider](#custom-sandbox-providers) using `createBindMountSandboxProvider` or `createIsolatedSandboxProvider`.\n\n## API\n\nSandcastle exports programmatic APIs for use in scripts, CI pipelines, or custom tooling. Use `run()` for one repository, `runWorkspaceTask()` when one product request may affect multiple repositories, and `runWorkspace()` when you need the lower-level multi-repository sandbox primitive directly. The examples below use `docker()`, but any compatible `SandboxProvider` works in its place.\n\n```typescript\nimport { run, claudeCode } from \"@chenshaohui6988/sandcastle\";\nimport { docker } from \"@chenshaohui6988/sandcastle/sandboxes/docker\";\n\nconst result = await run({\n  agent: claudeCode(\"claude-opus-4-8\"),\n  sandbox: docker(),\n  promptFile: \".sandcastle/prompt.md\",\n});\n\nconsole.log(result.iterations.length); // number of iterations executed\nconsole.log(result.iterations); // per-iteration results with optional sessionId\nconsole.log(result.commits); // array of { sha } for commits created\nconsole.log(result.branch); // target branch name\n```\n\n### `runWorkspaceTask()` — plan and execute across repositories\n\nUse `runWorkspaceTask()` when you have a PRD or product request and a set of candidate repositories. Sandcastle runs a planner agent first, asks it to produce PRD alignment notes, a technical plan, and repository-local issues, then runs one executor agent per selected repository in parallel. Each executor gets its own managed worktree, branch, commits, dirty preservation, and result entry.\n\n```typescript\nimport { runWorkspaceTask, claudeCode } from \"@chenshaohui6988/sandcastle\";\nimport { docker } from \"@chenshaohui6988/sandcastle/sandboxes/docker\";\n\nconst result = await runWorkspaceTask({\n  repositories: [\n    {\n      name: \"vocimcore\",\n      cwd: \"/Users/me/IdeaProjects/vocimcore\",\n      kind: \"backend\",\n      description: \"Core domain model, API contract, and shared types\",\n    },\n    {\n      name: \"vocsearchmng\",\n      cwd: \"/Users/me/IdeaProjects/vocsearchmng\",\n      kind: \"backend\",\n      description: \"Search service integration\",\n    },\n    {\n      name: \"vocimmng\",\n      cwd: \"/Users/me/IdeaProjects/vocimmng\",\n      kind: \"backend\",\n      description: \"IM management backend\",\n    },\n    {\n      name: \"vocmngweb\",\n      cwd: \"/Users/me/IdeaProjects/vocmngweb\",\n      kind: \"frontend\",\n      description: \"Management UI\",\n    },\n    {\n      name: \"vocprod\",\n      cwd: \"/Users/me/IdeaProjects/vocprod\",\n      kind: \"frontend\",\n      description: \"Product-facing UI\",\n    },\n  ],\n  agent: claudeCode(\"claude-opus-4-8\"),\n  sandbox: docker(),\n  branchPrefix: \"codex/01-add-im-session-robot-source\",\n  prompt: \"Implement IM session robot source support.\",\n});\n\nconsole.log(result.plan.alignment); // automatic PRD alignment notes\nconsole.log(result.plan.technicalPlan); // cross-repository technical plan\nconsole.log(result.plan.repositories); // repository issues selected by the planner\nconsole.log(result.repositories.vocimcore?.commits);\nconsole.log(result.repositories.vocmngweb?.status);\n```\n\nThe planner must emit a `<workspace_plan>` JSON block containing `alignment`, a `technicalPlan`, and per-repository issue bodies. Sandcastle validates that every planned repository exists in the candidate list and rejects duplicate or unknown repository names before execution.\n\nExecution result entries are grouped by repository:\n\n```typescript\ntype WorkspaceTaskRepositoryResult = {\n  task: string;\n  reason?: string;\n  status: \"success\" | \"failed\";\n  branch: string;\n  commits: Array<{ sha: string }>;\n  stdout?: string;\n  preservedWorktreePath?: string;\n  error?: string;\n};\n```\n\nYou can run the same flow from the CLI with a JSON config instead of writing a TypeScript runner:\n\n```json\n{\n  \"branchPrefix\": \"codex/01-add-im-session-robot-source\",\n  \"repositories\": [\n    {\n      \"name\": \"vocimcore\",\n      \"cwd\": \"../vocimcore\",\n      \"kind\": \"backend\",\n      \"description\": \"Core domain model, API contract, and shared types\"\n    },\n    {\n      \"name\": \"vocmngweb\",\n      \"cwd\": \"../vocmngweb\",\n      \"kind\": \"frontend\",\n      \"description\": \"Management UI\"\n    }\n  ]\n}\n```\n\n```bash\nsandcastle workspace plan --prd-file ./prd.md\n# Review .scratch/<prd-name>/alignment.md, technical-plan.md, and issues/*.md\nsandcastle workspace execute --plan-file .scratch/<prd-name>/workspace-plan.json\n```\n\nFor PRD-first workflows, `workspace plan --prd-file ./prd.md` writes `.scratch/<prd-name>/workspace-plan.json`, `.scratch/<prd-name>/alignment.md`, `.scratch/<prd-name>/technical-plan.md`, and `.scratch/<prd-name>/issues/<repo>.md`. The plan JSON snapshots the workspace chosen for that PRD, so later execution uses the repositories recorded in the plan instead of whatever `.sandcastle/workspace.json` contains at that time. Review those artifacts, then run `workspace execute --plan-file .scratch/<prd-name>/workspace-plan.json` to execute the approved repository issues in parallel.\n\n`workspace run --prd-file ./prd.md` is the fully automatic pipeline: PRD alignment, technical plan, repository issue generation, and execution in one command. When the current repo has exactly one ready local issue under `.scratch/`, `workspace run` can still use that issue as the prompt file automatically. Pass one of `--prd`, `--prd-file`, `--prompt`, or `--prompt-file` to override it.\n\n### `runWorkspace()` — multi-repository tasks\n\nUse `runWorkspace()` when you need the lower-level primitive: one agent invocation sees several managed repositories in the same sandbox. Sandcastle creates one managed worktree per repository, bind-mounts all of them into the same sandbox under `/home/agent/repos/<name>`, runs the agent from the primary repository, and returns commits grouped by repository.\n\n```typescript\nimport { runWorkspace, claudeCode } from \"@chenshaohui6988/sandcastle\";\nimport { docker } from \"@chenshaohui6988/sandcastle/sandboxes/docker\";\n\nconst result = await runWorkspace({\n  repositories: [\n    {\n      name: \"vocimcore\",\n      cwd: \"/Users/me/IdeaProjects/vocimcore\",\n      branchStrategy: {\n        type: \"branch\",\n        branch: \"codex/01-add-im-session-robot-source-core\",\n      },\n      copyToWorktree: [\"node_modules\"],\n    },\n    {\n      name: \"vocmngweb\",\n      cwd: \"/Users/me/IdeaProjects/vocmngweb\",\n      branchStrategy: {\n        type: \"branch\",\n        branch: \"codex/01-add-im-session-robot-source-web\",\n      },\n    },\n  ],\n  primaryRepository: \"vocimcore\",\n  agent: claudeCode(\"claude-opus-4-8\"),\n  sandbox: docker(),\n  prompt: \"Implement the cross-repo feature.\",\n  maxIterations: 1,\n});\n\nconsole.log(result.repositories.vocimcore.commits);\nconsole.log(result.repositories.vocmngweb.commits);\n```\n\nThe agent prompt is automatically appended with a workspace manifest listing every repository name, sandbox path, branch, and the primary repository. For example, `vocimcore` is available at `/home/agent/repos/vocimcore` and `vocmngweb` at `/home/agent/repos/vocmngweb`.\n\nEach repository has its own `cwd`, `branchStrategy`, `copyToWorktree`, and `hooks`. If `branchStrategy` is omitted, Sandcastle uses `{ type: \"merge-to-head\" }` for that repository. `{ type: \"branch\", branch }` is supported. `{ type: \"head\" }` is rejected because `runWorkspace()` always uses managed worktrees.\n\nThe result is grouped by repository:\n\n```typescript\ntype RunWorkspaceResult = {\n  repositories: {\n    [name: string]: {\n      branch: string;\n      worktreePath: string;\n      commits: Array<{ sha: string }>;\n      preservedWorktreePath?: string;\n    };\n  };\n  stdout: string;\n  iterations: IterationResult[];\n  completionSignal?: string;\n  logFilePath?: string;\n};\n```\n\nV1 limitations:\n\n- `runWorkspace()` supports bind-mount sandbox providers only, such as Docker and Podman. Isolated providers throw a clear error.\n- The lower-level `runWorkspace()` primitive has no direct CLI. Use `sandcastle workspace run` for the product-level planner/executor workflow.\n- Extra provider mounts are still provider-level mounts. Repositories that need git lifecycle management must be listed in `repositories`.\n\n### All options\n\n```typescript\nimport { run, claudeCode } from \"@chenshaohui6988/sandcastle\";\nimport { docker } from \"@chenshaohui6988/sandcastle/sandboxes/docker\";\n\nconst result = await run({\n  // Agent provider — required. Pass a model string to claudeCode().\n  // Optional second arg for provider-specific options like effort level.\n  agent: claudeCode(\"claude-opus-4-8\", { effort: \"high\" }),\n\n  // Sandbox provider — required. Any SandboxProvider works (docker, podman, vercel, or custom).\n  // Provider-specific config (like imageName, mounts) lives inside the provider factory call.\n  sandbox: docker({\n    imageName: \"sandcastle:local\",\n    // Optional: override the UID/GID used for --user flag (defaults to host UID/GID).\n    // Must match the UID baked into the image. Pre-flight check catches mismatches.\n    // containerUid: 1000,\n    // containerGid: 1000,\n    // Optional: mount host directories into the sandbox (e.g. package manager caches)\n    // hostPath supports absolute, tilde-expanded (~), and relative paths (resolved from cwd).\n    // sandboxPath supports absolute and relative paths (resolved from the sandbox repo directory).\n    mounts: [\n      { hostPath: \"~/.npm\", sandboxPath: \"/home/agent/.npm\", readonly: true },\n      { hostPath: \"data\", sandboxPath: \"data\" }, // mounts <cwd>/data → <sandbox-repo>/data\n    ],\n    // Optional: SELinux volume label — \"z\" (default, shared), \"Z\" (private), or false (none).\n    // No-op on non-SELinux systems (Docker Desktop on macOS/Windows, Linux without SELinux).\n    selinuxLabel: \"z\",\n    // Optional: provider-level env vars merged at launch time\n    env: { DOCKER_SPECIFIC: \"value\" },\n    // Optional: attach container to Docker network(s) — string or string[]\n    network: \"my-network\",\n    // Optional: add the container user to supplementary groups via --group-add.\n    // Accepts group names or numeric GIDs (e.g. for a bind-mounted Docker socket).\n    groups: [\"docker\", 999],\n    // Optional: expose host devices via --device. Each entry is a full device\n    // spec in host[:container[:permissions]] form (e.g. \"/dev/kvm\").\n    devices: [\"/dev/kvm\"],\n    // Optional: limit CPU resources via --cpus. Fractional values allowed (e.g. 1.5).\n    // cpus: 2,\n  }),\n\n  // Host repo directory — replaces process.cwd() as the anchor for\n  // .sandcastle/ artifacts (worktrees, logs, env, patches) and git operations.\n  // Relative paths resolve against process.cwd(). Defaults to process.cwd().\n  cwd: \"../other-repo\",\n\n  // Branch strategy — controls how the agent's changes relate to branches.\n  // Defaults to { type: \"head\" } for bind-mount and { type: \"merge-to-head\" } for isolated providers.\n  branchStrategy: { type: \"branch\", branch: \"agent/fix-42\" },\n\n  // Prompt source — provide one of these, not both.\n  // Note: promptFile resolves against process.cwd(), NOT cwd.\n  promptFile: \".sandcastle/prompt.md\", // path to a prompt file\n  // prompt: \"Fix issue #42 in this repo\", // OR an inline prompt string\n\n  // Values substituted for {{KEY}} placeholders in the prompt.\n  promptArgs: {\n    ISSUE_NUMBER: \"42\",\n  },\n\n  // Maximum number of agent iterations to run before stopping. Default: 1\n  maxIterations: 5,\n\n  // Display name for this run, shown as a prefix in log output.\n  name: \"fix-issue-42\",\n\n  // Lifecycle hooks grouped by where they run: host or sandbox.\n  hooks: {\n    host: {\n      onWorktreeReady: [{ command: \"cp .env.example .env\" }],\n      onSandboxReady: [{ command: \"echo setup done\" }],\n    },\n    sandbox: {\n      onSandboxReady: [{ command: \"npm install\" }],\n    },\n  },\n\n  // Host-relative file paths to copy into the sandbox before the container starts.\n  // Not supported with branchStrategy: { type: \"head\" }.\n  copyToWorktree: [\".env\"],\n\n  // Override default timeouts for built-in lifecycle steps.\n  // Unset keys keep their defaults.\n  timeouts: {\n    copyToWorktreeMs: 120_000, // default: 60_000\n    gitSetupMs: 30_000, // default: 10_000\n    commitCollectionMs: 60_000, // default: 30_000\n    mergeToHostMs: 60_000, // default: 30_000\n  },\n\n  // How to record progress. Default: write to a file under .sandcastle/logs/\n  logging: {\n    type: \"file\",\n    path: \".sandcastle/logs/my-run.log\",\n    // Optional: forward the agent's output stream to your own observability system.\n    // Fires for each text chunk, tool call, and raw stdout line the agent\n    // produces. Errors thrown by the callback are swallowed so a broken\n    // forwarder cannot kill the run.\n    onAgentStreamEvent: (event) => {\n      // event is { type: \"text\" | \"toolCall\" | \"raw\", iteration, timestamp, ... }\n      myLogger.info(event);\n    },\n    // Optional: append every raw stdout line the agent emits to the same\n    // log file, interleaved with the human-readable output. Includes lines\n    // the provider's stream parser would otherwise drop. Intended for\n    // debugging stuck or unexpected agent behaviour.\n    verbose: true,\n  },\n  // logging: { type: \"stdout\", verbose: true }, // OR terminal mode (verbose: raw lines to stdout)\n\n  // String (or array of strings) the agent emits to end the iteration loop early.\n  // Default: \"<promise>COMPLETE</promise>\"\n  completionSignal: \"<promise>COMPLETE</promise>\",\n\n  // Idle timeout in seconds — resets whenever the agent produces output. Default: 600 (10 minutes)\n  idleTimeoutSeconds: 600,\n\n  // Grace window in seconds after the agent emits a completion signal but\n  // before its process has exited (a \"hanging process\" — typically a spawned\n  // `gh`/git child or MCP server keeping stdout open). Resets on every\n  // subsequent output line so trailing data is still captured. Default: 60\n  completionTimeoutSeconds: 60,\n\n  // Structured output — extract a typed payload from the agent's stdout.\n  // Requires maxIterations === 1 and the tag must appear in the prompt.\n  // output: Output.object({ tag: \"result\", schema: z.object({ answer: z.number() }) }),\n  // output: Output.string({ tag: \"summary\" }),\n});\n\nconsole.log(result.iterations.length); // number of iterations executed\nconsole.log(result.completionSignal); // matched signal string, or undefined if none fired\nconsole.log(result.commits); // array of { sha } for commits created\nconsole.log(result.branch); // target branch name\n```\n\n### `createSandbox()` — reusable sandbox\n\nUse `createSandbox()` when you need to run multiple agents (or multiple rounds of the same agent) inside a single sandbox. It creates the sandbox once, and you call `sandbox.run()` as many times as you need. This avoids repeated container startup costs and keeps all runs on the same branch.\n\nUse `run()` instead when you only need a single one-shot invocation — it handles sandbox lifecycle automatically.\n\n#### Basic single-run usage\n\n```typescript\nimport { createSandbox, claudeCode } from \"@chenshaohui6988/sandcastle\";\nimport { docker } from \"@chenshaohui6988/sandcastle/sandboxes/docker\";\n\nawait using sandbox = await createSandbox({\n  branch: \"agent/fix-42\",\n  sandbox: docker(),\n});\n\nconst result = await sandbox.run({\n  agent: claudeCode(\"claude-opus-4-8\"),\n  prompt: \"Fix issue #42 in this repo.\",\n});\n\nconsole.log(result.commits); // [{ sha: \"abc123\" }]\n```\n\n#### Multi-run implement-then-review\n\n```typescript\nimport { createSandbox, claudeCode } from \"@chenshaohui6988/sandcastle\";\nimport { docker } from \"@chenshaohui6988/sandcastle/sandboxes/docker\";\n\nawait using sandbox = await createSandbox({\n  branch: \"agent/fix-42\",\n  sandbox: docker(),\n  hooks: { sandbox: { onSandboxReady: [{ command: \"npm install\" }] } },\n});\n\n// Step 1: implement\nconst implResult = await sandbox.run({\n  agent: claudeCode(\"claude-opus-4-8\"),\n  promptFile: \".sandcastle/implement.md\",\n  maxIterations: 5,\n});\n\n// Step 2: review on the same branch, same container\nconst reviewResult = await sandbox.run({\n  agent: claudeCode(\"claude-sonnet-4-6\"),\n  prompt: \"Review the changes and fix any issues.\",\n});\n```\n\nCommits from all `run()` calls accumulate on the same branch. The sandbox container stays alive between runs, so installed dependencies and build artifacts persist.\n\n`sandbox.exec()` lets the harness run shell commands directly in the same warm sandbox — handy for gating an implement step on a quick verification before kicking off the review:\n\n```typescript\nawait using sandbox = await createSandbox({\n  branch: \"agent/fix-42\",\n  sandbox: docker(),\n  hooks: { sandbox: { onSandboxReady: [{ command: \"npm install\" }] } },\n});\n\nawait sandbox.run({\n  agent: claudeCode(\"claude-opus-4-8\"),\n  promptFile: \".sandcastle/implement.md\",\n  maxIterations: 5,\n});\n\n// Verify before review — non-zero exitCode is returned, not thrown.\nconst tests = await sandbox.exec(\"npm test\");\nif (tests.exitCode !== 0) {\n  throw new Error(`Tests failed:\\n${tests.stdout}\\n${tests.stderr}`);\n}\n\nawait sandbox.run({\n  agent: claudeCode(\"claude-sonnet-4-6\"),\n  prompt: \"Review the changes and fix any issues.\",\n});\n```\n\n`cwd` defaults to the sandbox repo path, matching `interactive()`. Pass `cwd` to override.\n\n#### Automatic cleanup with `await using`\n\n`await using` calls `sandbox.close()` automatically when the block exits. If the sandbox has uncommitted changes, the worktree is preserved on disk; if clean, both container and worktree are removed.\n\n#### Manual `close()` with `CloseResult`\n\n```typescript\nconst sandbox = await createSandbox({\n  branch: \"agent/fix-42\",\n  sandbox: docker(),\n});\n// ... run agents ...\nconst closeResult = await sandbox.close();\nif (closeResult.preservedWorktreePath) {\n  console.log(`Worktree preserved at ${closeResult.preservedWorktreePath}`);\n}\n```\n\n#### `CreateSandboxOptions`\n\n| Option           | Type            | Default         | Description                                                                                                         |\n| ---------------- | --------------- | --------------- | ------------------------------------------------------------------------------------------------------------------- |\n| `branch`         | string          | —               | **Required.** Explicit branch for the sandbox                                                                       |\n| `sandbox`        | SandboxProvider | —               | **Required.** Sandbox provider (e.g. `docker()`, `podman()`)                                                        |\n| `cwd`            | string          | `process.cwd()` | Host repo directory — relative paths resolve against `process.cwd()`                                                |\n| `hooks`          | SandboxHooks    | —               | Lifecycle hooks (`host.*`, `sandbox.*`) — run once at creation time                                                 |\n| `copyToWorktree` | string[]        | —               | Host-relative file paths to copy into the sandbox at creation time                                                  |\n| `timeouts`       | Timeouts        | —               | Override built-in lifecycle step timeouts (`copyToWorktreeMs`, `gitSetupMs`, `commitCollectionMs`, `mergeToHostMs`) |\n\n#### `Sandbox`\n\n| Property / Method       | Type                                                                     | Description                                                                                                               |\n| ----------------------- | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------- |\n| `branch`                | string                                                                   | The branch the sandbox is on                                                                                              |\n| `worktreePath`          | string                                                                   | Host path to the worktree                                                                                                 |\n| `run(options)`          | `(SandboxRunOptions) => Promise<SandboxRunResult>`                       | Invoke an agent inside the existing sandbox                                                                               |\n| `interactive(options)`  | `(SandboxInteractiveOptions) => Promise<SandboxInteractiveResult>`       | Launch an interactive session in the sandbox                                                                              |\n| `exec(cmd, options?)`   | `(command: string, options?: SandboxExecOptions) => Promise<ExecResult>` | Run a shell command in the sandbox. `cwd` defaults to the sandbox repo path. Non-zero `exitCode` is returned, not thrown. |\n| `close()`               | `() => Promise<CloseResult>`                                             | Tear down the container and sandbox                                                                                       |\n| `[Symbol.asyncDispose]` | `() => Promise<void>`                                                    | Auto teardown via `await using`                                                                                           |\n\n#### `SandboxRunOptions`\n\n| Option                     | Type               | Default                       | Description                                                                                                                          |\n| -------------------------- | ------------------ | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |\n| `agent`                    | AgentProvider      | —                             | **Required.** Agent provider (e.g. `claudeCode(\"claude-opus-4-8\")`)                                                                  |\n| `prompt`                   | string             | —                             | Inline prompt (mutually exclusive with `promptFile`)                                                                                 |\n| `promptFile`               | string             | —                             | Path to prompt file (mutually exclusive with `prompt`)                                                                               |\n| `promptArgs`               | PromptArgs         | —                             | Key-value map for `{{KEY}}` placeholder substitution                                                                                 |\n| `maxIterations`            | number             | `1`                           | Maximum iterations to run                                                                                                            |\n| `completionSignal`         | string \\| string[] | `<promise>COMPLETE</promise>` | String(s) the agent emits to stop the iteration loop early                                                                           |\n| `idleTimeoutSeconds`       | number             | `600`                         | Idle timeout in seconds — resets on each agent output event                                                                          |\n| `completionTimeoutSeconds` | number             | `60`                          | Grace window after the completion signal is seen but the agent process hasn't exited                                                 |\n| `name`                     | string             | —                             | Display name for the run                                                                                                             |\n| `logging`                  | object             | file (auto-generated)         | `{ type: 'file', path }` or `{ type: 'stdout' }`                                                                                     |\n| `resumeSession`            | string             | —                             | Resume a prior session by ID for agents that support resume. Incompatible with `maxIterations > 1`. Session file must exist on host. |\n| `signal`                   | AbortSignal        | —                             | Cancels the run when aborted; handle stays usable afterward                                                                          |\n\n#### `SandboxRunResult`\n\n| Field                      | Type                                                                                     | Description                                                                                                                         |\n| -------------------------- | ---------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |\n| `iterations`               | `IterationResult[]`                                                                      | Per-iteration results (use `.length` for the count)                                                                                 |\n| `completionSignal`         | string?                                                                                  | The matched completion signal string, or `undefined` if none fired                                                                  |\n| `stdout`                   | string                                                                                   | Combined agent output from all iterations                                                                                           |\n| `commits`                  | `{ sha }[]`                                                                              | Commits created during the run                                                                                                      |\n| `logFilePath`              | string?                                                                                  | Path to the log file (only when logging to a file)                                                                                  |\n| `resume(prompt, options?)` | `(prompt: string, options?: ResumeSandboxRunResultOptions) => Promise<SandboxRunResult>` | Continue the captured session for one iteration inside the same warm sandbox. Present only when the provider captured a session id. |\n| `fork(prompt, options?)`   | `(prompt: string, options?: ResumeSandboxRunResultOptions) => Promise<SandboxRunResult>` | Fork the captured session for one iteration inside the same warm sandbox. The parent session is left intact (ADR 0018).             |\n\n#### `CloseResult`\n\n| Field                   | Type    | Description                                                              |\n| ----------------------- | ------- | ------------------------------------------------------------------------ |\n| `preservedWorktreePath` | string? | Host path to the preserved worktree, set when it had uncommitted changes |\n\n### `createWorktree()` — independent worktree lifecycle\n\nUse `createWorktree()` when you need a worktree (git worktree) as an independent, first-class concept — separate from any sandbox. This is useful when you want to run an interactive session first and then hand the same worktree to a sandboxed AFK agent.\n\nOnly `branch` and `merge-to-head` strategies are accepted; `head` is a compile-time type error since it means no worktree.\n\nPass `cwd` to target a repo other than `process.cwd()`. Relative paths resolve against `process.cwd()`; absolute paths pass through. A `CwdError` is thrown if the path does not exist or is not a directory.\n\n```typescript\nimport { createWorktree } from \"@chenshaohui6988/sandcastle\";\n\nawait using wt = await createWorktree({\n  branchStrategy: { type: \"branch\", branch: \"agent/fix-42\" },\n  copyToWorktree: [\"node_modules\"],\n  cwd: \"/path/to/other-repo\", // optional — defaults to process.cwd()\n});\n\nconsole.log(wt.worktreePath); // host path to the worktree\nconsole.log(wt.branch); // \"agent/fix-42\"\n\n// Run an interactive session in the worktree (defaults to noSandbox)\nawait wt.interactive({\n  agent: claudeCode(\"claude-opus-4-8\"),\n  prompt: \"Explore the codebase and understand the bug.\",\n});\n\n// Run an AFK agent in the worktree (sandbox is required)\nconst result = await wt.run({\n  agent: claudeCode(\"claude-opus-4-8\"),\n  sandbox: docker({ imageName: \"sandcastle:myrepo\" }),\n  prompt: \"Fix issue #42.\",\n  maxIterations: 3,\n});\nconsole.log(result.commits); // commits made during the run\n\n// Create a long-lived sandbox from the worktree\nimport { docker } from \"@chenshaohui6988/sandcastle/sandboxes/docker\";\n\nawait using sandbox = await wt.createSandbox({\n  sandbox: docker(),\n  hooks: { sandbox: { onSandboxReady: [{ command: \"npm install\" }] } },\n});\n\n// sandbox.close() tears down the container only — the worktree stays\nawait sandbox.close();\n\n// wt.close() cleans up the worktree\n```\n\n`wt.close()` checks for uncommitted changes: if the worktree is dirty, it's preserved on disk; if clean, it's removed. `await using` calls `close()` automatically. The worktree persists after `run()`, `interactive()`, and `createSandbox()` complete, so you can hand it to another agent or inspect it.\n\nWith `branchStrategy: { type: \"merge-to-head\" }`, each `wt.run()` / `wt.interactive()` merges the agent's commits back to the host's current branch before returning, and the worktree's source branch is preserved across calls so subsequent ones can reuse the same handle. (This differs from top-level `run()`, where the temp branch is deleted after the merge.)\n\n**Split ownership**: When a sandbox is created via `wt.createSandbox()`, `sandbox.close()` tears down the container only — the worktree remains. `wt.close()` is responsible for worktree cleanup. This differs from the top-level `createSandbox()`, where `sandbox.close()` owns both container and worktree.\n\n#### `CreateWorktreeOptions`\n\n| Option           | Type                   | Default | Description                                                                                                         |\n| ---------------- | ---------------------- | ------- | ------------------------------------------------------------------------------------------------------------------- |\n| `branchStrategy` | WorktreeBranchStrategy | —       | **Required.** `{ type: \"branch\", branch }` or `{ type: \"merge-to-head\" }`                                           |\n| `copyToWorktree` | string[]               | —       | Host-relative file paths to copy into the worktree at creation time                                                 |\n| `timeouts`       | Timeouts               | —       | Override built-in lifecycle step timeouts (`copyToWorktreeMs`, `gitSetupMs`, `commitCollectionMs`, `mergeToHostMs`) |\n\n#### `Worktree`\n\n| Property / Method        | Type                                                                  | Description                                         |\n| ------------------------ | --------------------------------------------------------------------- | --------------------------------------------------- |\n| `branch`                 | string                                                                | The branch the worktree is on                       |\n| `worktreePath`           | string                                                                | Host path to the worktree                           |\n| `run(options)`           | `(options: WorktreeRunOptions) => Promise<WorktreeRunResult>`         | Run an AFK agent in the worktree (sandbox required) |\n| `interactive(options)`   | `(options: WorktreeInteractiveOptions) => Promise<InteractiveResult>` | Run an interactive agent session in the worktree    |\n| `createSandbox(options)` | `(options: WorktreeCreateSandboxOptions) => Promise<Sandbox>`         | Create a long-lived sandbox backed by this worktree |\n| `close()`                | `() => Promise<CloseResult>`                                          | Clean up the worktree (preserves if dirty)          |\n| `[Symbol.asyncDispose]`  | `() => Promise<void>`                                                 | Auto cleanup via `await using`                      |\n\n#### `WorktreeInteractiveOptions`\n\n| Option       | Type                   | Default       | Description                                                                                       |\n| ------------ | ---------------------- | ------------- | ------------------------------------------------------------------------------------------------- |\n| `agent`      | AgentProvider          | —             | **Required.** Agent provider                                                                      |\n| `sandbox`    | AnySandboxProvider     | `noSandbox()` | Sandbox provider (defaults to no sandbox)                                                         |\n| `prompt`     | string                 | —             | Inline prompt (mutually exclusive with `promptFile`)                                              |\n| `promptFile` | string                 | —             | Path to prompt file                                                                               |\n| `name`       | string                 | —             | Optional session name                                                                             |\n| `hooks`      | SandboxHooks           | —             | Lifecycle hooks (`host.*`, `sandbox.*`)                                                           |\n| `promptArgs` | PromptArgs             | —             | Key-value map for `{{KEY}}` placeholder substitution                                              |\n| `env`        | Record<string, string> | —             | Environment variables to inject into the sandbox                                                  |\n| `signal`     | AbortSignal            | —             | Cancel the session when aborted. The worktree is preserved on disk. Rejects with `signal.reason`. |\n\n#### `WorktreeRunOptions`\n\n| Option                     | Type                   | Default | Description                                                                                                                          |\n| -------------------------- | ---------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------ |\n| `agent`                    | AgentProvider          | —       | **Required.** Agent provider                                                                                                         |\n| `sandbox`                  | SandboxProvider        | —       | **Required.** Sandbox provider (AFK agents must be sandboxed)                                                                        |\n| `prompt`                   | string                 | —       | Inline prompt (mutually exclusive with `promptFile`)                                                                                 |\n| `promptFile`               | string                 | —       | Path to prompt file                                                                                                                  |\n| `maxIterations`            | number                 | 1       | Maximum iterations to run                                                                                                            |\n| `completionSignal`         | string \\| string[]     | —       | Substring(s) to stop the iteration loop early                                                                                        |\n| `idleTimeoutSeconds`       | number                 | 600     | Idle timeout in seconds                                                                                                              |\n| `completionTimeoutSeconds` | number                 | 60      | Grace window after completion signal is seen but agent process hasn't exited                                                         |\n| `name`                     | string                 | —       | Optional run name                                                                                                                    |\n| `logging`                  | LoggingOption          | file    | Logging mode                                                                                                                         |\n| `hooks`                    | SandboxHooks           | —       | Lifecycle hooks (`host.*`, `sandbox.*`)                                                                                              |\n| `promptArgs`               | PromptArgs             | —       | Key-value map for `{{KEY}}` placeholder substitution                                                                                 |\n| `env`                      | Record<string, string> | —       | Environment variables to inject into the sandbox                                                                                     |\n| `resumeSession`            | string                 | —       | Resume a prior session by ID for agents that support resume. Incompatible with `maxIterations > 1`. Session file must exist on host. |\n| `signal`                   | AbortSignal            | —       | Cancel the run when aborted. Kills the in-flight agent subprocess; the worktree is preserved on disk. Rejects with `signal.reason`.  |\n\n#### `WorktreeRunResult`\n\n| Property           | Type                | Description                                            |\n| ------------------ | ------------------- | ------------------------------------------------------ |\n| `iterations`       | `IterationResult[]` | Per-iteration results (use `.length` for the count)    |\n| `completionSignal` | string              | The matched completion signal, or undefined            |\n| `stdout`           | string              | Combined stdout output from all agent iterations       |\n| `commits`          | { sha: string }[]   | List of commits made by the agent during the run       |\n| `branch`           | string              | The branch name the agent worked on                    |\n| `logFilePath`      | string              | Path to the log file, if logging was drained to a file |\n\n#### `WorktreeCreateSandboxOptions`\n\n| Option           | Type            | Default | Description                                                                                                         |\n| ---------------- | --------------- | ------- | ------------------------------------------------------------------------------------------------------------------- |\n| `sandbox`        | SandboxProvider | —       | **Required.** Sandbox provider (e.g. `docker()`)                                                                    |\n| `hooks`          | SandboxHooks    | —       | Lifecycle hooks (`host.*`, `sandbox.*`)                                                                             |\n| `copyToWorktree` | string[]        | —       | Host-relative file paths to copy into the worktree at creation time                                                 |\n| `timeouts`       | Timeouts        | —       | Override built-in lifecycle step timeouts (`copyToWorktreeMs`, `gitSetupMs`, `commitCollectionMs`, `mergeToHostMs`) |\n\n## How it works\n\nSandcastle uses a **branch strategy** configured on the sandbox provider to control how the agent's changes relate to branches. There are three strategies:\n\n- **Head** (`{ type: \"head\" }`) — The agent writes directly to the host working directory. No worktree, no branch indirection. This is the default for bind-mount providers like `docker()`.\n- **Merge-to-head** (`{ type: \"merge-to-head\" }`) — Sandcastle creates a temporary branch in a git worktree. The agent works on the temp branch, and changes are merged back to HEAD when done. The temp branch is cleaned up after merge.\n- **Branch** (`{ type: \"branch\", branch: \"foo\" }`) — Commits land on an explicitly named branch in a git worktree. Re-running with the same branch reuses the existing worktree and fast-forwards it from `origin` when safe — see [ADR 0003](docs/adr/0003-reuse-worktree-by-default.md).\n\nFor bind-mount providers (like Docker), the worktree directory is bind-mounted into the container — the agent writes directly to the host filesystem through the mount, so no sync is needed.\n\nFrom your point of view, you just configure `branchStrategy: { type: 'branch', branch: 'foo' }` on `run()`, and get a commit on branch `foo` once it's complete. All 100% local.\n\n## Prompts\n\nSandcastle uses a flexible prompt system. You write the prompt, and the engine executes it — no opinions about workflow, task management, or context sources are imposed.\n\n### Prompt resolution\n\nYou must provide exactly one of:\n\n1. `prompt: \"inline string\"` — pass an inline prompt directly via `RunOptions`\n2. `promptFile: \"./path/to/prompt.md\"` — point to a specific file via `RunOptions`\n\n`prompt` and `promptFile` are mutually exclusive — providing both is an error. If neither is provided, `run()` throws an error asking you to supply one.\n\n**Inline prompts (`prompt: \"...\"`) are passed to the agent literally.** No `{{KEY}}` substitution, no `` !`command` `` expansion, no built-in `{{SOURCE_BRANCH}}` / `{{TARGET_BRANCH}}` injection. If you need values interpolated into an inline prompt, build the string in JavaScript (`` `Work on ${branch}…` ``). Passing `promptArgs` alongside an inline prompt is an error — switch to `promptFile` to use substitution.\n\nThe substitution and expansion features below apply **only** to prompts sourced from `promptFile`.\n\n> **Convention**: `sandcastle init` scaffolds `.sandcastle/prompt.md` and all templates explicitly reference it via `promptFile: \".sandcastle/prompt.md\"`. This is a convention, not an automatic fallback — Sandcastle does not read `.sandcastle/prompt.md` unless you pass it as `promptFile`.\n\n### Dynamic context with `` !`command` ``\n\nUse `` !`command` `` expressions in your prompt to pull in dynamic context. Each expression is replaced with the command's stdout before the prompt is sent to the agent. All expressions in a prompt run **in parallel** for faster expansion.\n\nCommands run **inside the sandbox** after `sandbox.onSandboxReady` hooks complete, so they see the same repo state the agent sees (including installed dependencies).\n\n```markdown\n# Open issues\n\n!`gh issue list --state open --label Sandcastle --json number,title,body,comments,labels --limit 100`\n\n# Recent commits\n\n!`git log --oneline -10`\n```\n\nIf any command exits with a non-zero code, the run fails immediately with an error.\n\n### Prompt arguments with `{{KEY}}`\n\nUse `{{KEY}}` placeholders in your prompt to inject values from the `promptArgs` option. This is useful for reusing the same prompt file across multiple runs with different parameters.\n\n```typescript\nimport { run } from \"@chenshaohui6988/sandcastle\";\n\nawait run({\n  promptFile: \"./my-prompt.md\",\n  promptArgs: { ISSUE_NUMBER: 42, PRIORITY: \"high\" },\n});\n```\n\nIn the prompt file:\n\n```markdown\nWork on issue #{{ISSUE_NUMBER}} (priority: {{PRIORITY}}).\n```\n\nPrompt argument substitution runs on the host before shell expression expansion, so `{{KEY}}` placeholders inside `` !`command` `` expressions are replaced first:\n\n```markdown\n!`gh issue view {{ISSUE_NUMBER}} --json body -q .body`\n```\n\nA `{{KEY}}` placeholder with no matching prompt argument is an error. Unused prompt arguments produce a warning.\n\n`` !`command` `` expansion only runs on shell blocks written in the prompt file itself. Any `` !`…` `` pattern that appears inside an argument value is treated as inert text — it won't be executed against the host shell. This makes it safe to pass user-authored content (issue titles, PR descriptions, docs excerpts) through `promptArgs`.\n\n### Built-in prompt arguments\n\nSandcastle automatically injects two built-in prompt arguments into every prompt:\n\n| Placeholder         | Value                                                             |\n| ------------------- | ----------------------------------------------------------------- |\n| `{{SOURCE_BRANCH}}` | The branch the agent works on (determined by the branch strategy) |\n| `{{TARGET_BRANCH}}` | The host's active branch at `run()` time                          |\n\nUse them in your prompt without passing them via `promptArgs`:\n\n```markdown\nYou are working on {{SOURCE_BRANCH}}. When diffing, compare against {{TARGET_BRANCH}}.\n```\n\nPassing `SOURCE_BRANCH` or `TARGET_BRANCH` in `promptArgs` is an error — built-in prompt arguments cannot be overridden.\n\n### Early termination with `<promise>COMPLETE</promise>`\n\nWhen the agent outputs `<promise>COMPLETE</promise>`, the orchestrator stops the iteration loop early. This is a convention you document in your prompt for the agent to follow — the engine never injects it.\n\nThis is useful for task-based workflows where the agent should stop once it has finished, rather than running all remaining iterations.\n\nYou can override the default signal by passing `completionSignal` to `run()`. It accepts a single string or an array of strings:\n\n```ts\nawait run({\n  // ...\n  completionSignal: \"DONE\",\n});\n\n// Or pass multiple signals — the loop stops on the first match:\nawait run({\n  // ...\n  completionSignal: [\"TASK_COMPLETE\", \"TASK_ABORTED\"],\n});\n```\n\nTell the agent to output your chosen string(s) in the prompt, and the orchestrator will stop when it detects any of them. The matched signal is returned as `result.completionSignal`.\n\n#### Hanging processes after the completion signal\n\nThe agent process is expected to exit shortly after emitting the completion signal. When a child it spawned — a `gh`/git subprocess, a long-lived MCP server, etc. — inherits the agent's stdout pipe and keeps it open, the parent process can linger long past its logical end. Sandcastle would otherwise wait for the full `idleTimeoutSeconds` and fail with `AgentIdleTimeoutError`, throwing away the commits the agent already made.\n\nInstead, once the completion signal is observed in the output buffer, Sandcastle swaps in a short **completion timeout** (default 60 s). When it expires, the run resolves successfully with a warning that the process was hanging; `result.commits` and `result.completionSignal` are populated as if the process had exited cleanly. The timer resets on every subsequent output line, so trailing data emitted after the signal — token-usage events, terminal `result` events, a structured-output `<tag>` — is still captured.\n\nA clean process exit always wins the race, so healthy runs gain zero added latency. The completion timeout only matters when the process hangs.\n\nTune the window with `completionTimeoutSeconds`:\n\n```ts\nawait run({\n  // ...\n  completionTimeoutSeconds: 30, // shorter grace window\n});\n```\n\nThis is independent of `idleTimeoutSeconds`. They cover different phases: `idleTimeoutSeconds` runs **before** any signal is seen (genuinely stuck agent → fail); `completionTimeoutSeconds` runs **after** the signal is seen (hanging process → succeed with warning). See [ADR 0019](docs/adr/0019-completion-timeout-for-hanging-process.md).\n\n### Structured output\n\nUse `Output.object()` to extract a typed, schema-validated JSON payload from the agent's stdout. The agent emits its answer inside an XML tag you specify, and Sandcastle parses, validates, and returns it on `result.output`. The schema can be any [Standard Schema](https://standardschema.dev) validator — the examples below use [Zod](https://zod.dev), but Valibot, ArkType, and others work identically. See [ADR 0010](docs/adr/0010-structured-output.md) for design rationale.\n\n```ts\nimport { run, Output, claudeCode } from \"@chenshaohui6988/sandcastle\";\nimport { docker } from \"@chenshaohui6988/sandcastle/sandboxes/docker\";\nimport { z } from \"zod\";\n\nconst result = await run({\n  agent: claudeCode(\"claude-opus-4-8\"),\n  sandbox: docker(),\n  prompt: `Analyze the code, and output the result as JSON inside <result> tags.\n    The result must match this schema:\n    { summary: string; score: string }\n  `,\n  output: Output.object({\n    tag: \"result\",\n    schema: z.object({ summary: z.string(), score: z.number() }),\n  }),\n});\n\nconsole.log(result.output.summary); // typed as string\nconsole.log(result.output.score); // typed as number\n```\n\n`Output.string({ tag })` extracts the tag contents as a plain string (trimmed, no JSON parsing). Both helpers require `maxIterations` to be `1` (the default). The resolved prompt must contain the configured opening tag literal.\n\nWhen extraction or validation fails, `run()` throws a `StructuredOutputError`. Alongside `tag`, `rawMatched`, `cause`, `commits`, `branch`, and `preservedWorktreePath`, the error carries the `sessionId` (and `sessionFilePath`, when the session was captured) of the run that produced the bad output.\n\nPass `maxRetries` to have Sandcastle handle the retry loop for you. Each retry resumes the same agent session and feeds back a token-efficient description of the error, so the agent can re-emit a corrected tag without redoing the work. Retries require an agent provider that supports session resumption (`claudeCode`, `codex`, `pi`) — calling `run()` with `maxRetries > 0` against a non-resumable provider (`cursor`, `opencode`, `copilot`) throws immediately.\n\n```ts\nconst result = await run({\n  agent: claudeCode(\"claude-opus-4-8\"),\n  sandbox: docker(),\n  prompt: \"Analyze the code and emit JSON inside <result> tags.\",\n  output: Output.object({\n    tag: \"result\",\n    schema: z.object({ summary: z.string(), score: z.number() }),\n    maxRetries: 2, // 2 retries on top of the initial attempt\n  }),\n});\n```\n\nIf you need to drive the retry loop manually — for example, to customise the feedback prompt or rotate models on each attempt — leave `maxRetries` at its default of `0` and resume the failed session yourself:\n\n```ts\nimport {\n  run,\n  Output,\n  StructuredOutputError,\n} from \"@chenshaohui6988/sandcastle\";\n\ntry {\n  return await run({ ...opts, output });\n} catch (e) {\n  if (e instanceof StructuredOutputError && e.sessionId) {\n    return await run({\n      ...opts,\n      output,\n      resumeSession: e.sessionId,\n      prompt: `Your previous output failed: ${e.message}. Re-emit it inside <${e.tag}> tags.`,\n    });\n  }\n  throw e;\n}\n```\n\n### Templates\n\n`sandcastle init` prompts you to choose a sandbox provider (Docker, Podman, or no-sandbox), an issue tracker (GitHub Issues, Beads, or Custom), and a template, which scaffolds a ready-to-use prompt and `main.mts` suited to a specific workflow. If your project's `package.json` has `\"type\": \"module\"`, the file will be named `main.ts` instead. Choosing **Custom** scaffolds the project in a deliberately broken-until-configured state plus a `.sandcastle/SETUP_ISSUE_TRACKER.md` prompt you feed to your coding agent, which wires up your own tracker by editing the scaffolded files in place. Five templates are available:\n\n| Template                       | Description                                                               |\n| ------------------------------ | ------------------------------------------------------------------------- |\n| `blank`                        | Bare scaffold — write your own prompt and orchestration                   |\n| `simple-loop`                  | Picks issues one by one and closes them                                   |\n| `sequential-reviewer`          | Implements issues one by one, with a code review step after each          |\n| `parallel-planner`             | Plans parallelizable issues, executes on separate branches, then merges   |\n| `parallel-planner-with-review` | Plans parallelizable issues, executes with per-branch review, then merges |\n\nSelect a template during `sandcastle init` when prompted, or re-run init in a fresh repo to try a different one.\n\n## CLI commands\n\n### `sandcastle init`\n\nScaffolds the `.sandcastle/` config directory. This is the first command you run in a new repo. You choose a sandbox provider during init: Docker writes a `Dockerfile`, Podman writes a `Containerfile`, and no-sandbox writes no container file because the agent runs directly on the host. Init also writes a default single-repository `.sandcastle/workspace.json`, so `sandcastle workspace plan/run` has a starter candidate workspace without hand-authoring the config first. Init also writes `.sandcastle/SKILL_ROUTER.md`, a companion guide that tells agents how to choose the right skill flow and when to update `AGENTS.md` or `CLAUDE.md` before starting project work. Image build prompts are skipped when no-sandbox is selected.\n\nInit detects your host package manager (npm, pnpm, yarn, or bun) from a `packageManager` field or lockfile, defaulting to npm. Templates whose `main` file imports a host dependency — the planner templates import [Zod](https://zod.dev) for their `<plan>` output","readmeFilename":"README.md"}