Open History to see the last commit
1/**
2 * `namedCloudflareSandbox` — like the package's `cloudflareSandbox()` provider, but
3 * pins the container Durable Object to a KNOWN name instead of a random UUID.
4 *
5 * Why: to show the app the agent builds, the `exposePreview` host tool opens a quick
6 * tunnel via `getSandbox(binding, threadId).tunnels.get(port)`. That has to target
7 * the SAME container the agent's dev server runs in — so the host needs to address
8 * it by a name it knows. The default provider names the container with a random
9 * UUID the host never sees; this one names it deterministically (we pass the run's
10 * `threadId`), so the tool reaches the same container.
11 *
12 * Pinning by `threadId` is also strictly better for `reuse: 'thread'`: the container
13 * is addressable across Durable Object eviction, not just within one live instance.
14 */
15import { getSandbox } from '@cloudflare/sandbox'
16import {
17 CLOUDFLARE_CAPS,
18 CloudflareHandle,
19} from '@tanstack/ai-sandbox-cloudflare'
20import type { Sandbox } from '@cloudflare/sandbox'
21import type {
22 SandboxCreateInput,
23 SandboxDestroyInput,
24 SandboxHandle,
25 SandboxProvider,
26 SandboxResumeInput,
27} from '@tanstack/ai-sandbox'
28
29const WORKDIR = '/workspace'
30
31// `sandbox.tunnels` (preview URLs) only exists on the RPC transport, and the
32// transport must be identical for every `getSandbox()` of an id — so create,
33// resume, and destroy all pass it. (The package's own `cloudflareSandbox` provider
34// defaults to `'rpc'` for the same reason; this custom provider mirrors it.)
35const SANDBOX_OPTIONS = { transport: 'rpc' } as const
36
37export function namedCloudflareSandbox(
38 binding: DurableObjectNamespace<Sandbox>,
39 name: string,
40 previewHostname?: string,
41): SandboxProvider {
42 return {
43 name: 'cloudflare-named',
44 capabilities: () => CLOUDFLARE_CAPS,
45 async create(input: SandboxCreateInput): Promise<SandboxHandle> {
46 const sandbox = getSandbox(binding, name, SANDBOX_OPTIONS)
47 if (input.env && Object.keys(input.env).length > 0) {
48 await sandbox.setEnvVars(input.env)
49 }
50 await sandbox.mkdir(WORKDIR, { recursive: true })
51 return new CloudflareHandle(name, sandbox, WORKDIR, previewHostname)
52 },
53 resume: (input: SandboxResumeInput): Promise<SandboxHandle> =>
54 Promise.resolve(
55 new CloudflareHandle(
56 input.id,
57 getSandbox(binding, input.id, SANDBOX_OPTIONS),
58 WORKDIR,
59 previewHostname,
60 ),
61 ),
62 async destroy(input: SandboxDestroyInput): Promise<void> {
63 await getSandbox(binding, input.id, SANDBOX_OPTIONS).destroy()
64 },
65 }
66}