Skip to content

5. Cloudflare Sandbox

Checkpoint 5 of 68 minutes

Cloudflare Sandbox

Have FieldTrip write itinerary.md, check its contents, and open it again in the same conversation.

The team likes the suggestions. Now they want an itinerary they can work with, not just another chat reply. FieldTrip needs somewhere to create a real file.

Think of the Sandbox as the planner’s workbench: a small Linux computer with a working folder. FieldTrip can write itinerary.md, read it to check the contents, and open it again when you ask in the same conversation. Each conversation gets its own workspace.

What you’ll add: the Sandbox setup and file tools. The workbench is temporary: files may disappear if its container is replaced. The saved trip notebook from checkpoint 2 lives separately and survives that replacement.

Under the hood: the workspace and its lifetime

useSandbox(cloudflareSandbox(getSandbox(env.Sandbox, id))) gives the model read, write, edit, bash, grep, and glob tools. The conversation ID selects a Sandbox Durable Object and container. Files can remain available across turns and deployments, but must not be relied on to survive container replacement. Conversation history and usePersistentState stay in the agent’s Durable Object, separate from the container disk.

Docker is first needed in this checkpoint. If it is missing, open the installation instructions below before running these checks.

Start Docker Desktop (or Docker Engine on Ubuntu). In Terminal B:

Terminal window
docker info --format '{{.OSType}}' && docker buildx version

Look for: linux and a Buildx version. Then download the lab’s image:

Terminal window
docker pull --platform linux/amd64 cloudflare/sandbox:0.12.10

Look for: Downloaded newer image or Image is up to date. Keep Docker running for local development and deployment throughout this checkpoint.

What if the Docker check fails?

If the daemon cannot be reached, open Docker Desktop and wait for the engine to start, then retry. On Windows choose Linux containers / WSL 2. On Ubuntu, docker info must work as your ordinary user, without sudo, for Wrangler to use it.

The explicit linux/amd64 platform also works on Apple Silicon; 0.12.10 matches the workshop’s Sandbox SDK.

Install Docker on Windows, macOS, or Ubuntu

Choose one operating-system tab. Run each block in order and wait for its prompts to finish.

On a managed computer where installation is blocked, show the output to a facilitator for the session’s installation path. Installers may request an administrator password. Docker Desktop’s commercial-use terms may require your organization’s paid subscription.

Use Windows PowerShell (5.1 or 7) on a supported Windows 11 x64 computer. These installation commands use PowerShell; return to Git Bash for the Docker checks and the rest of the workshop.

1. Install Docker Desktop:

Terminal window
winget install --id Docker.DockerDesktop --exact --source winget --accept-source-agreements --accept-package-agreements

2. Enable WSL 2 if Docker asks for it. In PowerShell → Run as administrator:

Terminal window
wsl --install --no-distribution

Restart Windows if prompted. If WSL is already installed but Docker asks for a newer version, run wsl --update in administrator PowerShell instead. Hardware virtualization must be enabled; a facilitator can help with Docker’s Windows requirements.

Open Docker Desktop from Start, complete its first-run prompts, use the Linux containers / WSL 2 backend, and wait for the engine to be running. Close your old terminals and open Git Bash from Start for the Docker check and all remaining workshop commands. In VS Code, select Git Bash as the terminal profile. Do not run the Linux installation tab inside WSL for this Windows setup.

After installation, reopen the workshop shell and run the Docker check.

Ready when: Docker runs Linux containers, Buildx works, and the pinned Sandbox image is downloaded.

Install the code package that lets your app use the Sandbox. Its version must match the Docker image you downloaded above: 0.12.10.

If a dev server is running, press Ctrl+C in its terminal before changing dependencies. Installing while Vite watches node_modules can leave a stale optimized-dependency cache.

Terminal window
npm install --save-exact @cloudflare/sandbox@0.12.10

This adds the following dependency to package.json and regenerates package-lock.json automatically:

"@cloudflare/sandbox": "0.12.10"

Keep the other dependencies unchanged. If you use Local dev, leave Vite stopped until all checkpoint files are in place, then restart it from that verification tab.

Create Dockerfile in the project root. It tells Docker which Sandbox image to use as the workspace’s starting point:

  • Dockerfile

Create this file. Create the parent folders if needed. In your code editor (for example, VS Code), open the file named above. Copy the code in Complete file, paste it into that file's editing pane, and save.

Dockerfile
# Container image for the agent sandbox (cp5).
# The tag MUST match the @cloudflare/sandbox version in package.json.
FROM docker.io/cloudflare/sandbox:0.12.10

Create src/cloudflare.ts so Cloudflare can load the Sandbox:

  • src
    • cloudflare.ts

Create this file. Create the parent folders if needed. In your code editor (for example, VS Code), open the file named above. Copy the code in Complete file, paste it into that file's editing pane, and save.

src/cloudflare.ts
// Extra Worker-entry exports. Flue re-exports everything from this file.
// The Sandbox Durable Object class backs the agent's container sandbox (cp5).
export { Sandbox } from '@cloudflare/sandbox';

Update src/env.d.ts so the code recognises the new Sandbox connection:

  • src
    • env.d.ts

Replace the entire contents of this file. In your code editor (for example, VS Code), open the file named above. Copy the code in Complete file, paste it into that file's editing pane, and save.

src/env.d.ts
// Vite `?raw` imports return the file contents as a string (used for the chat UI).
declare module '*.html?raw' {
const content: string;
export default content;
}
// cp5: the Sandbox binding from wrangler.jsonc, typed for `import { env } from 'cloudflare:workers'`.
declare module 'cloudflare:workers' {
export const env: { Sandbox: Parameters<typeof import('@cloudflare/sandbox').getSandbox>[0] };
}

3. Tell Cloudflare how to run the workspace

Section titled “3. Tell Cloudflare how to run the workspace”

Update wrangler.jsonc to add the workspace setup. It connects the app to the Sandbox and tells Cloudflare which container image to run:

  • wrangler.jsonc

Replace the entire contents of this file. In your code editor (for example, VS Code), open the file named above. Copy the code in Complete file, paste it into that file's editing pane, and save.

wrangler.jsonc
{
"$schema": "./node_modules/wrangler/config-schema.json",
"name": "field-trip-agent",
// Flue requires nodejs_compat and a compatibility_date of 2026-04-01 or newer.
"compatibility_date": "2026-09-01",
"compatibility_flags": ["nodejs_compat"],
// Workers AI binding: powers `cloudflare/@cf/...` models. No API keys needed.
// AI always runs remotely (even in `vite dev`), so `remote: true` is explicit.
"ai": {
"binding": "AI",
"remote": true
},
// Durable Object migrations. Flue generates one DO class per agent
// (FieldTrip -> FlueFieldTripAgent), but YOU own the migration history.
// Checkpoint 1 adds the first entry here. Append; never rewrite deployed entries.
"migrations": [
{
"tag": "v1",
"new_sqlite_classes": ["FlueFieldTripAgent"]
},
{ "tag": "v2", "new_sqlite_classes": ["Sandbox"] }
],
// cp5: container sandbox (class exported from src/cloudflare.ts, image from ./Dockerfile).
"durable_objects": { "bindings": [{ "name": "Sandbox", "class_name": "Sandbox" }] },
"containers": [{ "class_name": "Sandbox", "image": "./Dockerfile", "max_instances": 10 }]
}

The v2 migration must be appended; never rewrite the deployed v1 migration.

Update src/agents/field-trip.ts to connect each conversation to its own workspace and tell FieldTrip to write and check the itinerary file:

  • src
    • agents
      • field-trip.ts

Replace the entire contents of this file. In your code editor (for example, VS Code), open the file named above. Copy the code in Complete file, paste it into that file's editing pane, and save.

src/agents/field-trip.ts
'use agent';
import { type AgentProps, useModel, usePersistentState, useSandbox, useSubagent, useTool } from '@flue/runtime';
import { cloudflareSandbox } from '@flue/runtime/cloudflare';
import { getSandbox } from '@cloudflare/sandbox';
import { env } from 'cloudflare:workers';
import * as v from 'valibot';
import { geocodeCity, getForecast } from '../tools/weather.ts';
import { findNearbyPlaces } from '../tools/wikipedia.ts';
import { venueScout } from '../subagents/venue-scout.ts';
// The trip brief the agent remembers for this conversation.
type TripBrief = {
city?: string;
startDate?: string; // YYYY-MM-DD
endDate?: string; // YYYY-MM-DD
headcount?: number;
budget?: string;
interests?: string[];
};
export function FieldTrip({ id }: AgentProps) {
useModel('cloudflare/@cf/google/gemma-4-26b-a4b-it');
// Durable, per-conversation state (stored in this conversation's Durable Object).
// Shaped like React's useState, but it survives restarts and redeploys.
const [brief, setBrief] = usePersistentState<TripBrief>('brief', {});
// Tools can write state. The write commits together with the tool call.
useTool({
name: 'save_trip_brief',
description:
'Save or update the offsite trip brief. Call this whenever the user states or changes the city, dates, headcount, budget, or interests. Only include fields the user mentioned; they are merged into the saved brief.',
input: v.object({
city: v.optional(v.string()),
startDate: v.optional(v.pipe(v.string(), v.isoDate())),
endDate: v.optional(v.pipe(v.string(), v.isoDate())),
headcount: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1))),
budget: v.optional(v.string()),
interests: v.optional(v.array(v.string())),
}),
async run({ data }) {
const updates = Object.fromEntries(
Object.entries(data).filter(([, value]) => value !== undefined),
) as TripBrief;
setBrief((previous) => ({ ...previous, ...updates }));
return { output: { saved: updates } };
},
});
// Tools that call an external API (Open-Meteo), defined in src/tools/weather.ts.
useTool(geocodeCity);
useTool(getForecast);
// The parent finds candidate places (Wikipedia geosearch)...
useTool(findNearbyPlaces);
// ...and delegates all three candidates in one task. The scout runs in a
// fresh context with its own tools, and only its final answer comes back.
useSubagent(venueScout);
// A Linux container per conversation (adds read/write/edit/bash/grep/glob tools).
useSandbox(cloudflareSandbox(getSandbox(env.Sandbox, id)));
// The agent re-renders before every model call, so these instructions
// always reflect the latest saved brief.
const hasBrief = Object.keys(brief).length > 0;
const today = new Date().toISOString().slice(0, 10);
return `You are FieldTrip, a helpful team-offsite planner. You help groups plan memorable offsites by understanding their destination, dates, headcount, budget, and interests.
Rules:
1. If the user's message contains ANY trip detail (city, dates, headcount, budget, interests), your FIRST action is to call \`save_trip_brief\` with those fields. Do this before writing any reply.
2. Answer questions about the trip from the saved brief below. If a detail is missing, ask for it.
3. For weather questions: call \`geocode_city\` for the city, then \`get_forecast\` with its latitude/longitude and the trip dates (use the saved brief). If there is no end date, use the start date. Summarise the forecast per day in plain words; if a tool returns an error, explain it to the user.
4. For venue, activity or place suggestions:
a. Call \`geocode_city\`, then \`find_nearby_places\` with its coordinates.
b. Pick the 3 places that best fit the brief (skip stations, offices, hospitals, embassies, companies, events).
c. Call \`task\` ONCE with agent \`venue-scout\` for all 3 places. The scout cannot see this conversation, so the prompt must be a complete briefing: the exact place titles, the city, the headcount, and the interests.
d. Combine the results into a short plan, keeping the links. If you know the forecast, suggest outdoor places for dry days and indoor ones for rainy days.
5. For an itinerary: \`write\` it to itinerary.md (one section per day: places, timing, weather), then \`read\` it to check. Do not repeat the file in your reply (the user sees the read result); reply in one sentence.
6. Keep replies short: at most 120 words unless the user asks for more detail.
Today is ${today}.
## Saved trip brief
${hasBrief ? JSON.stringify(brief, null, 2) : '(nothing saved yet)'}`;
}

Everything under src/tools/, src/subagents/venue-scout.ts, and src/app.ts is unchanged from cp/4-subagent.

Reuse one conversation ID so all turns reach the same container. Trip dates are filled automatically in the commands and their copy buttons.

Keep Docker running: deployment builds and uploads the image from Dockerfile.

Terminal window
npm run deploy
sleep 5

Wait for deployment to finish. The first container deployment can need several minutes to provision even after the Worker URL is printed. Then run:

Terminal window
npm run smoke -- https://field-trip-agent.<subdomain>.workers.dev cp5-live "Offsite in Lisbon from <START> to <END> for 14 people, budget 400 EUR each. We like food, history and the outdoors."
TIMEOUT_S=200 npm run smoke -- https://field-trip-agent.<subdomain>.workers.dev cp5-live "Write the itinerary to itinerary.md and show it to me."
npm run smoke -- https://field-trip-agent.<subdomain>.workers.dev cp5-live "Show me itinerary.md again."

The itinerary turn must show write, then read. The last turn must read the same file again. Judge the tool calls rather than the exact model wording. This tests image upload and Sandbox execution on Cloudflare Containers.

Optional depth check: repeat delegation, then prove isolation:

Terminal window
TIMEOUT_S=200 npm run smoke -- https://field-trip-agent.<subdomain>.workers.dev cp5-live "Suggest 3 places for our offsite."
TIMEOUT_S=200 npm run smoke -- https://field-trip-agent.<subdomain>.workers.dev cp5-live-other "Use bash to run: ls -la /workspace. Then tell me whether a trip brief is saved."

cp5-live-other must not inherit cp5-live’s itinerary or trip brief. A redeploy may reuse an existing container, so it does not deterministically prove ephemeral disk.

Save your workers.dev subdomain to open this test ↗https://field-trip-agent.<subdomain>.workers.dev/?id=cp5-live

This opens the same conversation as the smoke test. If you repeat this checkpoint, before copying its commands.

Verification gate

Prove it works

  • The agent uses write and read for itinerary.md.
  • A later message in the same conversation reads the file again.
  • Optional: a different conversation has its own workspace and trip notebook.
  • You understand that workspace files are temporary, while the trip notebook stays saved.
Optional mini quizCheck your understanding: the workbench3 questions instant feedback
1Who shares the workspace?
2How do you check that FieldTrip really created the itinerary?
3What stays saved if the temporary workspace is replaced?
Recovery lane

Get back on track in under a minute

If a dev server is running, stop it first. Uncommitted work is stashed and the current commit gets a backup branch before anything moves.

Option 01

Restart this exercise

Return to cp/4-subagent, rebuild this exercise, then use its Live deploy verification tab. Stop any running dev server with Ctrl+C before switching.

Terminal
git stash push --include-untracked -m "workshop recovery"
git fetch origin
git branch -f workshop-backup HEAD
git switch --no-track -C workshop origin/cp/4-subagent
npm ci
Option 02

Catch up with the room

Jump to cp/5-sandbox, then use this checkpoint's Live deploy verification tab. Stop any running dev server with Ctrl+C before switching.

Terminal
git stash push --include-untracked -m "workshop recovery"
git fetch origin
git branch -f workshop-backup HEAD
git switch --no-track -C workshop origin/cp/5-sandbox
npm ci

Next: See how FieldTrip reaches an answer →