Open History to see the last commit
1import Dockerode from 'dockerode'
2import { DOCKER_CAPS, DockerHandle } from './handle'
3import { copyLocalSource, readLocalSource } from './local-source'
4import type { DockerLogger } from './handle'
5import type { LocalSource } from './local-source'
6import type {
7 SandboxCapabilities,
8 SandboxCreateInput,
9 SandboxDestroyInput,
10 SandboxHandle,
11 SandboxProvider,
12 SandboxRestoreInput,
13 SandboxResumeInput,
14} from '@tanstack/ai-sandbox'
15
16export interface DockerSandboxConfig {
17 /** Image to run, e.g. `node:22`. Pulled automatically if absent locally. */
18 image: string
19 /** Working directory inside the container. Defaults to `/workspace`. */
20 workdir?: string
21 /** Options forwarded to `new Dockerode(...)` (socketPath, host, port, …). */
22 dockerodeOptions?: Dockerode.DockerOptions
23 /** Command that keeps the container alive. Defaults to `tail -f /dev/null`. */
24 keepAliveCommand?: Array<string>
25 /** Container ports to publish to the host (for `ports.connect`). */
26 publishPorts?: Array<number>
27 /**
28 * Add `host.docker.internal:host-gateway` so the container can reach the
29 * host (e.g. a host-side MCP tool-bridge). Defaults to true.
30 */
31 hostGateway?: boolean
32 /** Remove the container on destroy (vs. just stop). Defaults to true. */
33 removeOnDestroy?: boolean
34 /**
35 * Sink for non-fatal teardown diagnostics — a container-side kill that was
36 * refused, or a process that survived it. Teardown never throws, so without a
37 * logger such a failure is silent and this provider's
38 * `killableProcesses: true` claim cannot be checked. `@tanstack/ai`'s
39 * `InternalLogger` satisfies this shape as-is.
40 */
41 logger?: DockerLogger
42}
43
44const DEFAULT_WORKDIR = '/workspace'
45
46class DockerProvider implements SandboxProvider {
47 readonly name = 'docker'
48 private readonly docker: Dockerode
49
50 constructor(private readonly config: DockerSandboxConfig) {
51 this.docker = new Dockerode(config.dockerodeOptions)
52 }
53
54 capabilities(): SandboxCapabilities {
55 return DOCKER_CAPS
56 }
57
58 private get workdir(): string {
59 return this.config.workdir ?? DEFAULT_WORKDIR
60 }
61
62 private async ensureImage(image: string): Promise<void> {
63 try {
64 await this.docker.getImage(image).inspect()
65 return
66 } catch {
67 // not present locally — pull it
68 }
69 const stream = await this.docker.pull(image)
70 await new Promise<void>((resolve, reject) => {
71 this.docker.modem.followProgress(stream, (err) =>
72 err ? reject(err) : resolve(),
73 )
74 })
75 }
76
77 private readonly forkFactory = async (
78 sourceContainerId: string,
79 ): Promise<SandboxHandle> => {
80 const source = this.docker.getContainer(sourceContainerId)
81 const image = await source.commit({
82 repo: 'tanstack-ai-sandbox-fork',
83 tag: `${sourceContainerId.slice(0, 12)}-${Date.now()}`,
84 })
85 const imageRef =
86 typeof image.Id === 'string'
87 ? image.Id
88 : `tanstack-ai-sandbox-fork:latest`
89 return this.startContainer(imageRef)
90 }
91
92 private async startContainer(
93 image: string,
94 options: {
95 env?: Record<string, string>
96 /** Copied into the work dir. Only `create` passes it. */
97 localSource?: LocalSource
98 signal?: AbortSignal
99 } = {},
100 ): Promise<SandboxHandle> {
101 const { env } = options
102 const exposed: Record<string, Record<string, never>> = {}
103 const bindings: Record<string, Array<{ HostPort: string }>> = {}
104 for (const port of this.config.publishPorts ?? []) {
105 exposed[`${port}/tcp`] = {}
106 bindings[`${port}/tcp`] = [{ HostPort: '' }] // let Docker pick a free host port
107 }
108
109 const container = await this.docker.createContainer({
110 Image: image,
111 Cmd: this.config.keepAliveCommand ?? ['sh', '-c', 'tail -f /dev/null'],
112 Tty: false,
113 WorkingDir: this.workdir,
114 Env: env ? Object.entries(env).map(([k, v]) => `${k}=${v}`) : undefined,
115 ExposedPorts: Object.keys(exposed).length ? exposed : undefined,
116 HostConfig: {
117 ...(Object.keys(bindings).length ? { PortBindings: bindings } : {}),
118 ...(this.config.hostGateway !== false
119 ? { ExtraHosts: ['host.docker.internal:host-gateway'] }
120 : {}),
121 },
122 })
123
124 // If anything after createContainer fails (start, the first exec to
125 // create the workspace dir, or the localSource copy), the container already
126 // exists and would leak as a stopped container. These accumulate and strain
127 // the daemon. Tear it down on any instantiation failure before propagating
128 // the error.
129 try {
130 await container.start()
131 const handle = new DockerHandle({
132 docker: this.docker,
133 container,
134 workdir: this.workdir,
135 forkFactory: this.forkFactory,
136 removeOnDestroy: this.config.removeOnDestroy ?? true,
137 logger: this.config.logger,
138 })
139 // Ensure the workspace dir exists.
140 await handle.fs.mkdir(this.workdir)
141 if (options.localSource !== undefined) {
142 await copyLocalSource(options.localSource, {
143 container,
144 handle,
145 logger: this.config.logger,
146 signal: options.signal,
147 })
148 }
149 return handle
150 } catch (error) {
151 try {
152 await container.remove({ force: true, v: true })
153 } catch {
154 // best-effort cleanup — container may not have started / already gone
155 }
156 throw error
157 }
158 }
159
160 async create(input: SandboxCreateInput): Promise<SandboxHandle> {
161 const source = input.workspace?.source
162 // Read a local folder before any container work, so a bad path fails fast.
163 const localSource =
164 source?.type === 'local' ? await readLocalSource(source.path) : undefined
165 await this.ensureImage(this.config.image)
166 return this.startContainer(this.config.image, {
167 env: input.env,
168 localSource,
169 signal: input.signal,
170 })
171 }
172
173 async resume(input: SandboxResumeInput): Promise<SandboxHandle | null> {
174 const container = this.docker.getContainer(input.id)
175 let info: Dockerode.ContainerInspectInfo
176 try {
177 info = await container.inspect()
178 } catch (error) {
179 // Only a container that Docker does not have is gone. When Docker does
180 // not answer, the caller gets that error, not "gone".
181 if (isNotFound(error)) return null
182 throw error
183 }
184 if (!info.State.Running) {
185 try {
186 await container.start()
187 } catch {
188 return null
189 }
190 }
191 return new DockerHandle({
192 docker: this.docker,
193 container,
194 workdir: this.workdir,
195 forkFactory: this.forkFactory,
196 removeOnDestroy: this.config.removeOnDestroy ?? true,
197 logger: this.config.logger,
198 })
199 }
200
201 async restoreSnapshot(input: SandboxRestoreInput): Promise<SandboxHandle> {
202 return this.startContainer(input.snapshotId, { env: input.env })
203 }
204
205 async destroy(input: SandboxDestroyInput): Promise<void> {
206 const container = this.docker.getContainer(input.id)
207 try {
208 await container.stop({ t: 5 })
209 } catch {
210 // already stopped / gone
211 }
212 if (this.config.removeOnDestroy ?? true) {
213 try {
214 await container.remove({ force: true, v: true })
215 } catch {
216 // already removed
217 }
218 }
219 }
220}
221
222/**
223 * Docker sandbox provider — runs harness adapters inside isolated containers.
224 * Requires a reachable Docker daemon (local socket by default; override via
225 * `dockerodeOptions`).
226 *
227 * When `workspace.source` is `localSource(dir)`, `create()` copies the folder
228 * into `workdir`: the files that git lists, with their uncommitted changes,
229 * and the history of the current branch. The folder must be a Git repository,
230 * and the image must have git (for example `node:24`). The copy goes one way,
231 * once. Fork, restore, and resume do not copy.
232 */
233export function dockerSandbox(config: DockerSandboxConfig): SandboxProvider {
234 return new DockerProvider(config)
235}
236
237/** True for a 404 of the Docker API: Docker does not have the container. */
238function isNotFound(error: unknown) {
239 return (
240 typeof error === 'object' &&
241 error !== null &&
242 'statusCode' in error &&
243 error.statusCode === 404
244 )
245}