Skip to content
pleach
Build

@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 SandboxProvider contract a host implements once and reuses across every sandboxed tool — read, write, list, exec — per the four-tool sketch in coding-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 legacy SandboxAdapter retained as a @deprecated alias, per the status row in packages.mdx.
  • The peer-dep anchor @pleach/coding-agent declares 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/sandbox

Endpoint-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.

AdapterImportBacking shape
createHttpStreamSandboxProvider@pleach/sandbox/adapters/httpStreamHTTP service with streaming responses (baseURL + auth)
createHttpPollSandboxProvider@pleach/sandbox/adapters/httpPollHTTP service you poll for completion (baseURL + auth)
createChildProcessSandboxProvider@pleach/sandbox/adapters/childProcesslocal child process (workspaceDir, shell)
createFargateSandboxProvider@pleach/sandbox/adapters/awsFargateAWS 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:

BackendPlatformWhat a cell gets
containerDocker or PodmanNo 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.
bwrapLinux, with bubblewrap installedEvery 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.
seatbeltmacOSA 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>/environ the 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

  • limits overrides any of cpuSeconds, memoryMb, pids, fileSizeMb, openFiles, outputBytes, defaultTimeoutMs, maxTimeoutMs and cpus (each has a built-in default). A non-positive or non-finite value throws, and a caller's timeoutMs is clamped to maxTimeoutMs. Which limits bind depends on the backend: memoryMb is --memory on the container backend and RLIMIT_AS on bwrap, but only a sampled watchdog on macOS with no hard cap; cpus applies to the container backend only.
  • workdirMode: "per-cell" (default) uses a fresh directory per call. "per-session" keeps one per chatId, bounded by maxSessions (default 32). On bwrap a per-cell /workspace is a tmpfs capped at fileSizeMb; 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.proc chooses 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 /proc paths (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 the ptrace probe alone, so an outer filter that denies ptrace would also satisfy it, and the runner adds a warning saying so.
  • container.image and container.engine select the image (digest-pinned) and the engine; interpreters and requirePythonVersion pin 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