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

provider.ts

201 lines6.4 KB

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