forked from mattpocock/sandcastle
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvercel.ts
More file actions
306 lines (269 loc) · 9.56 KB
/
Copy pathvercel.ts
File metadata and controls
306 lines (269 loc) · 9.56 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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
/**
* Vercel isolated sandbox provider — wraps `@vercel/sandbox` into a SandboxProvider.
*
* Usage:
* import { vercel } from "sandcastle/sandboxes/vercel";
* await run({ agent: claudeCode("claude-opus-4-7"), sandbox: vercel() });
*/
import { execSync } from "node:child_process";
import { readFile, unlink, writeFile, mkdir, stat } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { Writable } from "node:stream";
import {
createIsolatedSandboxProvider,
type ExecResult,
type IsolatedSandboxHandle,
type IsolatedSandboxProvider,
} from "../SandboxProvider.js";
import { BoundedTail, MAX_TAIL_CHARS } from "../boundedTail.js";
/** Worktree path inside the Vercel sandbox. */
const VERCEL_REPO_PATH = "/vercel/sandbox/workspace";
/**
* Options for creating a Vercel sandbox provider.
*
* All `@vercel/sandbox` `Sandbox.create()` options are accepted as pass-through,
* plus Sandcastle-specific options for auth and branch strategy.
*/
export interface VercelOptions {
/**
* Vercel access token.
*
* Falls back to the SDK's default auth behavior, which reads
* `VERCEL_OIDC_TOKEN` (recommended for Vercel-hosted environments) or
* `VERCEL_TOKEN` from the environment.
*/
readonly token?: string;
// ---- Pass-through @vercel/sandbox Sandbox.create() options ----
/**
* The source of the sandbox (git repo, tarball, or snapshot).
* Omit to start an empty sandbox.
*/
readonly source?:
| {
type: "git";
url: string;
depth?: number;
revision?: string;
username?: string;
password?: string;
}
| {
type: "tarball";
url: string;
}
| {
type: "snapshot";
snapshotId: string;
};
/** Array of port numbers to expose from the sandbox (up to 4). */
readonly ports?: number[];
/** Timeout in milliseconds before the sandbox auto-terminates. */
readonly timeout?: number;
/**
* Resources to allocate to the sandbox.
* Each vCPU gets 2048 MB of memory.
*/
readonly resources?: {
vcpus: number;
};
/**
* The runtime of the sandbox (e.g. `"node24"`, `"node22"`, `"python3.13"`).
* Defaults to `"node24"`.
*/
readonly runtime?: string;
/**
* Network policy for the sandbox.
* Defaults to full internet access if not specified.
*/
readonly networkPolicy?: Record<string, unknown>;
/**
* Vercel project ID to associate sandbox operations with.
*/
readonly projectId?: string;
/**
* Vercel team ID to associate sandbox operations with.
*/
readonly teamId?: string;
/**
* Timeout in milliseconds (alias for `timeout`, kept for discoverability).
*/
readonly timeoutMs?: number;
/**
* Sandbox template shorthand (e.g. `"node-22"`).
* Maps to the `runtime` option.
*/
readonly template?: string;
/** Environment variables injected by this provider. Merged at launch time with env resolver and agent provider env. */
readonly env?: Record<string, string>;
/**
* Maximum number of characters of streamed `exec` output retained per stream
* (stdout and stderr) when an `onLine` callback is supplied (default: 64KiB).
*
* Output is delivered live to `onLine` regardless; this only bounds the tail
* returned in `ExecResult`, preventing a long-running agent's output from
* overflowing V8's max string length and crashing the run.
*/
readonly maxOutputTailChars?: number;
}
/**
* Create a Vercel isolated sandbox provider.
*
* The returned provider creates Vercel Firecracker microVM sandboxes via
* the `@vercel/sandbox` SDK. Each sandbox is ephemeral — one sandbox per run.
*
* Requires `@vercel/sandbox` to be installed as a peer dependency.
*/
export const vercel = (options?: VercelOptions): IsolatedSandboxProvider =>
createIsolatedSandboxProvider({
name: "vercel",
env: options?.env,
create: async (createOptions): Promise<IsolatedSandboxHandle> => {
const maxOutputTailChars = options?.maxOutputTailChars ?? MAX_TAIL_CHARS;
// Dynamic import so the peer dependency is only loaded at runtime
const { Sandbox } = await import("@vercel/sandbox");
const createParams: Record<string, unknown> = {};
// Pass through SDK options
if (options?.source) createParams.source = options.source;
if (options?.ports) createParams.ports = options.ports;
if (options?.resources) createParams.resources = options.resources;
if (options?.networkPolicy)
createParams.networkPolicy = options.networkPolicy;
// runtime takes precedence over the template convenience alias
const resolvedRuntime = options?.runtime ?? options?.template;
if (resolvedRuntime) createParams.runtime = resolvedRuntime;
// Timeout: prefer explicit timeout, fall back to timeoutMs alias
const timeoutValue = options?.timeout ?? options?.timeoutMs;
if (timeoutValue !== undefined) createParams.timeout = timeoutValue;
// Merge provider env with Sandcastle env
createParams.env = createOptions.env;
// Auth: pass token and team/project IDs if provided
if (options?.token) createParams.token = options.token;
if (options?.projectId) createParams.projectId = options.projectId;
if (options?.teamId) createParams.teamId = options.teamId;
const sandbox = await Sandbox.create(
createParams as Parameters<typeof Sandbox.create>[0],
);
// Ensure worktree directory exists
await sandbox.mkDir(VERCEL_REPO_PATH);
const handle: IsolatedSandboxHandle = {
worktreePath: VERCEL_REPO_PATH,
exec: async (
command: string,
opts?: {
onLine?: (line: string) => void;
cwd?: string;
sudo?: boolean;
},
): Promise<ExecResult> => {
if (opts?.onLine) {
const onLine = opts.onLine;
const stdoutTail = new BoundedTail(maxOutputTailChars, "\n");
const stderrTail = new BoundedTail(maxOutputTailChars, "");
let partial = "";
const stdoutWritable = new Writable({
write(chunk, _encoding, callback) {
const text = partial + chunk.toString();
const lines = text.split("\n");
partial = lines.pop() ?? "";
for (const line of lines) {
stdoutTail.push(line);
onLine(line);
}
callback();
},
final(callback) {
if (partial) {
stdoutTail.push(partial);
onLine(partial);
partial = "";
}
callback();
},
});
const stderrWritable = new Writable({
write(chunk, _encoding, callback) {
stderrTail.push(chunk.toString());
callback();
},
});
const result = await sandbox.runCommand({
cmd: "sh",
args: ["-c", command],
cwd: opts?.cwd ?? VERCEL_REPO_PATH,
stdout: stdoutWritable,
stderr: stderrWritable,
...(opts?.sudo ? { sudo: true } : {}),
});
return {
stdout: stdoutTail.toString(),
stderr: stderrTail.toString(),
exitCode: result.exitCode,
};
}
const result = await sandbox.runCommand({
cmd: "sh",
args: ["-c", command],
cwd: opts?.cwd ?? VERCEL_REPO_PATH,
...(opts?.sudo ? { sudo: true } : {}),
});
const stdout = await result.stdout();
const stderr = await result.stderr();
return {
stdout,
stderr,
exitCode: result.exitCode,
};
},
copyIn: async (
hostPath: string,
sandboxPath: string,
): Promise<void> => {
const info = await stat(hostPath);
if (info.isDirectory()) {
const tarPath = join(
tmpdir(),
`sandcastle-copyin-${Date.now()}.tar.gz`,
);
execSync(`tar -czf "${tarPath}" -C "${hostPath}" .`);
try {
const tarContent = await readFile(tarPath);
const sandboxTarPath = `/tmp/sandcastle-copyin-${Date.now()}.tar.gz`;
await sandbox.writeFiles([
{ path: sandboxTarPath, content: tarContent },
]);
await sandbox.runCommand({
cmd: "sh",
args: [
"-c",
`mkdir -p "${sandboxPath}" && tar -xzf "${sandboxTarPath}" -C "${sandboxPath}" && rm -f "${sandboxTarPath}"`,
],
});
} finally {
await unlink(tarPath).catch(() => {});
}
} else {
const content = await readFile(hostPath);
await sandbox.writeFiles([{ path: sandboxPath, content }]);
}
},
copyFileOut: async (
sandboxPath: string,
hostPath: string,
): Promise<void> => {
const buffer = await sandbox.readFileToBuffer({
path: sandboxPath,
});
if (!buffer) {
throw new Error(`File not found in Vercel sandbox: ${sandboxPath}`);
}
await mkdir(dirname(hostPath), { recursive: true });
await writeFile(hostPath, buffer);
},
close: async (): Promise<void> => {
await sandbox.stop();
},
};
return handle;
},
});