Open History to see the last commit
1/**
2 * The browser-preview capability, as reusable building blocks rather than
3 * per-app glue: a `chat()` server tool that mints a preview URL for a dev server
4 * running inside the sandbox, plus the system-prompt guidance an agent needs to
5 * produce a preview that works.
6 *
7 * Previews go over a **Cloudflare quick tunnel** (`sandbox.tunnels.get(port)` →
8 * `https://<name>.trycloudflare.com`), served by `cloudflared` INSIDE the sandbox.
9 * We deliberately do NOT use `exposePort` + `proxyToSandbox` here: that routes the
10 * preview through the Worker's own origin, which in local dev is the example's Vite
11 * dev server — and Vite's middleware then serves the preview's module/asset
12 * requests (`/@vite/client`, `/src/*`, `/@fs/*`) from the HOST instead of the
13 * container, breaking the page. A tunnel bypasses the Vite port entirely, needs no
14 * custom domain on a deploy, and forwards WebSockets (so the app's HMR works).
15 *
16 * Both exports belong to THIS package because the transport is its concern, not any
17 * particular app's. Wire them explicitly into your agent:
18 *
19 * ```ts
20 * import {
21 * exposePreviewTool,
22 * PREVIEW_GUIDANCE,
23 * } from '@tanstack/ai-sandbox-cloudflare/agent'
24 *
25 * createCloudflareSandboxAgent({
26 * adapter: () => claudeCodeText('sonnet'),
27 * tools: (input, env) => [exposePreviewTool(input, env)],
28 * systemPrompts: [PREVIEW_GUIDANCE],
29 * })
30 * ```
31 *
32 * Workers-only (imports `@cloudflare/sandbox`) — exported from the `/agent` entry.
33 */
34import { toolDefinition } from '@tanstack/ai'
35import { z } from 'zod'
36import { getSandbox } from '@cloudflare/sandbox'
37import type { Sandbox } from '@cloudflare/sandbox'
38import type { StartRunInput } from './coordinator'
39
40/**
41 * The minimum env an {@link exposePreviewTool} needs: the Sandbox namespace it
42 * addresses the run's container in. `SandboxAgentEnv` satisfies this structurally,
43 * so the factory's `tools` resolver passes its env straight in.
44 */
45export interface PreviewToolEnv {
46 Sandbox: DurableObjectNamespace<Sandbox>
47}
48
49/**
50 * System-prompt guidance for any agent that exposes a dev server as a browser
51 * preview. App-agnostic: the only requirement a quick tunnel imposes is that the
52 * dev server accept the tunnel hostname (Vite/webpack reject unknown hosts by
53 * default), so the rule is "bind wide + allow all hosts", not "disable HMR" — the
54 * tunnel forwards WebSockets, so HMR works.
55 */
56export const PREVIEW_GUIDANCE: string = [
57 'PREVIEW SERVERS: to show the user a running web app, start its dev server bound',
58 'to 0.0.0.0 on a port OTHER than 3000 (3000 is reserved by the sandbox control',
59 'plane), then call the `exposePreview` tool with that port. It returns a public',
60 'Cloudflare quick-tunnel URL (https://<name>.trycloudflare.com) served straight',
61 'from the sandbox — no custom domain needed, and HMR / live-reload WebSockets',
62 'work through the tunnel (you do NOT need to disable HMR). The ONE requirement:',
63 'the dev server must ACCEPT the tunnel hostname, which servers reject by default,',
64 'so allow all hosts in its config before starting:',
65 '• Vite — `server: { host: true, allowedHosts: true }` in vite.config.',
66 "• webpack-dev-server — `allowedHosts: 'all'` (and `host: '0.0.0.0'`).",
67 '• Other dev servers — bind 0.0.0.0 and allow all hosts equivalently.',
68 'Once it is listening, call `exposePreview` with that port, then share the URL.',
69].join('\n')
70
71const LOCAL_PROBE_TIMEOUT_MS = 5_000
72// Fresh quick tunnels need a few seconds of DNS/edge propagation, hence retries.
73const EDGE_PROBE_ATTEMPTS = 5
74const EDGE_PROBE_BASE_DELAY_MS = 250
75const EDGE_PROBE_FETCH_TIMEOUT_MS = 3_000
76
77/**
78 * Probe the port INSIDE the sandbox via `containerFetch`. Returns the HTTP
79 * status when a listener answered (any response — 4xx/5xx included — proves one
80 * exists), or the failure symptom (a string) when nothing did.
81 */
82async function localProbe(
83 sandbox: Sandbox,
84 port: number,
85): Promise<number | string> {
86 // A race instead of AbortSignal: signals don't serialize across the sandbox
87 // RPC boundary, and a lost in-flight probe response is harmless.
88 let timeoutId: ReturnType<typeof setTimeout> | undefined
89 const timeout = new Promise<never>((_, reject) => {
90 timeoutId = setTimeout(
91 () => reject(new Error(`no response within ${LOCAL_PROBE_TIMEOUT_MS}ms`)),
92 LOCAL_PROBE_TIMEOUT_MS,
93 )
94 })
95 try {
96 const res = await Promise.race([
97 sandbox.containerFetch('http://preview/', { method: 'HEAD' }, port),
98 timeout,
99 ])
100 return res.status
101 } catch (error) {
102 return error instanceof Error ? error.message : String(error)
103 } finally {
104 clearTimeout(timeoutId)
105 }
106}
107
108/**
109 * Probe a tunnel URL through the public edge with bounded retries. Only 502/530
110 * — Cloudflare's tunnel/origin-unreachable signatures — mark the URL as
111 * unreachable (401/403/404 prove the server answered, and `redirect: 'manual'`
112 * keeps a login redirect from probing some other site), and even those are
113 * trusted when the app answered the SAME status locally, so an app's own
114 * 502/530 never gets its healthy tunnel destroyed. The verdict split exists
115 * because only an OBSERVED non-matching 502/530 ('stale') is evidence that
116 * justifies destroying the tunnel; fetch exceptions ('unverified') prove
117 * nothing about it — the probe path itself may be what failed. A throw
118 * anywhere in the retry window therefore wins over an earlier 502/530: the
119 * window did not finish as HTTP probes, so we must not destroy.
120 */
121async function edgeProbeFailure(
122 url: string,
123 localStatus: number,
124): Promise<{ verdict: 'stale' | 'unverified'; symptom: string } | null> {
125 let lastFailure = 'no response'
126 let verdict: 'stale' | 'unverified' = 'unverified'
127 let sawFetchException = false
128 for (let attempt = 0; attempt < EDGE_PROBE_ATTEMPTS; attempt += 1) {
129 if (attempt > 0) {
130 await new Promise((resolve) =>
131 setTimeout(resolve, EDGE_PROBE_BASE_DELAY_MS * 2 ** (attempt - 1)),
132 )
133 }
134 try {
135 const res = await fetch(url, {
136 method: 'HEAD',
137 redirect: 'manual',
138 signal: AbortSignal.timeout(EDGE_PROBE_FETCH_TIMEOUT_MS),
139 })
140 if (
141 (res.status !== 502 && res.status !== 530) ||
142 res.status === localStatus
143 ) {
144 return null
145 }
146 lastFailure = `HTTP ${res.status}`
147 verdict = 'stale'
148 } catch (error) {
149 sawFetchException = true
150 lastFailure = error instanceof Error ? error.message : String(error)
151 }
152 }
153 return {
154 verdict: sawFetchException ? 'unverified' : verdict,
155 symptom: lastFailure,
156 }
157}
158
159/**
160 * Build the `exposePreview` server tool for one run. Starting a tunnel is a
161 * HOST-side call on the Sandbox DO stub, so an in-sandbox agent cannot make it from
162 * bash — it calls this bridged tool instead. We address the run's container by
163 * `threadId` and open (or reuse) a quick tunnel to the given port.
164 *
165 * Closes over the run's `input` + `env`, so build it inside the `tools` resolver
166 * (`tools: (input, env) => [exposePreviewTool(input, env)]`).
167 */
168export function exposePreviewTool(input: StartRunInput, env: PreviewToolEnv) {
169 return toolDefinition({
170 name: 'exposePreview',
171 description:
172 'Expose a port a dev server is listening on inside the sandbox and return a public preview URL (a Cloudflare quick tunnel) to show the user. Call this AFTER the server is up. The dev server must allow all hosts (e.g. Vite `server.allowedHosts: true`) so it accepts the tunnel hostname.',
173 inputSchema: z.object({
174 port: z
175 .number()
176 .int()
177 .min(1024)
178 .max(65535)
179 .describe('The port the dev server is listening on, e.g. 5173.'),
180 }),
181 }).server(async ({ port }) => {
182 // `sandbox.tunnels` only exists on the RPC transport (on HTTP/WebSocket it's a
183 // stub that throws "requires the RPC transport"), so we must obtain the stub
184 // with `transport: 'rpc'`. IMPORTANT: this must MATCH how the sandbox was
185 // created — pass `transport: 'rpc'` on EVERY `getSandbox()` for this id (in your
186 // sandbox provider too), or the differing transport disconnects the run's active
187 // client. See the SDK `SandboxOptions.transport` note.
188 const sandbox = getSandbox(env.Sandbox, input.threadId, {
189 transport: 'rpc',
190 })
191 // Gate tunnel work on a live listener: a fresh tunnel to a dead port is still
192 // a dead preview, and the failure the agent can FIX is "start the server".
193 const local = await localProbe(sandbox, port)
194 if (typeof local === 'string') {
195 throw new Error(
196 `No server is listening on port ${port} inside the sandbox (${local}). Start the dev server (bound to 0.0.0.0:${port}) first, then retry exposePreview.`,
197 )
198 }
199 // A Cloudflare quick tunnel (`*.trycloudflare.com`) run by `cloudflared` INSIDE
200 // the sandbox: it bypasses the local Vite dev server's port entirely (so Vite
201 // can't hijack the preview's asset requests) and needs no custom domain on a
202 // deploy. `get(port)` is idempotent per port. See the Sandbox SDK `tunnels` API.
203 const tunnel = await sandbox.tunnels.get(port)
204 const edgeFailure = await edgeProbeFailure(tunnel.url, local)
205 if (edgeFailure === null) return { url: tunnel.url }
206 // Never destroy on 'unverified': the tunnel may be healthy with only the
207 // probe path broken, so destroying it could kill a working preview.
208 if (edgeFailure.verdict === 'unverified') {
209 throw new Error(
210 `Port ${port} is serving inside the sandbox, but the preview tunnel could not be verified from the edge (${edgeFailure.symptom}). The tunnel was left in place — retry exposePreview in a few seconds.`,
211 )
212 }
213 // Local server healthy but the edge kept answering 502/530: the cached tunnel
214 // record is suspect. Refresh, bounded to ONE so we never churn tunnels.
215 await sandbox.tunnels.destroy(port)
216 const fresh = await sandbox.tunnels.get(port)
217 const freshFailure = await edgeProbeFailure(fresh.url, local)
218 if (freshFailure === null) {
219 return {
220 url: fresh.url,
221 note: `The tunnel for port ${port} was stale, so it was replaced. Any previously shared preview URL for this port is dead — share this new URL instead.`,
222 }
223 }
224 // Don't leave a known-dead record in DO storage (the #992 failure mode).
225 if (freshFailure.verdict === 'stale') {
226 await sandbox.tunnels.destroy(port)
227 }
228 const [diagnosis, hint] =
229 freshFailure.verdict === 'stale'
230 ? [
231 'its preview tunnel never became reachable',
232 'Retry exposePreview, and if it keeps failing, restart the dev server and try again.',
233 ]
234 : [
235 'the replacement preview tunnel could not be verified from the edge',
236 'Retry exposePreview in a few seconds.',
237 ]
238 throw new Error(
239 `Port ${port} is serving inside the sandbox, but ${diagnosis} (old tunnel: ${edgeFailure.symptom}; replacement tunnel: ${freshFailure.symptom}). ${hint}`,
240 )
241 })
242}