forked from mattpocock/sandcastle
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocker.ts
More file actions
272 lines (244 loc) · 8.35 KB
/
docker.ts
File metadata and controls
272 lines (244 loc) · 8.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
/**
* Docker sandbox provider — wraps DockerLifecycle into a SandboxProvider.
*
* Usage:
* import { docker } from "sandcastle/sandboxes/docker";
* await run({ agent: claudeCode("claude-opus-4-6"), sandbox: docker() });
*/
import {
execFile,
execFileSync,
spawn,
type StdioOptions,
} from "node:child_process";
import { randomUUID } from "node:crypto";
import { createInterface } from "node:readline";
import { Effect } from "effect";
import { startContainer, removeContainer } from "../DockerLifecycle.js";
import {
createBindMountSandboxProvider,
type SandboxProvider,
type BindMountCreateOptions,
type BindMountSandboxHandle,
type ExecResult,
type InteractiveExecOptions,
} from "../SandboxProvider.js";
import type { MountConfig } from "../MountConfig.js";
import { defaultImageName, resolveUserMounts } from "../mountUtils.js";
export interface DockerOptions {
/** Docker image name (default: derived from repo directory name). */
readonly imageName?: string;
/**
* Additional host directories to bind-mount into the sandbox.
*
* Each entry specifies a `hostPath` (tilde-expanded) and `sandboxPath`.
* If `hostPath` does not exist, sandbox creation fails with a clear error.
*/
readonly mounts?: readonly MountConfig[];
/** Environment variables injected by this provider. Merged at launch time with env resolver and agent provider env. */
readonly env?: Record<string, string>;
/**
* Docker network(s) to attach the container to.
*
* - `"my-network"` → `--network my-network`
* - `["net1", "net2"]` → `--network net1 --network net2`
*
* When omitted, Docker's default bridge network is used.
*/
readonly network?: string | readonly string[];
}
/**
* Create a Docker sandbox provider.
*
* The returned provider creates Docker containers with bind-mounts
* for the worktree and git directories.
*/
export const docker = (options?: DockerOptions): SandboxProvider => {
const configuredImageName = options?.imageName;
const sandboxHomedir = "/home/agent";
const userMounts = options?.mounts
? resolveUserMounts(options.mounts, sandboxHomedir)
: [];
return createBindMountSandboxProvider({
name: "docker",
env: options?.env,
sandboxHomedir,
create: async (
createOptions: BindMountCreateOptions,
): Promise<BindMountSandboxHandle> => {
const containerName = `sandcastle-${randomUUID()}`;
const worktreePath =
createOptions.mounts.find(
(m) => m.hostPath === createOptions.worktreePath,
)?.sandboxPath ?? "/home/agent/workspace";
// Build volume mount strings (internal mounts + user-provided mounts)
const allMounts = [...createOptions.mounts, ...userMounts];
const volumeMounts = allMounts.map((m) => {
const base = `${m.hostPath}:${m.sandboxPath}`;
return m.readonly ? `${base}:ro` : base;
});
// Resolve image name
const imageName =
configuredImageName ?? defaultImageName(createOptions.hostRepoPath);
const hostUid = process.getuid?.() ?? 1000;
const hostGid = process.getgid?.() ?? 1000;
// Start container
await Effect.runPromise(
startContainer(
containerName,
imageName,
{
...createOptions.env,
HOME: "/home/agent",
},
{
volumeMounts,
workdir: worktreePath,
user: `${hostUid}:${hostGid}`,
network: options?.network,
},
),
);
// Set up signal handlers for cleanup
const onExit = () => {
try {
execFileSync("docker", ["rm", "-f", containerName], {
stdio: "ignore",
});
} catch {
/* best-effort */
}
};
const onSignal = () => {
onExit();
process.exit(1);
};
process.on("exit", onExit);
process.on("SIGINT", onSignal);
process.on("SIGTERM", onSignal);
const handle: BindMountSandboxHandle = {
worktreePath,
exec: (
command: string,
opts?: {
onLine?: (line: string) => void;
cwd?: string;
sudo?: boolean;
stdin?: string;
},
): Promise<ExecResult> => {
const effectiveCommand = opts?.sudo ? `sudo ${command}` : command;
const args = ["exec"];
if (opts?.stdin !== undefined) args.push("-i");
if (opts?.cwd) args.push("-w", opts.cwd);
args.push(containerName, "sh", "-c", effectiveCommand);
return new Promise((resolve, reject) => {
const proc = spawn("docker", args, {
stdio: [
opts?.stdin !== undefined ? "pipe" : "ignore",
"pipe",
"pipe",
],
});
if (opts?.stdin !== undefined) {
proc.stdin!.write(opts.stdin);
proc.stdin!.end();
}
const stdoutChunks: string[] = [];
const stderrChunks: string[] = [];
if (opts?.onLine) {
const onLine = opts.onLine;
const rl = createInterface({ input: proc.stdout! });
rl.on("line", (line) => {
stdoutChunks.push(line);
onLine(line);
});
} else {
proc.stdout!.on("data", (chunk: Buffer) => {
stdoutChunks.push(chunk.toString());
});
}
proc.stderr!.on("data", (chunk: Buffer) => {
stderrChunks.push(chunk.toString());
});
proc.on("error", (error) => {
reject(new Error(`docker exec failed: ${error.message}`));
});
proc.on("close", (code) => {
resolve({
stdout: stdoutChunks.join(opts?.onLine ? "\n" : ""),
stderr: stderrChunks.join(""),
exitCode: code ?? 0,
});
});
});
},
interactiveExec: (
args: string[],
opts: InteractiveExecOptions,
): Promise<{ exitCode: number }> => {
return new Promise((resolve, reject) => {
const dockerArgs = ["exec"];
// Allocate a pseudo-terminal when stdin looks like a TTY
if (
"isTTY" in opts.stdin &&
(opts.stdin as { isTTY?: boolean }).isTTY
) {
dockerArgs.push("-it");
} else {
dockerArgs.push("-i");
}
if (opts.cwd) dockerArgs.push("-w", opts.cwd);
dockerArgs.push(containerName, ...args);
const proc = spawn("docker", dockerArgs, {
stdio: [opts.stdin, opts.stdout, opts.stderr] as StdioOptions,
});
proc.on("error", (error: Error) => {
reject(new Error(`docker exec failed: ${error.message}`));
});
proc.on("close", (code: number | null) => {
resolve({ exitCode: code ?? 0 });
});
});
},
copyFileIn: (hostPath: string, sandboxPath: string): Promise<void> =>
new Promise((resolve, reject) => {
execFile(
"docker",
["cp", hostPath, `${containerName}:${sandboxPath}`],
(error) => {
if (error) {
reject(new Error(`docker cp (in) failed: ${error.message}`));
} else {
resolve();
}
},
);
}),
copyFileOut: (sandboxPath: string, hostPath: string): Promise<void> =>
new Promise((resolve, reject) => {
execFile(
"docker",
["cp", `${containerName}:${sandboxPath}`, hostPath],
(error) => {
if (error) {
reject(new Error(`docker cp (out) failed: ${error.message}`));
} else {
resolve();
}
},
);
}),
close: async (): Promise<void> => {
process.removeListener("exit", onExit);
process.removeListener("SIGINT", onSignal);
process.removeListener("SIGTERM", onSignal);
await Effect.runPromise(removeContainer(containerName));
},
};
return handle;
},
});
};
// Re-export for backwards compatibility
export { defaultImageName };