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

cloudflare.md

328 lines16.2 KB

1---
2title: Cloudflare (Edge, Advanced)
3id: cloudflare
4order: 11
5description: "Run a coding-agent harness and a live preview at the edge with @tanstack/ai-sandbox-cloudflare — Workers, Containers, and Durable Objects in one deploy."
6---
7​
8You want your coding agent to run **at the edge** — UI, agent loop, and the
9sandbox container all in one Cloudflare Worker — and to hand users a **live
10preview URL** of whatever the agent builds. `@tanstack/ai-sandbox-cloudflare`
11provides the `cloudflareSandbox` provider plus a ready-made agent coordinator so
12you don't hand-roll the Worker ↔ container plumbing.
13​
14This page covers the edge-specific concerns. For the provider-agnostic basics
15(workspace, tools, policy, lifecycle) start at the [Overview](./overview).
16​
17## Two execution models
18​
19Where the harness loop and its [tool bridge](./tools) run is a deployment
20choice. The Cloudflare layer supports two shapes.
21​
22### DO-drives-container (default)
23​
24The orchestrator (a Durable Object) runs `chat()` and the tool-bridge; the
25container only runs the agent CLI. The bridge is served from the orchestrator's
26own `fetch` handler — no raw TCP listener — and the agent reaches it across the
27container → orchestrator boundary, so the **whole MCP protocol** crosses that
28boundary. The `examples/sandbox-cloudflare` TanStack Start app demonstrates this:
29UI, agent, Durable Objects, and the container in one Worker.
30​
31### Co-located (in-container)
32​
33The harness loop **and** the tool-bridge run inside the container — the
34in-container sandbox is just `localProcessSandbox()`, with native stdin and a
35localhost `node:http` bridge. The only thing that still crosses back to the
36orchestrator is host **tool execution**: a `chat()` tool's `execute()` closure
37(your DB, secrets, app state) lives on the orchestrator, not in the container.
38The public surface shrinks from the whole MCP protocol to a single authenticated
39tool-exec call.
40​
41Enable it with `createCloudflareSandboxAgent({ mode: 'colocated' })` plus a
42`runInContainerHarness` container program from
43`@tanstack/ai-sandbox-cloudflare/runner`. The seam is four exports from
44`@tanstack/ai-sandbox`: the orchestrator serializes its tools with
45`toolDescriptors(tools)` and ships the descriptors in; the container rebuilds
46them with `remoteToolStubs(descriptors, executor)`, where each stub's `execute()`
47delegates to a `RemoteToolExecutor` (`httpRemoteToolExecutor(url, token)` POSTs
48`{ name, args }` back); the orchestrator answers that one call with
49`executeHostTool(tools, name, args)`.
50​
51```ts
52import { chat } from '@tanstack/ai'
53import { grokBuildText } from '@tanstack/ai-grok-build'
54import {
55 defineSandbox,
56 defineWorkspace,
57 httpRemoteToolExecutor,
58 remoteToolStubs,
59 withSandbox,
60} from '@tanstack/ai-sandbox'
61import { localProcessSandbox } from '@tanstack/ai-sandbox-local-process'
62import { request } from './run-request'
63​
64// Inside the container: the orchestrator POSTed `{ messages, toolDescriptors,
65// toolExecUrl, toolExecToken }`. Rebuild its tools as stubs whose execute()
66// POSTs back; the adapter bridges them over the in-container localhost MCP
67// transport, and only that one tool-exec call leaves the container.
68chat({
69 threadId: request.threadId,
70 adapter: grokBuildText('grok-build'),
71 messages: request.messages,
72 tools: remoteToolStubs(
73 request.toolDescriptors,
74 httpRemoteToolExecutor(request.toolExecUrl, request.toolExecToken),
75 ),
76 // The in-container sandbox is just local-process (native stdin + a localhost
77 // node:http bridge).
78 middleware: [
79 withSandbox(
80 defineSandbox({
81 id: 'in-container',
82 provider: localProcessSandbox(),
83 workspace: defineWorkspace({ source: { type: 'none' } }),
84 }),
85 ),
86 ],
87})
88```
89​
90## Durable runs at the edge
91​
92Cloudflare is the **log-first tier** of the portable durable-runs protocol —
93not a separate architecture. Read
94[Durable Runs Explained](./durable-runs#the-two-tiers) first; this section is
95what the edge changes and what it deliberately does not.
96​
97The coordinator Durable Object owns each run and persists every emitted chunk
98into a DO-storage-backed run log (`DurableObjectRunEventLog`) under a monotonic
99`seq`. Clients only ever tail that log from a cursor, so a refresh, a dropped
100WebSocket, or a coordinator that hibernated between chunks reconnects **without
101ever touching the sandbox**. The [journal](./journal) keeps its portable job on
102the driver side — warm reattach and the driver's resume position — and the
103precedence rule is the portable one: the log wins for what clients see, the
104journal wins for where the driver resumes.
105​
106What is genuinely Cloudflare-specific is the DO's *supervised lifetime*: the
107driver outlives any request and `alarm()` gives it a scheduler. Off Cloudflare,
108[takeover](./takeover) is the substitute for exactly that, which is why the
109journal stays mandatory on every tier.
110​
111"One portable protocol" is literal here, not a framing: the coordinator drives
112runs with **core's run driver** (`RunController` from `@tanstack/ai-sandbox`),
113bound to the DO log by two adapters — `runLogStore` exposes the log as core's
114`RunStore`, and `runLogStream` exposes one run of it as core's
115`StreamDurability`. Both are exported from
116`@tanstack/ai-sandbox-cloudflare/agent` for apps composing directly, and they
117are what lets the portable pieces (`alignToStoredLog`, `replayRunStream`) work
118against the DO log the same way they do against `memoryStream` or
119`durableStream`.
120​
121The vocabulary is core's throughout: statuses are `completed` / `failed` /
122`aborted`, and the record is core's `RunRecord` plus the log's own `lastSeq`
123cursor (`RunLogRecord`). Records a Durable Object persisted under the pre-1.0
124layout (`done` / `error` statuses, `createdAt`/`updatedAt` fields) are
125migrated in place on first read — nothing to run, but note that
126`GET /runs/:id` and the WebSocket terminal `status` frame now carry the
127converged status strings and field names.
128​
129### Stall watchdog
130​
131`createCloudflareSandboxAgent` sets one stall policy for the whole app. The
132`stallTimeoutMs` field applies to every run in both `do-drives` (the default)
133and `colocated` mode:
134​
135| Value | Behavior |
136| --- | --- |
137| Omitted | Treat the run as stalled after `300000` ms (five minutes) without persisted activity |
138| Positive safe integer | Use that many milliseconds as the stall threshold |
139| `false` | Disable stall detection |
140​
141```ts
142import { grokBuildText } from '@tanstack/ai-grok-build'
143import { createCloudflareSandboxAgent } from '@tanstack/ai-sandbox-cloudflare/agent'
144​
145export const agent = createCloudflareSandboxAgent({
146 adapter: () => grokBuildText('grok-build'),
147 stallTimeoutMs: 10 * 60_000,
148})
149```
150​
151The alarm checks every 30 seconds, or every `stallTimeoutMs` when that is
152shorter, so detection can lag the configured threshold by up to one check
153interval. Persisted run events refresh
154`updatedAt`; authenticated `/_bridge` and `/tool-exec` callbacks also refresh it
155on arrival and completion. Unknown-run and unauthorized requests do not.
156​
157Choose a timeout longer than the longest legitimate quiet period. Native
158operations that emit no event and make no callback are invisible to the
159watchdog. An authenticated callback is protected while it remains in flight.
160A callback that never completes can leave an orphaned `running` record.
161Disabling the watchdog with `false` can do the same. When a stall is detected, the watchdog marks
162the run log `failed`; it may not kill the underlying agent process or container.
163Use provider lifecycle controls and [reaping](./reaping) for resource cleanup.
164​
165### Three layers, three homes
166​
167Keep these separate — each has a different home on Cloudflare, and conflating
168them is how workspace bytes end up "durably" in `/tmp`:
169​
170| Layer | Where it lives on Cloudflare | Covered in |
171| --- | --- | --- |
172| Run + events | The coordinator DO's run log (DO storage) | [The Run Journal](./journal), [Takeover](./takeover) |
173| Workspace (the files the agent edits) | The container filesystem — **not durable**; re-provision it on create | [Workspace](./workspace), [Provisioning](./provisioning) |
174| Artifacts (outputs worth keeping) | R2, via a persistence `BlobStore` / `ArtifactStore` | [Keep generated files](../persistence/keep-generated-files) |
175​
176### What edge durability does not buy you
177​
178- **The journal is not durable here.** `cloudflareSandbox` declares
179 `durableFilesystem: false`: the `/tmp` journal lives exactly as long as the
180 container instance. That is fine — on this tier the DO log is the durable
181 copy and the journal is driver recovery — but it means the journal must never
182 be treated as the store of record.
183- **Refresh safety is not sleep survival.** The log makes *reconnecting
184 clients* safe. It does not keep the container awake: if the container stops,
185 the agent process dies mid-run like anywhere else, and what the log preserves
186 is everything emitted up to that point.
187- **The `sleepAfter` footgun.** The Sandbox container class carries a
188 `sleepAfter` idle timeout. A run that is *detached but quiet* — nobody
189 connected, the agent thinking or waiting — can look idle, and an idle
190 container sleeps. The symptom is a run that "died for no reason" while the
191 log dutifully preserved its prefix, which reads as durability failing when it
192 is the container lifecycle working as configured. Size `sleepAfter` well
193 above your longest expected quiet stretch before relying on detached runs.
194- **Name the sandbox by `threadId`.** Prefer
195 `defineSandbox({ id: input.threadId, … })` (as `examples/sandbox-cloudflare`
196 does) over a fixed id: reconnects, `exposePreview`, and `reuse: 'thread'`
197 then all address the same container even across DO eviction.
198​
199### Disconnect detaches; Stop cancels
200​
201The portable rule holds on this path: a closed tab or dropped WebSocket only
202detaches the tail — the DO keeps driving and the log keeps filling. Stopping is
203an explicit cancel, and on this provider that has teeth: `killableProcesses` is
204`false` (no signal crosses the Workers RPC boundary), so the only cancel that
205actually stops the agent is destroying the container. Aborting the run so the
206log is marked `aborted`, without the destroy, leaves the agent running — and
207billing — behind a UI that says stopped. See
208[what cancel means on a provider that cannot kill](./takeover#what-cancel-means-on-a-provider-that-cannot-kill).
209​
210## Callback hosts: bridge vs preview
211​
212In both models the container is **off-isolate compute** — it can't use a service
213binding or an in-process call to reach the Worker, only the network. So the
214container's callback URLs need real hosts. There are **two distinct surfaces**
215with different reachers and therefore different correct values, resolved by
216`resolveBridgeOrigin` and `resolvePreviewHost` (both from
217`@tanstack/ai-sandbox-cloudflare/agent`).
218​
219- **Bridge / tool-exec** (container → Worker: `/_bridge`, `/tool-exec`). Just
220 needs to *reach* the Worker. `PUBLIC_HOSTNAME` is optional — when unset, the
221 host is derived from the `POST /runs` trigger request, so a `*.workers.dev`
222 deploy works with **zero config**, and **local dev uses
223 `host.docker.internal`** (the Docker host gateway, over `http`) — no tunnel.
224​
225 > Request-derivation is safe **on Cloudflare**, where it would be unsafe on a
226 > generic Node server: the edge dispatches a request to your Worker only when
227 > its hostname matches a route you own, so the request `Host` is always one of
228 > your own hostnames — never attacker-chosen — and the per-run bearer token
229 > that rides the URL can't be steered off-domain. On plain Node the `Host`
230 > header is attacker-controlled, which is why request-derivation there would be
231 > a token-exfil / SSRF vector. (See [Tools](./tools) for the non-edge bridge.)
232​
233- **Preview** (browser → Worker → container: `exposePort`). Needs **wildcard
234 DNS**, so `PREVIEW_HOSTNAME` is a *separate* knob. **Local** uses `*.localhost`
235 (browsers resolve it to loopback with zero setup — previews work locally with
236 no tunnel). **Deployed** needs a **custom domain** with a `*.<domain>` route:
237 `*.workers.dev` has no wildcard subdomains, so the SDK's `exposePort` rejects
238 it and `resolvePreviewHost` throws a clear error pointing at `PREVIEW_HOSTNAME`
239 instead of failing deep in a run.
240​
241## Exposing a live preview
242​
243The package ships the browser-preview wiring so you don't hand-roll it — both
244exported from `@tanstack/ai-sandbox-cloudflare/agent`:
245​
246- **`exposePreviewTool(input, env)`** — a ready-made `chat()` server tool (the
247 agent sees it as `exposePreview`). It addresses the run's container by
248 `threadId` and opens a **Cloudflare quick tunnel** to the dev server's port
249 (`sandbox.tunnels.get(port)`), returning a
250 `https://<name>.trycloudflare.com` URL.
251- **`PREVIEW_GUIDANCE`** — a system prompt that tells the agent how to start a
252 dev server whose tunnel preview works. App-agnostic on purpose.
253​
254The factory is **harness-agnostic about auth**: it binds no API key of its own.
255Your app declares the key its harness needs (`XAI_API_KEY` for Grok Build,
256`ANTHROPIC_API_KEY` for Claude Code, `CODEX_API_KEY` for Codex, …) on its own env
257type and supplies it as a [workspace secret](./provisioning) — the coordinator
258injects each declared secret into the sandbox env by name.
259​
260```ts
261import {
262 PREVIEW_GUIDANCE,
263 createCloudflareSandboxAgent,
264 exposePreviewTool,
265 resolvePreviewHost,
266} from '@tanstack/ai-sandbox-cloudflare/agent'
267import { cloudflareSandbox } from '@tanstack/ai-sandbox-cloudflare'
268import { createSecrets, defineSandbox, defineWorkspace } from '@tanstack/ai-sandbox'
269import { grokBuildText } from '@tanstack/ai-grok-build'
270import type { SandboxAgentEnv } from '@tanstack/ai-sandbox-cloudflare/agent'
271​
272// Extend the package's harness-agnostic env with the key YOUR harness needs.
273interface AppEnv extends SandboxAgentEnv {
274 XAI_API_KEY: string
276​
277export const agent = createCloudflareSandboxAgent<AppEnv>({
278 adapter: () => grokBuildText('grok-build'),
279 systemPrompts: [PREVIEW_GUIDANCE],
280 tools: (input, env) => [exposePreviewTool(input, env)],
281 // Supply the harness's auth here — the package binds no key. The `sandbox`
282 // resolver receives the Worker `env` per run, so the secret VALUE is read from
283 // it. A different harness declares its own, e.g. `ANTHROPIC_API_KEY` for Claude
284 // Code or `CODEX_API_KEY` for Codex.
285 sandbox: (input, env) =>
286 defineSandbox({
287 id: 'cf-edge-agent',
288 provider: cloudflareSandbox({
289 binding: env.Sandbox,
290 previewHostname: resolvePreviewHost(env, input),
291 }),
292 workspace: defineWorkspace({
293 source: { type: 'none' },
294 secrets: createSecrets({ XAI_API_KEY: env.XAI_API_KEY }),
295 }),
296 lifecycle: { reuse: 'thread' },
297 }),
298})
299```
300​
301> The runnable example lives at
302> [`examples/sandbox-cloudflare`](https://github.com/TanStack/ai/tree/main/examples/sandbox-cloudflare):
303> one app that runs Claude Code, Codex, or Grok Build — pick the harness in the
304> UI (or via the `HARNESS` var). Same edge topology, different adapter + key.
305​
306### Why a quick tunnel, not `exposePort`
307​
308`exposePort` + `proxyToSandbox` routes the preview through the Worker's own
309origin. In local dev that origin is your Vite dev server, and Vite's middleware
310then serves the preview's module/asset requests (`/@vite/client`, `/src/*`,
311`/@fs/*`) from your **host** instead of the container — the page loads the wrong
312code and breaks.
313​
314A quick tunnel is served by `cloudflared` **inside** the sandbox (`cloudflared`
315ships in the `cloudflare/sandbox` base image), so it bypasses the Vite port
316entirely, needs **no custom domain** on a deploy, and forwards WebSockets — so
317the app's HMR works. The one requirement, which `PREVIEW_GUIDANCE` instructs, is
318that the dev server **accept the tunnel hostname** (servers reject unknown
319hosts): Vite `server: { host: true, allowedHosts: true }`, webpack-dev-server
320`allowedHosts: 'all'`. (`exposePort` + `resolvePreviewHost` remain available for
321apps that want the Worker to front the request on a custom domain.)
322​
323> **Transport:** `sandbox.tunnels` exists only on the SDK's **RPC** transport —
324> on the default `http` it throws *"requires the RPC transport"*. So
325> `cloudflareSandbox` defaults to `transport: 'rpc'` (and the example also sets
326> `SANDBOX_TRANSPORT=rpc` for the Sandbox DO). The transport must match on every
327> `getSandbox()` for an id, so a custom provider must pass `{ transport: 'rpc' }`
328> too. Override to `'http'` only if you don't use tunnel previews.