Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

cloudflare.md

224 lines10.2 KB

1---
2title: Cloudflare (Edge, Advanced)
3id: cloudflare
4order: 11
5description: "Run a coding-agent harness at the edge with @tanstack/ai-sandbox-cloudflare: the agent loop, the run log, and the sandbox container in one Worker deploy, with runs that survive a closed tab."
6---
7​
8The Cloudflare sandbox runs the agent loop, the run history, and the container in one deploy. A run continues after the user closes the tab.
9​
10`@tanstack/ai-sandbox-cloudflare` gives you both. `createCloudflareSandboxAgent` builds the Worker routes, a coordinator Durable Object that drives each run and keeps its log, and the container plumbing.
11​
12For the provider-neutral basics (workspace, tools, policy, lifecycle), start at the [Overview](./overview).
13​
14## Deploy an agent at the edge
15​
161. Install the packages.
17​
18<!-- ::start:tabs variant="package-manager" mode="install" -->
19​
20react: @tanstack/ai @tanstack/ai-sandbox @tanstack/ai-sandbox-cloudflare @tanstack/ai-sandbox-local-process @tanstack/ai-claude-code zod
21vue: @tanstack/ai @tanstack/ai-sandbox @tanstack/ai-sandbox-cloudflare @tanstack/ai-sandbox-local-process @tanstack/ai-claude-code zod
22solid: @tanstack/ai @tanstack/ai-sandbox @tanstack/ai-sandbox-cloudflare @tanstack/ai-sandbox-local-process @tanstack/ai-claude-code zod
23svelte: @tanstack/ai @tanstack/ai-sandbox @tanstack/ai-sandbox-cloudflare @tanstack/ai-sandbox-local-process @tanstack/ai-claude-code zod
24preact: @tanstack/ai @tanstack/ai-sandbox @tanstack/ai-sandbox-cloudflare @tanstack/ai-sandbox-local-process @tanstack/ai-claude-code zod
25angular: @tanstack/ai @tanstack/ai-sandbox @tanstack/ai-sandbox-cloudflare @tanstack/ai-sandbox-local-process @tanstack/ai-claude-code zod
26octane: @tanstack/ai @tanstack/ai-sandbox @tanstack/ai-sandbox-cloudflare @tanstack/ai-sandbox-local-process @tanstack/ai-claude-code zod
27vanilla: @tanstack/ai @tanstack/ai-sandbox @tanstack/ai-sandbox-cloudflare @tanstack/ai-sandbox-local-process @tanstack/ai-claude-code zod
28​
29<!-- ::end:tabs -->
30​
31<!-- ::start:tabs variant="package-manager" mode="dev-install" -->
32​
33react: wrangler
34vue: wrangler
35solid: wrangler
36svelte: wrangler
37preact: wrangler
38angular: wrangler
39octane: wrangler
40vanilla: wrangler
41​
42<!-- ::end:tabs -->
43​
442. Add a `Dockerfile` for the sandbox container. Start from the `cloudflare/sandbox` base image, and install your harness CLI. Match the image tag to the `@cloudflare/sandbox` version in your lockfile.
45​
46```dockerfile
47FROM docker.io/cloudflare/sandbox:0.12.1
48​
49RUN npm install -g @anthropic-ai/claude-code --include=optional && claude --version
50```
51​
523. Declare the container and the two Durable Objects in `wrangler.jsonc`.
53​
54```jsonc
56 "name": "edge-agent",
57 "main": "src/worker.ts",
58 "compatibility_date": "2026-05-01",
59 "compatibility_flags": ["nodejs_compat"],
60 "containers": [{ "class_name": "Sandbox", "image": "./Dockerfile", "max_instances": 5 }],
61 "durable_objects": {
62 "bindings": [
63 // The coordinator that owns each run and its log.
64 { "name": "RUN_COORDINATOR", "class_name": "RunCoordinator" },
65 // The container host.
66 { "name": "Sandbox", "class_name": "Sandbox" }
67 ]
68 },
69 "migrations": [
70 { "tag": "v1", "new_sqlite_classes": ["RunCoordinator", "Sandbox"] }
71 ],
72 "vars": { "SANDBOX_TRANSPORT": "rpc" }
74```
75​
764. Create the agent. The package binds no API key, so declare the key your harness needs and pass it as a [workspace secret](./provisioning). This example uses `ANTHROPIC_API_KEY` for Claude Code. Grok Build uses `XAI_API_KEY`, and Codex uses `CODEX_API_KEY`.
77​
78```ts
79// src/agent.ts
80import { claudeCodeText } from '@tanstack/ai-claude-code'
81import {
82 createSecrets,
83 defineSandbox,
84 defineWorkspace,
85} from '@tanstack/ai-sandbox'
86import { cloudflareSandbox } from '@tanstack/ai-sandbox-cloudflare'
87import { createCloudflareSandboxAgent } from '@tanstack/ai-sandbox-cloudflare/agent'
88import type { SandboxAgentEnv } from '@tanstack/ai-sandbox-cloudflare/agent'
89​
90export interface AppEnv extends SandboxAgentEnv {
91 ANTHROPIC_API_KEY: string
93​
94export const agent = createCloudflareSandboxAgent<AppEnv>({
95 adapter: () => claudeCodeText('claude-opus-4-8'),
96 sandbox: (_input, env) =>
97 defineSandbox({
98 id: 'cf-edge-agent',
99 provider: cloudflareSandbox({ binding: env.Sandbox }),
100 workspace: defineWorkspace({
101 // The image already has the CLI. Nothing to clone.
102 source: { type: 'none' },
103 secrets: createSecrets({ ANTHROPIC_API_KEY: env.ANTHROPIC_API_KEY }),
104 }),
105 // One sandbox per thread, so a follow-up run reuses the workspace.
106 lifecycle: { reuse: 'thread' },
107 }),
108})
109```
110​
1115. Export the Worker and the Durable Object classes, set the key, and deploy.
112​
113```ts
114// src/worker.ts
115import { agent } from './agent'
116​
117// The class names in wrangler.jsonc.
118export const RunCoordinator = agent.Coordinator
119export const Sandbox = agent.Sandbox
120​
121export default agent.worker
122```
123​
124```bash
125npx wrangler secret put ANTHROPIC_API_KEY
126npx wrangler deploy
127```
128​
129## Start a run from the client
130​
131`POST /runs` starts a run and returns `202 { runId }` at once. Then open a WebSocket on `/runs/<runId>/stream` to tail it.
132​
133```ts
134export async function startRun(threadId: string, prompt: string) {
135 const response = await fetch('/runs', {
136 method: 'POST',
137 headers: { 'Content-Type': 'application/json' },
138 body: JSON.stringify({
139 threadId,
140 messages: [{ role: 'user', content: prompt }],
141 }),
142 })
143 const body: unknown = await response.json()
144 if (
145 typeof body !== 'object' ||
146 body === null ||
147 !('runId' in body) ||
148 typeof body.runId !== 'string'
149 ) {
150 throw new Error('POST /runs returned no runId')
151 }
152 return body.runId
154​
155// Pass the last `seq` you saw to resume after a drop. -1 replays from the start.
156export function tailRun(threadId: string, runId: string, lastSeq = -1) {
157 const url = new URL(`/runs/${runId}/stream`, window.location.href)
158 url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
159 url.searchParams.set('threadId', threadId)
160 url.searchParams.set('lastSeq', String(lastSeq))
161​
162 const socket = new WebSocket(url)
163 socket.addEventListener('message', (message) => {
164 // `{ seq, chunk }` per event, then one `{ type: 'status', record }`.
165 console.log(JSON.parse(String(message.data)))
166 })
167 return socket
169```
170​
171Call `startRun`, then `tailRun`. Close the tab in the middle, open it again, and tail with your last `seq`: the run kept going.
172​
173## How it works
174​
175- **The Worker only routes.** `POST /runs` goes to the coordinator Durable Object for that `threadId`, which registers the run and returns. The Worker does not wait for the agent.
176- **The coordinator drives the run.** It runs `chat()` with your adapter. The agent CLI runs in the container. Your `chat()` tools reach the agent through an MCP bridge on the coordinator's own `fetch` handler.
177- **Every chunk goes to a run log** in Durable Object storage, under a growing `seq`. Clients tail that log from a cursor. A refresh, a dropped WebSocket, or a coordinator that hibernates between chunks never touches the sandbox.
178- **The container is reached over the network**, through callback URLs that the coordinator derives from the request host. A `*.workers.dev` deploy needs no config.
179​
180This is the default **DO-drives** model. In the **co-located** model, the agent loop runs inside the container instead. See [Cloudflare Edge Details](./cloudflare-advanced#co-located-mode).
181​
182## Durable runs at the edge
183​
184Cloudflare is the **log-first tier** of the [durable runs](./durable-runs#the-two-tiers) protocol. The coordinator's run log is the durable copy. A closed tab or dropped WebSocket only detaches the tail: the coordinator keeps driving, and the log keeps filling.
185​
186Two rules matter in production:
187​
188- **Stop must destroy the container.** `cloudflareSandbox` declares `killableProcesses: false`: no signal crosses the Workers RPC boundary. So the only cancel that stops the agent is to destroy the container. A run marked `aborted` without the destroy keeps working, and billing, behind a UI that says "stopped". See [what cancel means on a provider that cannot kill](./takeover#what-cancel-means-on-a-provider-that-cannot-kill).
189- **The run log survives, the container does not.** If the container stops, the agent dies mid-run, like anywhere else. The log keeps everything emitted up to that point.
190​
191> [!WARNING]
192> The Sandbox container class has a `sleepAfter` idle timeout. A detached run that is quiet (nobody connected, the agent thinking) can look idle, and an idle container sleeps. The run then "dies for no reason", while the log keeps its prefix. Set `sleepAfter` well above your longest quiet stretch before you rely on detached runs.
193​
194### Stall watchdog
195​
196`createCloudflareSandboxAgent` sets one stall policy for the whole app. `stallTimeoutMs` applies to every run, in both `do-drives` (the default) and `colocated` mode:
197​
198| Value | Behavior |
199| --- | --- |
200| Omitted | A run with no persisted activity for `300000` ms (five minutes) is stalled. |
201| Positive safe integer | Use that many milliseconds as the limit. |
202| `false` | No stall detection. |
203​
204To allow ten quiet minutes, add one line next to `adapter` in `src/agent.ts`:
205​
206```diff
207 export const agent = createCloudflareSandboxAgent<AppEnv>({
208 adapter: () => claudeCodeText('claude-opus-4-8'),
209+ stallTimeoutMs: 10 * 60_000,
210 sandbox: (_input, env) =>
211```
212​
213How it decides:
214​
215- **The alarm checks every 30 seconds**, or every `stallTimeoutMs` when that is shorter. So detection can lag the limit by up to one check.
216- **Activity resets the clock.** Persisted run events do. Authenticated `/_bridge` and `/tool-exec` callbacks do too, when they arrive and when they complete. Unknown-run and unauthorized requests do not.
217- **Set the limit above your longest quiet period.** A native operation that emits no event and makes no callback is invisible to the watchdog.
218- **An in-flight authenticated callback is protected.** A callback that never completes can leave an orphaned `running` record. So can `false`.
219​
220On a stall, the watchdog marks the run log `failed`. It does not promise to kill the agent process or the container. Use provider lifecycle controls and the [reaper](./reaping) for cleanup.
221​
222## Go deeper
223​
224For the co-located model, live previews, callback hosts, the run log internals, and what edge durability does not cover, see [Cloudflare Edge Details](./cloudflare-advanced).