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

factory.ts

239 lines10.3 KB

1/**
2 * `createCloudflareSandboxAgent` — the headline DX: one configured function call
3 * returns the Durable Object coordinator, the Sandbox DO, and the Worker fetch
4 * handler, so a Cloudflare app's whole `worker.ts` is just export wiring:
5 *
6 * ```ts
7 * const agent = createCloudflareSandboxAgent({
8 * adapter: () => claudeCodeText('sonnet'),
9 * })
10 * export const RunCoordinator = agent.Coordinator
11 * export const Sandbox = agent.Sandbox
12 * export default agent.worker
13 * ```
14 *
15 * Two modes, switched by `config.mode`:
16 * - `'do-drives'` (default) → a {@link ChatSandboxCoordinator}: the DO runs
17 * `chat()` itself and hosts the MCP tool-bridge.
18 * - `'colocated'` → a {@link ContainerSandboxCoordinator}: an in-container
19 * runner runs `chat()`; the DO is a thin coordinator that executes host tools.
20 *
21 * Env bindings (set in `wrangler.jsonc`):
22 * - `RUN_COORDINATOR` — this coordinator DO's own namespace (so the Worker can
23 * address it by `threadId`). Class name: whatever you export `Coordinator` as.
24 * - `Sandbox` — the `@cloudflare/sandbox` Sandbox DO namespace (the container
25 * hosts). Bind the exported `Sandbox` class.
26 * - `PUBLIC_HOSTNAME` — OPTIONAL. Hostname the CONTAINER uses to reach the Worker's
27 * tool-bridge / tool-exec endpoint. Unset → request-derived (local dev →
28 * `host.docker.internal`). See `resolveBridgeOrigin`.
29 * - `PREVIEW_HOSTNAME` — OPTIONAL. Custom domain (with a `*.<domain>` route) for
30 * browser-facing `exposePort` preview URLs. Unset → request-derived (local dev →
31 * `localhost`); REQUIRED on a `*.workers.dev` deploy, which has no wildcard
32 * subdomains. See `resolvePreviewHost`.
33 * - The harness's API key (`ANTHROPIC_API_KEY` for Claude Code, `CODEX_API_KEY` for
34 * codex, …) — supplied by YOUR app, never by the package. Declare it as a secret
35 * on the run's workspace (via a `sandbox`/`workspace` resolver) and add the field
36 * to your own env type; the coordinator injects each declared secret into the
37 * sandbox env by name. The package itself is harness-agnostic and binds no key.
38 *
39 * NOTE: Workers-runtime code — compiles against the real Cloudflare + TanStack
40 * AI types; not runtime-verified in this repo (no Workers runtime here).
41 */
42import { defineSandbox, defineWorkspace } from '@tanstack/ai-sandbox'
43import { Sandbox } from '@cloudflare/sandbox'
44import { cloudflareSandbox } from './provider'
45import { ChatSandboxCoordinator } from './chat-coordinator'
46import { ContainerSandboxCoordinator } from './container-coordinator'
47import { createSandboxAgentWorker } from './worker'
48import { normalizeStallTimeoutMs, resolvePreviewHost } from './coordinator'
49import type { ChatCoordinatorEnv, ChatRunConfig } from './chat-coordinator'
50import type {
51 ContainerCoordinatorEnv,
52 ContainerRunConfig,
53} from './container-coordinator'
54import type { HarnessId } from './protocol'
55import type { SandboxCoordinator, StartRunInput } from './coordinator'
56import type { AnyTextAdapter, AnyTool, SystemPrompt } from '@tanstack/ai'
57import type {
58 SandboxDefinition,
59 WorkspaceDefinition,
60} from '@tanstack/ai-sandbox'
61​
62/**
63 * The base Env every generated app binds: the coordinator's own namespace, the
64 * Sandbox namespace, the OPTIONAL bridge/preview hostnames (request-derived when
65 * unset), and the Anthropic key. The two modes extend this with exactly the
66 * coordinator base each one requires.
67 */
68export interface SandboxAgentEnv
69 extends ChatCoordinatorEnv, ContainerCoordinatorEnv {
70 /** This coordinator DO's own namespace (so the Worker can address it). */
71 RUN_COORDINATOR: DurableObjectNamespace<SandboxCoordinator<SandboxAgentEnv>>
72 /**
73 * Custom domain (with a `*.<domain>` route) for browser-facing `exposePort`
74 * preview URLs. Optional: unset → request-derived (local dev → `localhost`).
75 * REQUIRED on a `*.workers.dev` deploy (no wildcard subdomains). Distinct from
76 * `PUBLIC_HOSTNAME`, which is the CONTAINER→Worker bridge host. See
77 * {@link resolvePreviewHost}.
78 */
79 PREVIEW_HOSTNAME?: string
81​
82/** Shared config across both modes. */
83interface BaseAgentConfig<TEnv extends SandboxAgentEnv> {
84 /** chat()-provided server tools, resolved per run (DO-drives: bridged over MCP). */
85 tools?: (input: StartRunInput, env: TEnv) => Array<AnyTool>
86 /**
87 * Fail a run after this many milliseconds without persisted activity. Omitted
88 * defaults to five minutes; `false` disables the watchdog.
89 */
90 stallTimeoutMs?: number | false
92​
93/** DO-drives config: the DO runs `chat()` with the given adapter. */
94export interface DoDrivesAgentConfig<
95 TEnv extends SandboxAgentEnv,
96> extends BaseAgentConfig<TEnv> {
97 mode?: 'do-drives'
98 /** The harness/text adapter `chat()` runs, resolved per run. */
99 adapter: (input: StartRunInput, env: TEnv) => AnyTextAdapter
100 /**
101 * Base system prompts prepended to every run's `chat()` (DO-drives only — the DO
102 * runs `chat()` itself). The natural home for transport-level guidance the agent
103 * needs regardless of what it builds — e.g. `systemPrompts: [PREVIEW_GUIDANCE]`
104 * so previews don't reload-loop. See {@link PREVIEW_GUIDANCE}.
105 */
106 systemPrompts?: Array<SystemPrompt>
107 /**
108 * The sandbox the agent runs in, resolved per run. When omitted, a default
109 * Cloudflare sandbox (one per thread, no source clone, NO auth secrets) is built
110 * from the `Sandbox` binding and the resolved preview host, optionally
111 * bootstrapping `workspace`. Supply the harness's API key either here (a custom
112 * `sandbox` resolver whose workspace declares the secret) or via `workspace`
113 * below — the package binds no key of its own.
114 */
115 sandbox?: (input: StartRunInput, env: TEnv) => SandboxDefinition
116 /**
117 * Workspace for the default sandbox (ignored when `sandbox` is provided). This is
118 * where a default-sandbox app declares its harness auth, e.g.
119 * `defineWorkspace({ source: { type: 'none' }, secrets: createSecrets({ ANTHROPIC_API_KEY: env.ANTHROPIC_API_KEY }) })`.
120 */
121 workspace?: WorkspaceDefinition
123​
124/** Co-located config: an in-container runner runs `chat()`. */
125export interface ColocatedAgentConfig<
126 TEnv extends SandboxAgentEnv,
127> extends BaseAgentConfig<TEnv> {
128 mode: 'colocated'
129 /** Which in-sandbox harness the runner spawns. */
130 harness: HarnessId
131 /** Model id passed to that harness. */
132 model: string
133 /** Workspace the in-container runner bootstraps for the agent. */
134 workspace: WorkspaceDefinition
136​
137export type CloudflareSandboxAgentConfig<TEnv extends SandboxAgentEnv> =
138 | DoDrivesAgentConfig<TEnv>
139 | ColocatedAgentConfig<TEnv>
140​
141/** What {@link createCloudflareSandboxAgent} returns: the app's whole worker. */
142export interface CloudflareSandboxAgent<TEnv extends SandboxAgentEnv> {
143 /** The coordinator Durable Object class — export as your `RUN_COORDINATOR` binding. */
144 Coordinator: new (
145 ctx: DurableObjectState,
146 env: TEnv,
147 ) => SandboxCoordinator<TEnv>
148 /** The `@cloudflare/sandbox` Sandbox DO class — export for the `Sandbox` binding. */
149 Sandbox: typeof Sandbox
150 /** The Worker fetch handler — `export default` it. */
151 worker: ExportedHandler<TEnv>
153​
154/** Build the default per-thread Cloudflare sandbox for the DO-drives mode. */
155function defaultSandbox<TEnv extends SandboxAgentEnv>(
156 env: TEnv,
157 input: StartRunInput,
158 workspace: WorkspaceDefinition | undefined,
159): SandboxDefinition {
160 return defineSandbox({
161 id: 'cf-edge-agent',
162 provider: cloudflareSandbox({
163 binding: env.Sandbox,
164 // Browser-facing preview host: `PREVIEW_HOSTNAME` if set, else derived from
165 // the trigger request (local dev → `localhost`; deployed → a custom domain,
166 // since `*.workers.dev` has no wildcard). See `resolvePreviewHost`.
167 previewHostname: resolvePreviewHost(env, input),
168 }),
169 workspace:
170 workspace ??
171 // The container image ships the harness CLI; no source to clone, and NO auth
172 // secrets — the package is harness-agnostic, so it can't know which key the
173 // CLI needs. Supply the harness's API key via a `workspace` with `secrets`
174 // (or a custom `sandbox` resolver), e.g.:
175 // workspace: defineWorkspace({
176 // source: { type: 'none' },
177 // secrets: createSecrets({ ANTHROPIC_API_KEY: env.ANTHROPIC_API_KEY }),
178 // })
179 defineWorkspace({ source: { type: 'none' } }),
180 // One sandbox per thread, so a follow-up run resumes the same workspace.
181 lifecycle: { reuse: 'thread' },
182 })
184​
185/** Resolve the coordinator DO that owns a thread's runs (`RUN_COORDINATOR`). */
186function resolveCoordinator<TEnv extends SandboxAgentEnv>(
187 env: TEnv,
188 threadId: string,
189): DurableObjectStub<SandboxCoordinator<TEnv>> {
190 return env.RUN_COORDINATOR.get(env.RUN_COORDINATOR.idFromName(threadId))
192​
193export function createCloudflareSandboxAgent<
194 TEnv extends SandboxAgentEnv = SandboxAgentEnv,
195>(config: CloudflareSandboxAgentConfig<TEnv>): CloudflareSandboxAgent<TEnv> {
196 const stallTimeoutMs = normalizeStallTimeoutMs(config.stallTimeoutMs)
197 const worker = createSandboxAgentWorker<TEnv>(resolveCoordinator)
198​
199 if (config.mode === 'colocated') {
200 const colocated = config
201 class ConfiguredContainerCoordinator extends ContainerSandboxCoordinator<TEnv> {
202 constructor(ctx: DurableObjectState, env: TEnv) {
203 super(ctx, env, stallTimeoutMs)
204 }
205​
206 protected override config(input: StartRunInput): ContainerRunConfig {
207 return {
208 hostTools: colocated.tools?.(input, this.env) ?? [],
209 workspace: colocated.workspace,
210 harness: colocated.harness,
211 model: colocated.model,
212 }
213 }
214 }
215 return { Coordinator: ConfiguredContainerCoordinator, Sandbox, worker }
216 }
217​
218 const doDrives = config
219 class ConfiguredChatCoordinator extends ChatSandboxCoordinator<TEnv> {
220 constructor(ctx: DurableObjectState, env: TEnv) {
221 super(ctx, env, stallTimeoutMs)
222 }
223​
224 protected override config(input: StartRunInput): ChatRunConfig {
225 const tools = doDrives.tools?.(input, this.env)
226 return {
227 adapter: doDrives.adapter(input, this.env),
228 sandbox:
229 doDrives.sandbox?.(input, this.env) ??
230 defaultSandbox(this.env, input, doDrives.workspace),
231 ...(tools !== undefined ? { tools } : {}),
232 ...(doDrives.systemPrompts !== undefined
233 ? { systemPrompts: doDrives.systemPrompts }
234 : {}),
235 }
236 }
237 }
238 return { Coordinator: ConfiguredChatCoordinator, Sandbox, worker }