@pleach/sandbox
Vendor-neutral SandboxProvider contract plus four endpoint-shape adapters that ship inside the package — the seam @pleach/coding-agent reads.
@pleach/sandbox is the contract layer between @pleach/core
runtimes and whatever process isolation a host chooses to ship —
a Docker container, a Firecracker microVM, an E2B or Daytona
sandbox, an in-process fixture. It ships the SandboxProvider
interface plus an in-memory fixture, and four adapters that ship
inside the package — keyed by the shape of the backing endpoint
(HTTP-stream, HTTP-poll, child-process, AWS Fargate), not by vendor
name. @pleach/coding-agent is the canonical consumer — its
file-read, file-write, and shell tools all dispatch through the
provider this package defines.
What it provides
- The
SandboxProvidercontract a host implements once and reuses across every sandboxed tool — read, write, list, exec — per the four-tool sketch incoding-agent.mdx. - An in-memory fixture suitable for tests and replay runs where the host hasn't wired a real backing process.
- The canonical name (
SandboxProvider) plus the legacySandboxAdapterretained as a@deprecatedalias, per the status row inpackages.mdx. - The peer-dep anchor
@pleach/coding-agentdeclares at^0.1.0(see Coding agent for the locked decisions).
Where it fits
@pleach/sandbox is the seam between the runtime and the
sandboxed tool surface — the low-level SandboxProvider contract
(execute, readFile, writeFile, listFiles, plus
acquire / release / capabilities). There is no ctx.sandbox:
core's ToolContext is sandbox-agnostic and carries only
toolCallId + signal?. Instead the host closes over a sandbox
handle when it constructs the tools; @pleach/coding-agent ships a
thin SandboxClient facade (exec, readFile, writeFile) built
over the low-level provider, and the tool handlers call that — see
Coding agent. The
direction lock keeps @pleach/core itself sandbox-agnostic:
consumers reach for @pleach/sandbox directly, and the coding-agent
SKU composes on top of both.
The SandboxProvider contract
A host implements this interface once, against Docker, Firecracker,
E2B, Daytona, or its own runner, and every sandboxed tool reuses it.
Each I/O method is capability-gated — capabilities() drives graceful
degradation when a backing process doesn't support, say, network
egress.
interface SandboxProvider {
readonly type: SandboxProviderType;
acquire(sessionId: string, options?: AcquireOptions): Promise<SandboxHandle>;
execute(handle: SandboxHandle, command: SandboxCommand): Promise<SandboxExecResult>;
readFile(handle: SandboxHandle, path: string): Promise<string>;
writeFile(handle: SandboxHandle, path: string, content: string): Promise<void>;
listFiles(handle: SandboxHandle, path: string): Promise<readonly FileEntry[]>;
release(handle: SandboxHandle): Promise<void>;
isAlive(handle: SandboxHandle): Promise<boolean>; // runtime heartbeat
capabilities(): SandboxCapabilities;
}acquire is idempotent on (sessionId × chatId), so a re-entered
session reuses its sandbox rather than spawning a second one. An
optional streaming execute variant yields SandboxExecChunk events
for long-running commands. The exact option shapes
(AcquireOptions, SandboxCommand, SandboxCapabilities) are on the
npm README — see below.
Install
npm install @pleach/sandboxEndpoint-shape adapters
Four adapters ship inside @pleach/sandbox, each implementing
SandboxProvider against a different endpoint shape. The three
HTTP/child-process adapters carry their own subpaths (so you pull only
the one you wire); all four are also re-exported from the package root.
| Adapter | Import | Backing shape |
|---|---|---|
createHttpStreamSandboxProvider | @pleach/sandbox/adapters/httpStream | HTTP service with streaming responses (baseURL + auth) |
createHttpPollSandboxProvider | @pleach/sandbox/adapters/httpPoll | HTTP service you poll for completion (baseURL + auth) |
createChildProcessSandboxProvider | @pleach/sandbox/adapters/childProcess | local child process (workspaceDir, shell) |
createFargateSandboxProvider | @pleach/sandbox/adapters/awsFargate | AWS ECS/Fargate task (region, cluster, taskDefinition, subnets). Also re-exported from the root barrel. |
Vercel Sandbox, Daytona, or E2B slot into whichever shape they present
— an HTTP-streaming service uses createHttpStreamSandboxProvider; you
don't need a per-vendor package. For tests, createInMemorySandboxProvider
ships at @pleach/sandbox/testing.
import { createChildProcessSandboxProvider } from "@pleach/sandbox/adapters/childProcess"
const provider = createChildProcessSandboxProvider({ workspaceDir: "/srv/agent-scratch" })Sandboxed code runner
createSandboxedCodeRunner (at @pleach/sandbox/adapters/codeRunner) is the
reference runner for the code_exec base tool. It returns a function that
satisfies core's CodeRunner contract and runs every cell, in Python, bash or
sh, under one of three backends:
| Backend | Platform | What a cell gets |
|---|---|---|
container | Docker or Podman | No network, a read-only root, a tmpfs workdir, all capabilities dropped, a non-root user, no-new-privileges, and process, memory and CPU limits. The image must be digest-pinned and already pulled. |
bwrap | Linux, with bubblewrap installed | Every namespace unshared (no network, its own pid namespace), a read-only system view, the workdir at /workspace, uid 65534, and /tmp and /workspace capped at limits.fileSizeMb. An in-cell seccomp filter denies nested user namespaces, ptrace, bpf, perf, the kernel keyring, io_uring and the mount API. |
seatbelt | macOS | A deny-default sandbox-exec profile: no network, reads limited to system roots, the interpreter prefix and the workdir, writes limited to the workdir. |
Every backend gives the cell its own working directory as cwd and HOME, an
environment built from an allowlist (nothing is copied from process.env), a
wall-clock timeout, and the same byte cap and truncation marker on output.
Cells are torn down on every exit path.
import { createSandboxedCodeRunner } from "@pleach/sandbox/adapters/codeRunner"
const runner = createSandboxedCodeRunner({
backend: "auto",
limits: { memoryMb: 256, fileSizeMb: 32 },
workdirMode: "per-session",
})
const status = await runner.ready
if (!status.ok) throw new Error(status.reason)
const result = await runner("print(1 + 1)", { language: "python", timeoutMs: 5_000 })Selection, self-test and refusal
The factory returns at once. Backend selection and a self-test run in the
background, and every call waits for them. With backend: "auto" the runner
tries a container engine whose daemon answers, then the platform-native
sandbox. The self-test runs canaries before a backend is accepted:
- a network canary;
- a filesystem canary, where a host file outside the workdir must be unreadable;
- a secret canary, where the environment of a same-uid holder process must be
unreadable from inside the cell. The bwrap and container backends scan every
/proc/<pid>/environthe cell can open; the container backend also grades the cell's pid namespace.
On bwrap the self-test also checks that the cell cannot create a user
namespace, that ptrace is refused by the in-cell filter, that the filter is
loaded, and that the cell is pid 1 of its pid namespace.
When no backend passes, every call throws a SandboxRefusedError. The runner
never falls back to running code unsandboxed. await runner.ready resolves to
the chosen backend with its secretIsolation verdict and any warnings, or to
{ ok: false, reason }; runner.health() reports whether a failed process
reap has left the runner unhealthy (calls throw until a re-reap succeeds), and
runner.dispose() kills live cells and deletes the workdirs.
Options a host configures
limitsoverrides any ofcpuSeconds,memoryMb,pids,fileSizeMb,openFiles,outputBytes,defaultTimeoutMs,maxTimeoutMsandcpus(each has a built-in default). A non-positive or non-finite value throws, and a caller'stimeoutMsis clamped tomaxTimeoutMs. Which limits bind depends on the backend:memoryMbis--memoryon the container backend andRLIMIT_ASon bwrap, but only a sampled watchdog on macOS with no hard cap;cpusapplies to the container backend only.workdirMode: "per-cell"(default) uses a fresh directory per call."per-session"keeps one perchatId, bounded bymaxSessions(default 32). On bwrap a per-cell/workspaceis a tmpfs capped atfileSizeMb; a per-session one is a host directory that is sampled and killed past the same cap, so a fast writer can overshoot before the kill.bwrap.procchooses what a bwrap cell sees at/proc."fresh"(default) mounts a procfs for the cell's own pid namespace and, on bubblewrap 0.8.0 or later, passes--disable-userns."none"mounts an empty tmpfs and omits--disable-userns; use it inside a container whose runtime masks/procpaths (Docker's default), where the kernel refuses the fresh procfs. The seccomp filter denies nested user namespaces in both modes. Under"none"the filter is proven by theptraceprobe alone, so an outer filter that deniesptracewould also satisfy it, and the runner adds a warning saying so.container.imageandcontainer.engineselect the image (digest-pinned) and the engine;interpretersandrequirePythonVersionpin the native backends' interpreters.- The runner can pass extra non-secret environment variables to cells; names that look like secrets are refused.
What the runner does not guarantee
The macOS seatbelt backend is not secret-isolating: a cell can read the launch
environment of any same-uid process. The self-test refuses it unless you pass
allowSameUidEnvExposure: true, in which case secretIsolation reports the
exposure. The isolation above holds only for the backend that passed its
self-test on the host, and only for the conditions that self-test exercises.
The subpath also re-exports the argv and seccomp-program builders, the
BwrapProcMode type and the probe and grader helpers the self-test uses. A
host that only runs code does not need them.
API surface
The full SandboxProvider method set, per-adapter option shapes, and
the @deprecated alias surface live in the @pleach/sandbox
package README (not on npm yet). The README is the source of truth
for the contract itself; if a claim here disagrees with it, the
README wins.
Where to go next
@pleach/rbac-contract
Zero-dependency type contract for role-based access control — the RbacRuntime interface @pleach/core types its rbacRuntime? slot against, plus the plugin-hook adapter that wires it in.
@pleach/replay
The `@pleach/replay` package — ReplayClient + ReplayHandle walk the canonical event log via runtime.events.iterate/fold, with tenantId required and a typed cache-miss policy.