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

provider.ts

115 lines3.9 KB

1import { getSandbox } from '@cloudflare/sandbox'
2import { CLOUDFLARE_CAPS, CloudflareHandle } from './handle'
3import type { Sandbox, SandboxTransport } from '@cloudflare/sandbox'
4import type {
5 SandboxCapabilities,
6 SandboxCreateInput,
7 SandboxDestroyInput,
8 SandboxHandle,
9 SandboxProvider,
10 SandboxResumeInput,
11} from '@tanstack/ai-sandbox'
12​
13const DEFAULT_WORKDIR = '/workspace'
14​
15export interface CloudflareSandboxConfig {
16 /**
17 * The Sandbox Durable Object namespace binding (e.g. `env.Sandbox`).
18 * Available inside a Worker `fetch` handler.
19 */
20 binding: DurableObjectNamespace<Sandbox>
21 /** Working directory inside the container. Defaults to `/workspace`. */
22 workdir?: string
23 /**
24 * Your Worker's request hostname, required by `ports.connect` to expose a
25 * preview URL (Cloudflare routes exposed ports by hostname).
26 */
27 previewHostname?: string
28 /**
29 * Container-control transport. Defaults to `'rpc'` (the SDK's primary path)
30 * because `sandbox.tunnels` — used by `exposePreviewTool` to mint quick-tunnel
31 * preview URLs — ONLY exists on the RPC transport; on `'http'`/`'websocket'` it
32 * throws "requires the RPC transport". The transport must be the same for every
33 * `getSandbox()` of a given id, so this provider applies it to create/resume/
34 * destroy alike. Override to `'http'` only if you don't use preview tunnels.
35 */
36 transport?: SandboxTransport
38​
39class CloudflareProvider implements SandboxProvider {
40 readonly name = 'cloudflare'
41​
42 constructor(private readonly config: CloudflareSandboxConfig) {}
43​
44 capabilities(): SandboxCapabilities {
45 return CLOUDFLARE_CAPS
46 }
47​
48 private get workdir(): string {
49 return this.config.workdir ?? DEFAULT_WORKDIR
50 }
51​
52 // `transport: 'rpc'` by default so `sandbox.tunnels` (preview URLs) works; must be
53 // identical across every `getSandbox()` for an id, so all three paths share this.
54 private get sandboxOptions(): { transport: SandboxTransport } {
55 return { transport: this.config.transport ?? 'rpc' }
56 }
57​
58 async create(input: SandboxCreateInput): Promise<SandboxHandle> {
59 // Honor the deterministic id `ensure()` supplies so reconnecting consumers
60 // (e.g. a preview iframe) address the same DO the agent edits. The DO id is
61 // `idFromName(id)`, so any stable string works; fall back to a random id
62 // when created outside `defineSandbox` (advanced direct use).
63 const id = input.id ?? crypto.randomUUID()
64 const sandbox = getSandbox(this.config.binding, id, this.sandboxOptions)
65 if (input.env && Object.keys(input.env).length > 0) {
66 await sandbox.setEnvVars(input.env)
67 }
68 await sandbox.mkdir(this.workdir, { recursive: true })
69 return new CloudflareHandle(
70 id,
71 sandbox,
72 this.workdir,
73 this.config.previewHostname,
74 )
75 }
76​
77 resume(input: SandboxResumeInput): Promise<SandboxHandle | null> {
78 // The Durable Object is durable, so the sandbox is always addressable by
79 // id. (The container disk may have been wiped on cold start — withSandbox
80 // re-bootstraps under the same identity when durableFilesystem is false.)
81 const sandbox = getSandbox(
82 this.config.binding,
83 input.id,
84 this.sandboxOptions,
85 )
86 return Promise.resolve(
87 new CloudflareHandle(
88 input.id,
89 sandbox,
90 this.workdir,
91 this.config.previewHostname,
92 ),
93 )
94 }
95​
96 async destroy(input: SandboxDestroyInput): Promise<void> {
97 const sandbox = getSandbox(
98 this.config.binding,
99 input.id,
100 this.sandboxOptions,
101 )
102 await sandbox.destroy()
103 }
105​
106/**
107 * Cloudflare sandbox provider — runs harness adapters inside Cloudflare
108 * Containers at the edge. Construct it inside a Worker with the Sandbox Durable
109 * Object namespace binding. See the stdin/snapshot limitations in `handle.ts`.
110 */
111export function cloudflareSandbox(
112 config: CloudflareSandboxConfig,
113): SandboxProvider {
114 return new CloudflareProvider(config)