Skip to content

Part 1: Build a Template and a Snapshot

Build an API that gives agents sandboxes. The slow setup runs once, when you deploy: an image with the tools, and a snapshot of it with a repository cloned. While the app runs, every sandbox starts from that snapshot in well under a second, already set up.

The finished code is in examples/e2b-agent-sandbox.

Finish E2B setup and Cloudflare setup.

A template is the image a sandbox boots from:

src/Sandbox.ts
import * as Dockerfile from "@alchemy.run/docker/Dockerfile";
import * as E2B from "@alchemy.run/e2b";
export const MyTemplate = E2B.Template("MyTemplate", {
dockerfile: Dockerfile.inline`
FROM node:22-bookworm
RUN apt-get update && apt-get install -y git
`,
cpuCount: 2,
memoryMB: 2048,
});

E2B builds it on its side, so you don’t need Docker.

A snapshot starts a sandbox from the template, runs commands in it, and saves the result:

src/Sandbox.ts
export const Warm = E2B.Snapshot("Warm", {
template: MyTemplate,
run: ["git clone --depth 1 https://github.com/sindresorhus/is repo"],
});

Every sandbox the app starts boots from Warm, with the repository already in /home/user/repo.

alchemy.run.ts
import * as Cloudflare from "@alchemy.run/cloudflare";
import * as E2B from "@alchemy.run/e2b";
import * as Alchemy from "alchemy";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { Warm } from "./src/Sandbox.ts";
export default Alchemy.Stack(
"E2BAgentSandboxExample",
{
providers: Layer.mergeAll(Cloudflare.providers(), E2B.providers()),
state: Alchemy.localState(),
},
Effect.gen(function* () {
const warm = yield* Warm;
return { snapshot: warm.templateId };
}),
);

Warm depends on MyTemplate, so deploying it builds both.

Terminal window
pnpm alchemy deploy

The first build takes a minute or two. Later deploys rebuild only what changed.

Part 2 starts sandboxes from it while the app runs.