Open History to see the last commit
1/**
2 * The sandbox agent — ONE fixed stack: **Claude Code** (the `claude` CLI)
3 * running in a **Docker** sandbox. Ask it to build a self-contained TanStack
4 * Start app; it scaffolds inside the sandbox, runs the dev server, and hands
5 * back a live preview URL.
6 *
7 * The stack is deliberately not configurable. This app is the runnable demo of
8 * [durable runs](../../../docs/sandbox/durable-runs.md), and durability's one
9 * hard requirement is that a run be reconstructible from its `runId` alone (the
10 * takeover route and the reaper have nothing else) — a fixed stack makes that
11 * rebuild trivial (see `run-durable.ts`). For the same wiring switched across
12 * harnesses live in the UI, see `examples/sandbox-cloudflare`.
13 *
14 * Docker is same-machine, so host tools (`tanstackStartRecipe`,
15 * `exposePreview`) are BRIDGED into the agent over MCP and it mints the preview
16 * URL on demand once its dev server is up.
17 */
18import { toolDefinition } from '@tanstack/ai'
19import { claudeCodeText } from '@tanstack/ai-claude-code'
20import {
21 createSecrets,
22 defineSandbox,
23 defineWorkspace,
24} from '@tanstack/ai-sandbox'
25import { dockerSandbox } from '@tanstack/ai-sandbox-docker'
26import { z } from 'zod'
27import type { AnyTextAdapter } from '@tanstack/ai'
28import type {
29 SandboxDefinition,
30 SandboxEnsureContext,
31} from '@tanstack/ai-sandbox'
32
33/** Docker base image override (`node:22` ships node + npm + git). */
34const SANDBOX_IMAGE = process.env.SANDBOX_IMAGE ?? 'node:22'
35
36/** The model the in-sandbox `claude` CLI runs. */
37export const CLAUDE_MODEL = 'claude-opus-4-8'
38
39/**
40 * Installs the Claude Code CLI in the fresh container.
41 *
42 * `--include=optional` matters: without it npm may skip the platform-specific
43 * native binary, leaving a `claude` that errors "native binary not installed".
44 * But npm treats optional deps as BEST-EFFORT even so — a transient failure
45 * fetching that binary is not an install error, so npm exits 0 and the break
46 * only surfaces later, mid-run. Running `claude --version` here turns it into a
47 * loud setup failure, and retrying the install once absorbs the transient case.
48 */
49const CLAUDE_CLI_INSTALL_COMMAND = (() => {
50 const attempt =
51 'npm install -g @anthropic-ai/claude-code --include=optional && claude --version'
52 return `${attempt} || { ${attempt} ; }`
53})()
54
55/**
56 * The ONE dev-server port the agent's app must bind. The preview is wired to
57 * exactly this port (published at create), so the recipe + guidance below tell
58 * the agent to use it.
59 */
60export const PREVIEW_PORT = 5173
61
62/**
63 * The harness adapter `chat()` runs. Claude Code's one spawn path is the
64 * journaling NDJSON stream (`claude -p --output-format stream-json`), so
65 * durable runs need no protocol override — a detached run's journal is always
66 * there to take over.
67 */
68export function buildAdapter(): AnyTextAdapter {
69 return claudeCodeText(CLAUDE_MODEL)
70}
71
72/**
73 * Required env vars that are not set. The `claude` CLI authenticates
74 * headlessly via `ANTHROPIC_API_KEY`.
75 */
76export function missingEnv(): Array<string> {
77 return process.env.ANTHROPIC_API_KEY ? [] : ['ANTHROPIC_API_KEY']
78}
79
80// ---------------------------------------------------------------------------
81// Scaffolding recipe + preview guidance
82// ---------------------------------------------------------------------------
83
84const SCAFFOLD =
85 'Scaffold with the TanStack CLI via npx (no global install needed — run it EXACTLY like this): `npx --yes @tanstack/cli create my-app --framework react --no-examples --intent -y`. The package is `@tanstack/cli` (it ships the `tanstack` bin); do NOT guess other package names. `--intent` writes TanStack Intent agent-skill mappings for coding agents. This creates a TanStack Start app and installs deps. (Add `--no-install` to skip install, or `--add-ons <id,…>` for integrations — but keep it env-free; do NOT add auth/database add-ons that need keys.)'
86
87const APP =
88 'Turn it into a SELF-CONTAINED interactive app — NO external APIs, NO env vars, NO keys. Pick something visual: a kanban board, a sortable dashboard over a bundled data.json, a markdown notepad, a drawing pad, or a small game (e.g. Game of Life). Keep all state client-side (persist to localStorage). Make it look polished.'
89
90/** Run step: bind wide, then call `exposePreview` for the URL. */
91const RUN = `FIRST, so the published host port reaches the dev server, add \`server: { host: true, allowedHosts: true }\` to the app's \`vite.config.ts\` (bind all interfaces + accept any host). THEN start the dev server bound to all interfaces on PORT ${PREVIEW_PORT} — it MUST be ${PREVIEW_PORT}, because that is the port wired to the preview: \`pnpm dev --host 0.0.0.0 --port ${PREVIEW_PORT}\` (or \`npm run dev -- --host 0.0.0.0 --port ${PREVIEW_PORT}\`). Once it is listening, call the \`exposePreview\` tool with \`{ "port": ${PREVIEW_PORT} }\` to get a preview URL and share it with the user. The app runs with ZERO configuration — no API keys or env needed.`
92
93/**
94 * The recipe as a bridged host tool. The agent sees it over MCP and calls it
95 * BEFORE scaffolding.
96 */
97export const tanstackStartRecipe = toolDefinition({
98 name: 'tanstackStartRecipe',
99 description:
100 'The canonical recipe for building a self-contained TanStack Start app in this sandbox that runs with no env or API keys: scaffold via `npx --yes @tanstack/cli create … --intent`, what to build, and how to bind/expose the dev server for a preview URL. Call this BEFORE scaffolding.',
101 inputSchema: z.object({
102 section: z
103 .enum(['scaffold', 'app', 'run', 'all'])
104 .describe('Which part of the recipe you need (use "all" first).'),
105 }),
106}).server(({ section }) => {
107 const recipe = { scaffold: SCAFFOLD, app: APP, run: RUN }
108 return section === 'all' ? recipe : { [section]: recipe[section] }
109})
110
111/**
112 * System-prompt preview guidance: bind wide on {@link PREVIEW_PORT}, then call
113 * `exposePreview` for the URL.
114 */
115export const PREVIEW_GUIDANCE: string = [
116 'PREVIEW SERVERS: to show the user a running web app, start its dev server bound',
117 `to 0.0.0.0 on port ${PREVIEW_PORT} (this is the ONLY port exposed to the host, so`,
118 `it must be ${PREVIEW_PORT}), then call the \`exposePreview\` tool with`,
119 `\`{ "port": ${PREVIEW_PORT} }\`. It returns a preview URL the user can open.`,
120 'Bind all interfaces and allow all hosts in the dev-server config before starting:',
121 '• Vite — `server: { host: true, allowedHosts: true }` in vite.config.',
122 "• webpack-dev-server — `allowedHosts: 'all'` (and `host: '0.0.0.0'`).",
123 'Once it is listening, call `exposePreview`, then share the URL.',
124].join('\n')
125
126// ---------------------------------------------------------------------------
127// The sandbox definition
128// ---------------------------------------------------------------------------
129
130/** One sandbox per thread (`reuse: 'thread'`), rebuildable from the threadId. */
131export function buildSandbox(threadId: string): SandboxDefinition {
132 const key = process.env.ANTHROPIC_API_KEY
133 return defineSandbox({
134 id: `sandbox-web-${threadId}`,
135 provider: dockerSandbox({
136 image: SANDBOX_IMAGE,
137 // The preview port, published at create.
138 publishPorts: [PREVIEW_PORT],
139 }),
140 workspace: defineWorkspace({
141 // No source to clone — the agent scaffolds a fresh app.
142 source: { type: 'none' },
143 setup: ({ serial }) => serial(CLAUDE_CLI_INSTALL_COMMAND),
144 secrets: createSecrets(key ? { ANTHROPIC_API_KEY: key } : {}),
145 }),
146 lifecycle: { reuse: 'thread' },
147 })
148}
149
150/**
151 * The `exposePreview` server tool for one run. Minting a preview URL is a
152 * HOST-side call (`handle.ports.connect`), so the in-sandbox agent calls this
153 * bridged tool instead. Resumes the run's sandbox by `threadId` (a no-op
154 * `ensure`, since `withSandbox` already created it) and resolves the host-port
155 * URL.
156 */
157export function makeExposePreviewTool(
158 definition: SandboxDefinition,
159 threadId: string,
160 // The caller's shared instance bookkeeping, so this resolves the run's REAL
161 // sandbox instead of minting a fresh one (a definition's fallback store is
162 // per-definition, and definitions are rebuilt per request).
163 bookkeeping?: Pick<SandboxEnsureContext, 'store' | 'locks'>,
164) {
165 return toolDefinition({
166 name: 'exposePreview',
167 description: `Expose a port a dev server is listening on inside the sandbox and return a preview URL to show the user. Call this AFTER the server is up and listening on port ${PREVIEW_PORT}.`,
168 inputSchema: z.object({
169 port: z
170 .number()
171 .int()
172 .min(1024)
173 .max(65535)
174 .describe(
175 `The port the dev server is listening on, e.g. ${PREVIEW_PORT}.`,
176 ),
177 }),
178 }).server(async ({ port }) => {
179 const handle = await definition.ensure({
180 threadId,
181 runId: 'expose-preview',
182 ...bookkeeping,
183 })
184 const channel = await handle.ports.connect(port)
185 return { url: channel.url }
186 })
187}