Skip to content

Sandboxes with Experimental.Sandbox

Experimental. Experimental.Sandbox is an experimental module. A release can change or remove it. It needs no opt-in in tsconfig.json or vibe.config.json.

A sandbox is a provisioned machine that sits behind the ordinary platform services. Experimental.Sandbox gives you a layer (a value that supplies services to a program) for each kind of machine. Inside its provide block, Effect's ChildProcessSpawner, FileSystem and Path services belong to that machine, and the code that uses them does not change. Use a sandbox when an agent runs commands or edits files that must stay off the developer's own checkout. The design is VIP-67.

export effect function build() {
  provide Experimental.Sandbox.interpreter() {
    const fs = try FileSystem.FileSystem
    const spawner = try ChildProcessSpawner.ChildProcessSpawner
    try fs.writeFileString("notes.txt", "draft\n")
    const code = try spawner.exitCode(ChildProcess.make("sh", ["-c", "mkdir -p out && cp notes.txt out/final.txt"]))
    const text = try spawner.string(ChildProcess.make("cat", ["out/final.txt"]))
    const where = try spawner.string(ChildProcess.make("pwd", []))
    return [Number(code), text.trim(), where.trim(), try fs.readDirectory("out")]
  }
}
// Run in an effect function: try Console.log(try build())
// Output: [ 0, 'draft', '/workspace', [ 'final.txt' ] ]

Experimental.Sandbox.interpreter() is a machine that exists only in memory, so the sample runs with no host services. The file that fs writes is the file that cp copies, because both services reach the same machine. Relative paths start at the machine's working directory, /workspace. When the provide block ends, the machine is gone.

Providers

The following table lists the providers in this release. Each one is a function that returns a layer.

ProviderMachineIsolationNeeds on the host
interpreter({ workdir? })An in-process shell interpreter over an in-memory file systemNo real process existsNothing
directory(root?)A directory on this machine. With no root, a temporary directory that is removed when the layer closesNoneChildProcessSpawner and /bin/sh
command(prefix, { workdir?, joinsArguments? })The machine the prefix reaches, such as ["ssh", "host"] or ["docker", "exec", "-i", id]The target'sChildProcessSpawner and the prefix program
container({ image, network?, workdir?, engine? })A container that the layer starts and removesThe container engine'sChildProcessSpawner and docker, or the program in engine
kubernetes({ image, namespace?, workdir?, kubectl?, readyTimeout? })One Pod, deleted when the layer closesThe cluster'sChildProcessSpawner and kubectl

The module implements no isolation of its own: what a sandbox prevents is the provider's property. A directory sandbox separates a workspace and confines nothing, and an absolute path there is the host's path. A container starts with --network none unless network names a mode. container and kubernetes use /workspace as the working directory unless you set workdir.

The host providers read the ChildProcessSpawner around them, so provide a platform layer such as NodeServices.layer outside the sandbox. A provider that cannot open its machine fails with SandboxError.

To add a provider, adapt it with Experimental.Sandbox.fromRunner({ provider, workdir, run }), where run executes one /bin/sh script on the machine. For a machine with its own lifecycle, use Experimental.Sandbox.make(open).

Run commands and read files

Inside a sandbox, use the same services as on the host. The following rules apply on every provider:

  • The environment is replaced. A command sees PATH, HOME, USER, LANG, TERM, TMPDIR, SHELL, the LC_* variables in Experimental.Sandbox.keptVariables, and what its env option declares. It sees nothing else from the host.
  • Unsupported process options fail. detached: true, stdin: "inherit", a custom shell and extra file descriptors fail with a BadArgument PlatformError before anything runs.
  • Standard input arrives whole. The machine delivers all of it or refuses the command.
export effect function refused() {
  provide Experimental.Sandbox.interpreter() {
    const spawner = try ChildProcessSpawner.ChildProcessSpawner
    const stage = try spawner.string(ChildProcess.make("sh", ["-c", "echo $STAGE"], { env: { STAGE: "test" } }))
    const missing = try spawner.exitCode(ChildProcess.make("node", ["--version"]))
    const error = try Effect.flip(spawner.exitCode(ChildProcess.make("true", [], { detached: true })))
    try Console.log(stage.trim(), Number(missing), error._tag, error.reason._tag)
  }
}
// Run in an effect function: try refused()
// Output: test 127 PlatformError BadArgument

Effect.flip swaps success and failure so that the sample can print the error. The interpreter has no node program, so that command exits with 127.

Collect the changes as a diff

Experimental.Sandbox.run(provider, work) holds one machine for one unit of work. It returns the work's result and a binary git diff of what the machine's directory gained, untracked files included.

import * as NodeServices from "@effect/platform-node/NodeServices"
 
effect function work() {
  const fs = try FileSystem.FileSystem
  const spawner = try ChildProcessSpawner.ChildProcessSpawner
  try fs.writeFileString("hello.txt", "hello\n")
  return (try spawner.string(ChildProcess.make("cat", ["hello.txt"]))).trim()
}
 
export effect function scratch() {
  provide NodeServices.layer {
    const ran = try Experimental.Sandbox.run(Experimental.Sandbox.directory(), work())
    return [ran.result, ran.diff.split("\n")[0], ran.diff.includes("+hello")]
  }
}
// Run in an effect function: try Console.log(try scratch())
// Output: [ 'hello', 'diff --git a/hello.txt b/hello.txt', true ]

This sample runs real commands in a temporary directory on the host, and directory() removes that directory afterward. run needs git on the machine. In a directory that is not a repository, run keeps its own repository outside the directory, so the checkout does not change. An empty diff means nothing changed. The interpreter has no git, so run fails there with SandboxError.

Supervise a machine and run durable jobs

A process handle does not outlive the host that started it. For a command that must, use Experimental.Sandbox.job. To replace a machine that stops answering, wrap the provider in Experimental.Sandbox.supervised.

import * as NodeServices from "@effect/platform-node/NodeServices"
 
export effect function nightly() {
  const machine = Experimental.Sandbox.supervised(
    Experimental.Sandbox.container({ image: "node:22" }),
    { interval: "30 seconds", tolerance: 3 }
  )
  provide Layer.provide(machine, NodeServices.layer) {
    const job = Experimental.Sandbox.job(["npm", "test"], { key: "nightly-tests" })
    const started = try job.start
    const result = try job.collect
    return { started, exitCode: result.exitCode, stdout: result.stdout }
  }
}

The following table lists the members of a job.

MemberResult
start"started", or "existing" when a job with this key was started before. The command does not run twice
probeThe status: Absent, Running, Done with exitCode, Cancelled or Lost
collectWaits for the job, then gives exitCode, stdout and stderr. It fails with SandboxError for a cancelled, lost or absent job
cancelEnds the job and its children. A cancelled job stays cancelled

A job keeps its state on the machine under $TMPDIR/vibe-sandbox-jobs/<key>, so a restarted host finds the job by its key. A key holds 1 to 128 letters, digits, ., _ or -, and starts with a letter or digit. A Lost job was started and neither runs nor left an exit code, and the module never reruns it. Jobs need a POSIX shell with job control, so the interpreter cannot run one.

supervised runs true on the machine every interval. After tolerance failed probes in a row, it retires the machine: commands in flight fail, and the next command runs on a fresh machine from the same provider.

Test with a fixed machine

For a unit test, describe the machine instead of provisioning one. Experimental.Test.host({ files, commands }) provides the same three services from fixed files and scripted commands. Experimental.Test needs { "vibe": { "experimental": ["builtins"] } } in tsconfig.json or vibe.config.json. Both files take the same "vibe" object. Without it, the compiler reports EK3013.

const machine = Experimental.Test.host({
  files: { "/repo/package.json": `{"name":"demo"}` },
  commands: { "git status --short": { stdout: " M src/a.ts\n M src/b.ts\n" } }
})
 
export effect function changedFiles() {
  provide machine {
    const fs = try FileSystem.FileSystem
    const spawner = try ChildProcessSpawner.ChildProcessSpawner
    const manifest = try fs.readFileString("/repo/package.json")
    const status = try spawner.lines(ChildProcess.make("git", ["status", "--short"]))
    return `${manifest}: ${status.length} changed`
  }
}
// Run in an effect function: try Console.log(try changedFiles())
// Output: {"name":"demo"}: 2 changed

A command that the test does not script fails to spawn with a NotFound PlatformError. Test agentic programs lists the rest of the double's behavior. Choose Test.host when a test needs exact command output, and Sandbox.interpreter() when the code under test runs shell scripts against files it wrote.

Check a provider

Experimental.Sandbox.check(provider) runs the conformance suite that every provider must pass. The report holds passed, one { name, passed, detail? } entry per case, and egress: "unsupported".

export effect function checked() {
  const report = try Experimental.Sandbox.check(Experimental.Sandbox.interpreter())
  try Console.log(report.passed, report.results.length, report.results[4]?.name)
}
// Run in an effect function: try checked()
// Output: true 13 standard input is delivered whole

The 13 cases cover output, exit codes, argument quoting, standard input, the replaced environment, the working directory, files, the four refusals, and interruption.

Limits

The following limits apply in this release:

  • Interpreter commands. The interpreter runs basename, cat, cd, cp, dirname, echo, env, exit, export, false, ls, mkdir, mv, printf, pwd, rm, sh -c, sleep, test, [, touch, true and unset. Any other command exits with 127.
  • Interpreter syntax. The interpreter supports quotes, $NAME, ${NAME}, $?, ;, &&, ||, |, redirections and NAME=value assignments. Other syntax exits with 2.
  • Pipelines. A piped command runs in one directory with one environment, and only its first command receives standard input.
  • Cleanup. A teardown that fails is logged with the annotation code: "sandbox_cleanup_failed" and counted on the Experimental.Sandbox.cleanupFailures metric. It does not fail the program.
  • Outbound requests. Routing a guest's outbound requests through a secrets proxy is not in this release. check reports egress: "unsupported" for every provider.

Rules and diagnostics

The module adds no compiler diagnostics of its own. The following table lists the failures and the one diagnostic this page mentions.

Code or errorCondition
SandboxErrorA machine cannot be opened, reached or retired. code is aborted, timeout, unavailable, not_found, spawn_error, cleanup, unhealthy or unknown, and provider and reason say where and why
PlatformError with BadArgumentA command asks for a detached process, inherited standard input, a custom shell or extra file descriptors
PlatformErrorAny other failed file or process operation on the machine, as on the host
EK3013A file uses Experimental.Test, such as Test.host, without the builtins switch