@ai-hero/sandcastle 0.12.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -1368
- package/dist/LinuxCapability-B_PQfsY_.d.ts +32 -0
- package/dist/{SandboxProvider-EkSMuBp8.d.ts → SandboxProvider-Chsi-Zs6.d.ts} +31 -3
- package/dist/{chunk-NGBM7T3E.js → chunk-6NQPCXSG.js} +5 -2
- package/dist/chunk-6NQPCXSG.js.map +1 -0
- package/dist/chunk-7N7AMUYA.js +353 -0
- package/dist/chunk-7N7AMUYA.js.map +1 -0
- package/dist/chunk-ATA2V2TC.js +112 -0
- package/dist/chunk-ATA2V2TC.js.map +1 -0
- package/dist/chunk-BIF2X6QB.js +94 -0
- package/dist/chunk-BIF2X6QB.js.map +1 -0
- package/dist/{chunk-BIWNFKGV.js → chunk-BVZWLFFT.js} +2 -2
- package/dist/chunk-BVZWLFFT.js.map +1 -0
- package/dist/chunk-EXYXBRCX.js +60 -0
- package/dist/chunk-EXYXBRCX.js.map +1 -0
- package/dist/chunk-G2R53CVZ.js +3172 -0
- package/dist/chunk-G2R53CVZ.js.map +1 -0
- package/dist/{chunk-CP3TYXZA.js → chunk-GCLEXPXG.js} +95 -85
- package/dist/chunk-GCLEXPXG.js.map +1 -0
- package/dist/chunk-H2PEFS4W.js +1244 -0
- package/dist/chunk-H2PEFS4W.js.map +1 -0
- package/dist/chunk-HSXPRZKG.js +150 -0
- package/dist/chunk-HSXPRZKG.js.map +1 -0
- package/dist/chunk-IBK2XNSS.js +50 -0
- package/dist/chunk-IBK2XNSS.js.map +1 -0
- package/dist/chunk-RDW7FNN6.js +792 -0
- package/dist/chunk-RDW7FNN6.js.map +1 -0
- package/dist/{chunk-DJRHWPEH.js → chunk-S6UHPTRG.js} +284 -352
- package/dist/chunk-S6UHPTRG.js.map +1 -0
- package/dist/{chunk-VOG34SRF.js → chunk-STB2U7BB.js} +11823 -6977
- package/dist/chunk-STB2U7BB.js.map +1 -0
- package/dist/chunk-VRXR2T3S.js +24 -0
- package/dist/chunk-VRXR2T3S.js.map +1 -0
- package/dist/index.d.ts +241 -26
- package/dist/index.js +1082 -1679
- package/dist/index.js.map +1 -1
- package/dist/main.js +1248 -854
- package/dist/main.js.map +1 -1
- package/dist/sandboxes/bwrap.d.ts +58 -0
- package/dist/sandboxes/bwrap.js +296 -0
- package/dist/sandboxes/bwrap.js.map +1 -0
- package/dist/sandboxes/daytona.d.ts +1 -1
- package/dist/sandboxes/daytona.js +203 -98
- package/dist/sandboxes/daytona.js.map +1 -1
- package/dist/sandboxes/docker.d.ts +18 -4
- package/dist/sandboxes/docker.js +7 -4
- package/dist/sandboxes/e2b.d.ts +41 -0
- package/dist/sandboxes/e2b.js +202 -0
- package/dist/sandboxes/e2b.js.map +1 -0
- package/dist/sandboxes/modal.d.ts +78 -0
- package/dist/sandboxes/modal.js +171 -0
- package/dist/sandboxes/modal.js.map +1 -0
- package/dist/sandboxes/no-sandbox.d.ts +1 -1
- package/dist/sandboxes/no-sandbox.js +2 -2
- package/dist/sandboxes/podman.d.ts +18 -4
- package/dist/sandboxes/podman.js +72 -56
- package/dist/sandboxes/podman.js.map +1 -1
- package/dist/sandboxes/seatbelt.d.ts +65 -0
- package/dist/sandboxes/seatbelt.js +425 -0
- package/dist/sandboxes/seatbelt.js.map +1 -0
- package/dist/sandboxes/sprites.d.ts +54 -0
- package/dist/sandboxes/sprites.js +198 -0
- package/dist/sandboxes/sprites.js.map +1 -0
- package/dist/sandboxes/vercel.d.ts +12 -5
- package/dist/sandboxes/vercel.js +195 -126
- package/dist/sandboxes/vercel.js.map +1 -1
- package/dist/templates/parallel-planner/main.mts +13 -22
- package/dist/templates/parallel-planner-with-review/main.mts +13 -15
- package/package.json +63 -11
- package/dist/chunk-62WN33RK.js +0 -104
- package/dist/chunk-62WN33RK.js.map +0 -1
- package/dist/chunk-BIWNFKGV.js.map +0 -1
- package/dist/chunk-CP3TYXZA.js.map +0 -1
- package/dist/chunk-DJRHWPEH.js.map +0 -1
- package/dist/chunk-NGBM7T3E.js.map +0 -1
- package/dist/chunk-VOG34SRF.js.map +0 -1
- package/dist/mountUtils-CCA-bbpK.d.ts +0 -25
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import { shellEscape } from '../chunk-H2PEFS4W.js';
|
|
3
|
+
import '../chunk-RDW7FNN6.js';
|
|
4
|
+
import '../chunk-STB2U7BB.js';
|
|
5
|
+
import { createIsolatedSandboxProvider } from '../chunk-BVZWLFFT.js';
|
|
6
|
+
import { MAX_TAIL_CHARS, BoundedTail } from '../chunk-6NQPCXSG.js';
|
|
7
|
+
import { mkdir, writeFile, stat, rm, readFile } from 'fs/promises';
|
|
8
|
+
import { dirname, join } from 'path';
|
|
9
|
+
import { spawn } from 'child_process';
|
|
10
|
+
import { randomUUID } from 'crypto';
|
|
11
|
+
import { once } from 'events';
|
|
12
|
+
import { tmpdir } from 'os';
|
|
13
|
+
|
|
14
|
+
createRequire(import.meta.url);
|
|
15
|
+
|
|
16
|
+
// src/sandboxes/e2bExec.ts
|
|
17
|
+
var deliverStdin = async (handle, stdin) => {
|
|
18
|
+
try {
|
|
19
|
+
if (stdin !== "") {
|
|
20
|
+
await handle.sendStdin(stdin);
|
|
21
|
+
}
|
|
22
|
+
await handle.closeStdin();
|
|
23
|
+
} catch (error) {
|
|
24
|
+
if (!(error instanceof Error && error.name === "NotFoundError")) {
|
|
25
|
+
await handle.kill().catch(() => void 0);
|
|
26
|
+
throw error;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
var isExitError = (ExitError, error) => error instanceof ExitError;
|
|
31
|
+
var waitForExit = async (ExitError, handle) => {
|
|
32
|
+
try {
|
|
33
|
+
const { stdout, stderr, exitCode } = await handle.wait();
|
|
34
|
+
return { stdout, stderr, exitCode };
|
|
35
|
+
} catch (error) {
|
|
36
|
+
if (!isExitError(ExitError, error)) {
|
|
37
|
+
throw error;
|
|
38
|
+
}
|
|
39
|
+
const { stdout, stderr, exitCode } = error;
|
|
40
|
+
return { stdout, stderr, exitCode };
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
var lineStreams = (onLine, maxTail) => {
|
|
44
|
+
const stdoutTail = new BoundedTail(maxTail, "\n");
|
|
45
|
+
const stderrTail = new BoundedTail(maxTail, "");
|
|
46
|
+
let partial = "";
|
|
47
|
+
return {
|
|
48
|
+
onStdout: (chunk) => {
|
|
49
|
+
const lines = (partial + chunk).split("\n");
|
|
50
|
+
partial = lines.pop() ?? "";
|
|
51
|
+
for (const line of lines) {
|
|
52
|
+
stdoutTail.push(line);
|
|
53
|
+
onLine(line);
|
|
54
|
+
}
|
|
55
|
+
},
|
|
56
|
+
onStderr: (chunk) => {
|
|
57
|
+
stderrTail.push(chunk);
|
|
58
|
+
},
|
|
59
|
+
finish: (exitCode) => {
|
|
60
|
+
if (partial !== "") {
|
|
61
|
+
stdoutTail.push(partial);
|
|
62
|
+
onLine(partial);
|
|
63
|
+
partial = "";
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
stdout: stdoutTail.toString(),
|
|
67
|
+
stderr: stderrTail.toString(),
|
|
68
|
+
exitCode
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
};
|
|
73
|
+
var makeExec = ({ ExitError, sandbox, worktreePath, maxTail }) => async (command, opts) => {
|
|
74
|
+
const streams = opts?.onLine === void 0 ? void 0 : lineStreams(opts.onLine, maxTail);
|
|
75
|
+
const handle = await sandbox.commands.run(command, {
|
|
76
|
+
background: true,
|
|
77
|
+
cwd: opts?.cwd ?? worktreePath,
|
|
78
|
+
...opts?.sudo === true ? { user: "root" } : {},
|
|
79
|
+
stdin: opts?.stdin !== void 0,
|
|
80
|
+
timeoutMs: 0,
|
|
81
|
+
...streams === void 0 ? {} : { onStdout: streams.onStdout, onStderr: streams.onStderr }
|
|
82
|
+
});
|
|
83
|
+
if (opts?.stdin !== void 0) {
|
|
84
|
+
await deliverStdin(handle, opts.stdin);
|
|
85
|
+
}
|
|
86
|
+
const result = await waitForExit(ExitError, handle);
|
|
87
|
+
return streams === void 0 ? result : streams.finish(result.exitCode);
|
|
88
|
+
};
|
|
89
|
+
var OCTET = { useOctetStream: true };
|
|
90
|
+
var fileBlob = async (path) => new Blob([await readFile(path)]);
|
|
91
|
+
var tarDirectory = async (archive, dir) => {
|
|
92
|
+
const child = spawn("tar", ["-czf", archive, "-C", dir, "."], {
|
|
93
|
+
stdio: ["ignore", "ignore", "pipe"]
|
|
94
|
+
});
|
|
95
|
+
let stderr = "";
|
|
96
|
+
child.stderr.on("data", (chunk) => {
|
|
97
|
+
stderr += chunk.toString();
|
|
98
|
+
});
|
|
99
|
+
await once(child, "close");
|
|
100
|
+
if (child.exitCode !== 0) {
|
|
101
|
+
throw new Error(
|
|
102
|
+
`tar exited with ${String(child.exitCode)}: ${stderr.trim()}`
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
var runToEnd = async (sandbox, command) => {
|
|
107
|
+
const result = await sandbox.commands.run(command, { timeoutMs: 0 });
|
|
108
|
+
return result.stdout;
|
|
109
|
+
};
|
|
110
|
+
var copyDirIn = async (sandbox, hostPath, sandboxPath) => {
|
|
111
|
+
const id = randomUUID();
|
|
112
|
+
const tarPath = join(tmpdir(), `sandcastle-copyin-${id}.tar.gz`);
|
|
113
|
+
const sandboxTarPath = `/tmp/sandcastle-copyin-${id}.tar.gz`;
|
|
114
|
+
const tar = shellEscape(sandboxTarPath);
|
|
115
|
+
try {
|
|
116
|
+
await tarDirectory(tarPath, hostPath);
|
|
117
|
+
await sandbox.files.write(sandboxTarPath, await fileBlob(tarPath), OCTET);
|
|
118
|
+
const dest = shellEscape(sandboxPath);
|
|
119
|
+
await runToEnd(
|
|
120
|
+
sandbox,
|
|
121
|
+
`mkdir -p ${dest} && tar -xzf ${tar} -C ${dest}; s=$?; rm -f ${tar}; exit $s`
|
|
122
|
+
);
|
|
123
|
+
} finally {
|
|
124
|
+
await rm(tarPath, { force: true });
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
var makeCopyIn = (sandbox) => async (hostPath, sandboxPath) => {
|
|
128
|
+
const info = await stat(hostPath);
|
|
129
|
+
if (info.isDirectory()) {
|
|
130
|
+
await copyDirIn(sandbox, hostPath, sandboxPath);
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
await sandbox.files.write(sandboxPath, await fileBlob(hostPath), OCTET);
|
|
134
|
+
const mode = (info.mode % 512).toString(8);
|
|
135
|
+
await runToEnd(sandbox, `chmod ${mode} ${shellEscape(sandboxPath)}`);
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
// src/sandboxes/e2b.ts
|
|
139
|
+
var DEFAULT_TIMEOUT_MS = 30 * 60 * 1e3;
|
|
140
|
+
var whyFailed = (error) => {
|
|
141
|
+
if (error instanceof Error && "stderr" in error && typeof error.stderr === "string" && error.stderr.trim() !== "") {
|
|
142
|
+
return error.stderr.trim();
|
|
143
|
+
}
|
|
144
|
+
return error instanceof Error ? error.message : String(error);
|
|
145
|
+
};
|
|
146
|
+
var prepareWorktree = async (sandbox) => {
|
|
147
|
+
const mkdirCommand = 'mkdir -p "$HOME/workspace" && cd "$HOME/workspace" && pwd';
|
|
148
|
+
try {
|
|
149
|
+
const out = await runToEnd(sandbox, mkdirCommand);
|
|
150
|
+
return out.trim();
|
|
151
|
+
} catch (error) {
|
|
152
|
+
await sandbox.kill().catch(() => void 0);
|
|
153
|
+
throw new Error(
|
|
154
|
+
`e2b(): could not create $HOME/workspace: ${whyFailed(error)}`,
|
|
155
|
+
{ cause: error }
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
var e2b = (options) => {
|
|
160
|
+
const {
|
|
161
|
+
env,
|
|
162
|
+
maxOutputTailChars: maxTail = MAX_TAIL_CHARS,
|
|
163
|
+
apiKey,
|
|
164
|
+
...sdkOptions
|
|
165
|
+
} = options ?? {};
|
|
166
|
+
return createIsolatedSandboxProvider({
|
|
167
|
+
name: "e2b",
|
|
168
|
+
env,
|
|
169
|
+
create: async (createOptions) => {
|
|
170
|
+
const { Sandbox: E2BSandbox, CommandExitError: ExitError } = await import('e2b');
|
|
171
|
+
const sandbox = await E2BSandbox.create({
|
|
172
|
+
...sdkOptions,
|
|
173
|
+
// An empty key counts as unset, so the SDK reads E2B_API_KEY
|
|
174
|
+
...apiKey === void 0 || apiKey === "" ? {} : { apiKey },
|
|
175
|
+
timeoutMs: sdkOptions.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
|
176
|
+
envs: createOptions.env,
|
|
177
|
+
lifecycle: { onTimeout: "kill", autoResume: false }
|
|
178
|
+
});
|
|
179
|
+
const worktreePath = await prepareWorktree(sandbox);
|
|
180
|
+
return {
|
|
181
|
+
worktreePath,
|
|
182
|
+
sandboxId: sandbox.sandboxId,
|
|
183
|
+
exec: makeExec({ ExitError, sandbox, worktreePath, maxTail }),
|
|
184
|
+
copyIn: makeCopyIn(sandbox),
|
|
185
|
+
copyFileOut: async (sandboxPath, hostPath) => {
|
|
186
|
+
const content = await sandbox.files.read(sandboxPath, {
|
|
187
|
+
format: "bytes"
|
|
188
|
+
});
|
|
189
|
+
await mkdir(dirname(hostPath), { recursive: true });
|
|
190
|
+
await writeFile(hostPath, content);
|
|
191
|
+
},
|
|
192
|
+
close: async () => {
|
|
193
|
+
await sandbox.kill();
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
});
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
export { e2b };
|
|
201
|
+
//# sourceMappingURL=e2b.js.map
|
|
202
|
+
//# sourceMappingURL=e2b.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/sandboxes/e2bExec.ts","../../src/sandboxes/e2bFiles.ts","../../src/sandboxes/e2b.ts"],"names":[],"mappings":";;;;;;;;;;;;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c,SAAS,CAAA;AAAA,QAC5D,MAAA,EAAQ,WAAW,OAAO,CAAA;AAAA,QAC1B,WAAA,EAAa,OAAO,WAAA,EAAa,QAAA,KAAa;AAC5C,UAAA,MAAM,OAAA,GAAU,MAAM,OAAA,CAAQ,KAAA,CAAM,KAAK,WAAA,EAAa;AAAA,YACpD,MAAA,EAAQ;AAAA,WACT,CAAA;AACD,UAAA,MAAM,MAAM,OAAA,CAAQ,QAAQ,GAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAClD,UAAA,MAAM,SAAA,CAAU,UAAU,OAAO,CAAA;AAAA,QACnC,CAAA;AAAA,QACA,OAAO,YAAY;AACjB,UAAA,MAAM,QAAQ,IAAA,EAAK;AAAA,QACrB;AAAA,OACF;AAAA,IACF;AAAA,GACD,CAAA;AACH","file":"e2b.js","sourcesContent":["/**\n * The `exec` of the E2B sandbox provider (`./e2b.ts`): native stdin, live\n * line streaming, and a non-zero exit mapped to its result.\n */\n\nimport type { CommandExitError, CommandHandle, Sandbox } from \"e2b\";\nimport type { ExecResult, IsolatedSandboxHandle } from \"../SandboxProvider.js\";\nimport { BoundedTail } from \"../boundedTail.js\";\n\n/** The SDK's non-zero-exit error class, loaded with the SDK at runtime. */\ntype ExitErrorClass = typeof CommandExitError;\ntype ExecOptions = Parameters<IsolatedSandboxHandle[\"exec\"]>[1];\n\n/** Send stdin, then close it. The command may exit before reading it. */\nconst deliverStdin = async (\n handle: CommandHandle,\n stdin: string,\n): Promise<void> => {\n try {\n if (stdin !== \"\") {\n await handle.sendStdin(stdin);\n }\n await handle.closeStdin();\n } catch (error) {\n // A command that already exited is a NotFoundError; wait() still reports it.\n if (!(error instanceof Error && error.name === \"NotFoundError\")) {\n await handle.kill().catch(() => undefined);\n throw error;\n }\n }\n};\n\nconst isExitError = (\n ExitError: ExitErrorClass,\n error: unknown,\n): error is CommandExitError => error instanceof ExitError;\n\n/** Wait for a command, mapping a non-zero exit to its result. */\nconst waitForExit = async (\n ExitError: ExitErrorClass,\n handle: CommandHandle,\n): Promise<ExecResult> => {\n try {\n const { stdout, stderr, exitCode } = await handle.wait();\n return { stdout, stderr, exitCode };\n } catch (error) {\n if (!isExitError(ExitError, error)) {\n throw error;\n }\n const { stdout, stderr, exitCode } = error;\n return { stdout, stderr, exitCode };\n }\n};\n\n/** Split streamed stdout into lines for `onLine`, keeping bounded tails. */\nconst lineStreams = (onLine: (line: string) => void, maxTail: number) => {\n const stdoutTail = new BoundedTail(maxTail, \"\\n\");\n const stderrTail = new BoundedTail(maxTail, \"\");\n let partial = \"\";\n return {\n onStdout: (chunk: string): void => {\n const lines = (partial + chunk).split(\"\\n\");\n partial = lines.pop() ?? \"\";\n for (const line of lines) {\n stdoutTail.push(line);\n onLine(line);\n }\n },\n onStderr: (chunk: string): void => {\n stderrTail.push(chunk);\n },\n finish: (exitCode: number): ExecResult => {\n if (partial !== \"\") {\n stdoutTail.push(partial);\n onLine(partial);\n partial = \"\";\n }\n return {\n stdout: stdoutTail.toString(),\n stderr: stderrTail.toString(),\n exitCode,\n };\n },\n };\n};\n\n/** What `exec` needs from the provider. */\nexport interface ExecContext {\n readonly ExitError: ExitErrorClass;\n readonly sandbox: Sandbox;\n readonly worktreePath: string;\n readonly maxTail: number;\n}\n\n/** The handle's `exec`, bound to one sandbox and its worktree. */\nexport const makeExec =\n ({ ExitError, sandbox, worktreePath, maxTail }: ExecContext) =>\n async (command: string, opts?: ExecOptions): Promise<ExecResult> => {\n const streams =\n opts?.onLine === undefined\n ? undefined\n : lineStreams(opts.onLine, maxTail);\n const handle = await sandbox.commands.run(command, {\n background: true,\n cwd: opts?.cwd ?? worktreePath,\n ...(opts?.sudo === true ? { user: \"root\" } : {}),\n stdin: opts?.stdin !== undefined,\n timeoutMs: 0,\n ...(streams === undefined\n ? {}\n : { onStdout: streams.onStdout, onStderr: streams.onStderr }),\n });\n if (opts?.stdin !== undefined) {\n await deliverStdin(handle, opts.stdin);\n }\n const result = await waitForExit(ExitError, handle);\n return streams === undefined ? result : streams.finish(result.exitCode);\n };\n","/**\n * Copying files into an E2B sandbox, for the E2B sandbox provider\n * (`./e2b.ts`). A directory goes in as one tarball.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport { once } from \"node:events\";\nimport { readFile, rm, stat } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { Sandbox } from \"e2b\";\nimport { shellEscape } from \"../AgentProvider.js\";\n\n/** Upload as a raw body, not multipart (the SDK falls back on an old envd). */\nconst OCTET = { useOctetStream: true } as const;\n\n/**\n * A host file's bytes, read now: a lazy `openAsBlob` would fail mid-upload\n * as \"fetch failed\" instead of naming the error, such as EACCES.\n */\nconst fileBlob = async (path: string): Promise<Blob> =>\n new Blob([await readFile(path)]);\n\n/** Pack `dir` into a gzipped tarball at `archive` on the host. */\nconst tarDirectory = async (archive: string, dir: string): Promise<void> => {\n const child = spawn(\"tar\", [\"-czf\", archive, \"-C\", dir, \".\"], {\n stdio: [\"ignore\", \"ignore\", \"pipe\"],\n });\n let stderr = \"\";\n child.stderr.on(\"data\", (chunk: Buffer) => {\n stderr += chunk.toString();\n });\n await once(child, \"close\");\n if (child.exitCode !== 0) {\n throw new Error(\n `tar exited with ${String(child.exitCode)}: ${stderr.trim()}`,\n );\n }\n};\n\n/** Run a setup command to completion and return its stdout. */\nexport const runToEnd = async (\n sandbox: Sandbox,\n command: string,\n): Promise<string> => {\n const result = await sandbox.commands.run(command, { timeoutMs: 0 });\n return result.stdout;\n};\n\n/** Copy a host directory in as a tarball, unpacked at `sandboxPath`. */\nconst copyDirIn = async (\n sandbox: Sandbox,\n hostPath: string,\n sandboxPath: string,\n): Promise<void> => {\n const id = randomUUID();\n const tarPath = join(tmpdir(), `sandcastle-copyin-${id}.tar.gz`);\n const sandboxTarPath = `/tmp/sandcastle-copyin-${id}.tar.gz`;\n const tar = shellEscape(sandboxTarPath);\n try {\n await tarDirectory(tarPath, hostPath);\n await sandbox.files.write(sandboxTarPath, await fileBlob(tarPath), OCTET);\n const dest = shellEscape(sandboxPath);\n // Remove the archive even if extraction fails, keeping its exit code\n await runToEnd(\n sandbox,\n `mkdir -p ${dest} && tar -xzf ${tar} -C ${dest}; s=$?; rm -f ${tar}; exit $s`,\n );\n } finally {\n await rm(tarPath, { force: true });\n }\n};\n\n/** The handle's `copyIn`: a file or a directory, keeping the host's mode. */\nexport const makeCopyIn =\n (sandbox: Sandbox) =>\n async (hostPath: string, sandboxPath: string): Promise<void> => {\n const info = await stat(hostPath);\n if (info.isDirectory()) {\n await copyDirIn(sandbox, hostPath, sandboxPath);\n return;\n }\n await sandbox.files.write(sandboxPath, await fileBlob(hostPath), OCTET);\n // files.write keeps an existing file's mode, so always apply the host's\n const mode = (info.mode % 0o1000).toString(8);\n await runToEnd(sandbox, `chmod ${mode} ${shellEscape(sandboxPath)}`);\n };\n","/**\n * E2B isolated sandbox provider — wraps the `e2b` SDK into a SandboxProvider.\n */\n\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport type { Sandbox, SandboxOpts } from \"e2b\";\nimport { createIsolatedSandboxProvider } from \"../SandboxProvider.js\";\nimport type {\n IsolatedSandboxHandle,\n IsolatedSandboxProvider,\n} from \"../SandboxProvider.js\";\nimport { MAX_TAIL_CHARS } from \"../boundedTail.js\";\nimport { makeExec } from \"./e2bExec.js\";\nimport { makeCopyIn, runToEnd } from \"./e2bFiles.js\";\n\n/**\n * Options for the E2B sandbox provider.\n *\n * All `Sandbox.create()` options from the `e2b` SDK pass through (`template`,\n * `timeoutMs`, `apiKey`, `metadata`, `network`, ...), except `envs` and\n * `lifecycle`, which the provider controls.\n *\n * `apiKey` falls back to the `E2B_API_KEY` environment variable. `timeoutMs`\n * defaults to 30 minutes; the sandbox is killed when it expires, so it must\n * cover setup, the agent run and syncing changes back.\n */\nexport interface E2BOptions extends Omit<SandboxOpts, \"envs\" | \"lifecycle\"> {\n /** Environment variables injected by this provider. Merged at launch time with env resolver and agent provider env. */\n readonly env?: Record<string, string>;\n\n /**\n * Maximum characters of streamed `exec` output kept per stream for\n * `ExecResult` when `onLine` is supplied (default: 64KiB). `onLine` still\n * gets every line.\n */\n readonly maxOutputTailChars?: number;\n}\n\nconst DEFAULT_TIMEOUT_MS = 30 * 60 * 1000;\n\n/** Why a setup command failed: its stderr when it has one, else the error. */\nconst whyFailed = (error: unknown): string => {\n if (\n error instanceof Error &&\n \"stderr\" in error &&\n typeof error.stderr === \"string\" &&\n error.stderr.trim() !== \"\"\n ) {\n return error.stderr.trim();\n }\n return error instanceof Error ? error.message : String(error);\n};\n\n/**\n * Create `$HOME/workspace` and return its path. On failure, kill the sandbox:\n * no handle exists yet, so nothing else could reach it before its timeout.\n */\nconst prepareWorktree = async (sandbox: Sandbox): Promise<string> => {\n const mkdirCommand =\n 'mkdir -p \"$HOME/workspace\" && cd \"$HOME/workspace\" && pwd';\n try {\n const out = await runToEnd(sandbox, mkdirCommand);\n return out.trim();\n } catch (error) {\n await sandbox.kill().catch(() => undefined);\n throw new Error(\n `e2b(): could not create $HOME/workspace: ${whyFailed(error)}`,\n { cause: error },\n );\n }\n};\n\n/**\n * Create an E2B isolated sandbox provider.\n *\n * Each sandbox is ephemeral: `create()` starts a new E2B sandbox and\n * `close()` kills it. Pausing is never enabled. Requires `e2b` to be\n * installed as a peer dependency, and `E2B_API_KEY` in the host environment\n * (or the `apiKey` option). E2B's default template has no agent CLI: use a\n * template that ships one (such as `\"claude\"` or `\"codex\"`), or install it in\n * an `onSandboxReady` hook.\n */\nexport const e2b = (options?: E2BOptions): IsolatedSandboxProvider => {\n const {\n env,\n maxOutputTailChars: maxTail = MAX_TAIL_CHARS,\n apiKey,\n ...sdkOptions\n } = options ?? {};\n return createIsolatedSandboxProvider({\n name: \"e2b\",\n env,\n create: async (createOptions): Promise<IsolatedSandboxHandle> => {\n // Dynamic import so the peer dependency is only loaded at runtime\n const { Sandbox: E2BSandbox, CommandExitError: ExitError } = await import(\n \"e2b\"\n );\n const sandbox = await E2BSandbox.create({\n ...sdkOptions,\n // An empty key counts as unset, so the SDK reads E2B_API_KEY\n ...(apiKey === undefined || apiKey === \"\" ? {} : { apiKey }),\n timeoutMs: sdkOptions.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n envs: createOptions.env,\n lifecycle: { onTimeout: \"kill\", autoResume: false },\n });\n const worktreePath = await prepareWorktree(sandbox);\n\n return {\n worktreePath,\n sandboxId: sandbox.sandboxId,\n exec: makeExec({ ExitError, sandbox, worktreePath, maxTail }),\n copyIn: makeCopyIn(sandbox),\n copyFileOut: async (sandboxPath, hostPath) => {\n const content = await sandbox.files.read(sandboxPath, {\n format: \"bytes\",\n });\n await mkdir(dirname(hostPath), { recursive: true });\n await writeFile(hostPath, content);\n },\n close: async () => {\n await sandbox.kill();\n },\n };\n },\n });\n};\n"]}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { I as IsolatedSandboxProvider } from '../SandboxProvider-Chsi-Zs6.js';
|
|
2
|
+
import { Image, SandboxCreateParams } from 'modal';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Modal isolated sandbox provider — wraps the `modal` SDK into a SandboxProvider.
|
|
6
|
+
*
|
|
7
|
+
* Usage:
|
|
8
|
+
* import { modal } from "@ai-hero/sandcastle/sandboxes/modal";
|
|
9
|
+
* await run({ agent: claudeCode("claude-opus-4-8"), sandbox: modal() });
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** Options for the Modal sandbox provider. */
|
|
13
|
+
interface ModalOptions {
|
|
14
|
+
/**
|
|
15
|
+
* Modal token id. Falls back to the `MODAL_TOKEN_ID` environment variable,
|
|
16
|
+
* then to `~/.modal.toml` (written by `modal token new`).
|
|
17
|
+
*/
|
|
18
|
+
readonly tokenId?: string;
|
|
19
|
+
/**
|
|
20
|
+
* Modal token secret. Falls back to the `MODAL_TOKEN_SECRET` environment
|
|
21
|
+
* variable, then to `~/.modal.toml`.
|
|
22
|
+
*/
|
|
23
|
+
readonly tokenSecret?: string;
|
|
24
|
+
/**
|
|
25
|
+
* Modal environment to create sandboxes in. Falls back to
|
|
26
|
+
* `MODAL_ENVIRONMENT`, then to the profile's default.
|
|
27
|
+
*/
|
|
28
|
+
readonly environment?: string;
|
|
29
|
+
/**
|
|
30
|
+
* Name of the Modal App the sandboxes belong to (default: `"sandcastle"`).
|
|
31
|
+
* It is created if it does not exist; no deploy step is needed.
|
|
32
|
+
*/
|
|
33
|
+
readonly appName?: string;
|
|
34
|
+
/**
|
|
35
|
+
* The sandbox image: a registry tag such as `"node:24-bookworm"`, or a
|
|
36
|
+
* Modal `Image` you built yourself (e.g. with `dockerfileCommands`).
|
|
37
|
+
*
|
|
38
|
+
* Omit it for Sandcastle's default: `node:24-bookworm` (Node LTS, git, tar)
|
|
39
|
+
* with Claude Code installed. Any other image must have `sh`, `git` and
|
|
40
|
+
* your agent's CLI, or install the CLI in an `onSandboxReady` hook.
|
|
41
|
+
*
|
|
42
|
+
* Modal runs every command as root, whatever the image's `USER`.
|
|
43
|
+
*/
|
|
44
|
+
readonly image?: string | Image;
|
|
45
|
+
/**
|
|
46
|
+
* Maximum lifetime of the sandbox in milliseconds (default: one hour,
|
|
47
|
+
* Modal's own default is 5 minutes). Modal can't extend it after create,
|
|
48
|
+
* so set it above your longest run. Modal allows up to 24 hours.
|
|
49
|
+
*/
|
|
50
|
+
readonly timeoutMs?: number;
|
|
51
|
+
/**
|
|
52
|
+
* Other `sandboxes.create()` options, passed through to Modal (`cpu`,
|
|
53
|
+
* `memoryMiB`, `regions`, `blockNetwork`, …). Its `env` wins over the
|
|
54
|
+
* env Sandcastle resolves.
|
|
55
|
+
*/
|
|
56
|
+
readonly create?: Omit<SandboxCreateParams, "timeoutMs">;
|
|
57
|
+
/** Environment variables injected by this provider. Merged at launch time with env resolver and agent provider env. */
|
|
58
|
+
readonly env?: Record<string, string>;
|
|
59
|
+
/**
|
|
60
|
+
* Maximum number of characters of streamed `exec` output retained per stream
|
|
61
|
+
* (stdout and stderr) when an `onLine` callback is supplied (default: 64KiB).
|
|
62
|
+
*
|
|
63
|
+
* Output is delivered live to `onLine` regardless; this only bounds the tail
|
|
64
|
+
* returned in `ExecResult`, preventing a long-running agent's output from
|
|
65
|
+
* overflowing V8's max string length and crashing the run.
|
|
66
|
+
*/
|
|
67
|
+
readonly maxOutputTailChars?: number;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Create a Modal isolated sandbox provider.
|
|
71
|
+
*
|
|
72
|
+
* Each `create()` starts a new Modal sandbox via the `modal` SDK, and
|
|
73
|
+
* `close()` terminates it. Requires `modal` to be installed as a peer
|
|
74
|
+
* dependency.
|
|
75
|
+
*/
|
|
76
|
+
declare const modal: (options?: ModalOptions) => IsolatedSandboxProvider;
|
|
77
|
+
|
|
78
|
+
export { type ModalOptions, modal };
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import { createIsolatedSandboxProvider } from '../chunk-BVZWLFFT.js';
|
|
3
|
+
import { MAX_TAIL_CHARS, BoundedTail } from '../chunk-6NQPCXSG.js';
|
|
4
|
+
import { stat, readdir } from 'fs/promises';
|
|
5
|
+
import { relative, sep, posix, join } from 'path';
|
|
6
|
+
|
|
7
|
+
createRequire(import.meta.url);
|
|
8
|
+
|
|
9
|
+
// src/sandboxes/modalExec.ts
|
|
10
|
+
var forEachLine = async (stream, onLine) => {
|
|
11
|
+
let partial = "";
|
|
12
|
+
for await (const chunk of stream) {
|
|
13
|
+
const lines = (partial + chunk).split("\n");
|
|
14
|
+
partial = lines.pop() ?? "";
|
|
15
|
+
for (const line of lines) {
|
|
16
|
+
onLine(line);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
if (partial !== "") {
|
|
20
|
+
onLine(partial);
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
var drainInto = async (stream, tail) => {
|
|
24
|
+
for await (const chunk of stream) {
|
|
25
|
+
tail.push(chunk);
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
var feedStdin = async (proc, stdin) => {
|
|
29
|
+
if (stdin !== void 0 && stdin !== "") {
|
|
30
|
+
await proc.stdin.writeText(stdin);
|
|
31
|
+
}
|
|
32
|
+
await proc.stdin.close();
|
|
33
|
+
};
|
|
34
|
+
var collectStreamed = async (proc, onLine, maxOutputTailChars) => {
|
|
35
|
+
const stdoutTail = new BoundedTail(maxOutputTailChars, "\n");
|
|
36
|
+
const stderrTail = new BoundedTail(maxOutputTailChars, "");
|
|
37
|
+
await Promise.all([
|
|
38
|
+
forEachLine(proc.stdout, (line) => {
|
|
39
|
+
stdoutTail.push(line);
|
|
40
|
+
onLine(line);
|
|
41
|
+
}),
|
|
42
|
+
drainInto(proc.stderr, stderrTail)
|
|
43
|
+
]);
|
|
44
|
+
const exitCode = await proc.wait();
|
|
45
|
+
return {
|
|
46
|
+
stdout: stdoutTail.toString(),
|
|
47
|
+
stderr: stderrTail.toString(),
|
|
48
|
+
exitCode
|
|
49
|
+
};
|
|
50
|
+
};
|
|
51
|
+
var collectBuffered = async (proc) => {
|
|
52
|
+
const [stdout, stderr] = await Promise.all([
|
|
53
|
+
proc.stdout.readText(),
|
|
54
|
+
proc.stderr.readText()
|
|
55
|
+
]);
|
|
56
|
+
const exitCode = await proc.wait();
|
|
57
|
+
return { stdout, stderr, exitCode };
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
// src/sandboxes/modal.ts
|
|
61
|
+
var MODAL_REPO_PATH = "/workspace";
|
|
62
|
+
var DEFAULT_APP_NAME = "sandcastle";
|
|
63
|
+
var DEFAULT_TIMEOUT_MS = 60 * 60 * 1e3;
|
|
64
|
+
var DEFAULT_BASE_IMAGE = "node:24-bookworm";
|
|
65
|
+
var DEFAULT_IMAGE_COMMANDS = [
|
|
66
|
+
"RUN npm install -g @anthropic-ai/claude-code && npm cache clean --force"
|
|
67
|
+
];
|
|
68
|
+
var toClientParams = (options) => Object.fromEntries(
|
|
69
|
+
Object.entries({
|
|
70
|
+
tokenId: options?.tokenId,
|
|
71
|
+
tokenSecret: options?.tokenSecret,
|
|
72
|
+
environment: options?.environment
|
|
73
|
+
}).filter(([, value]) => value !== void 0 && value !== "")
|
|
74
|
+
);
|
|
75
|
+
var toImage = (client, image) => {
|
|
76
|
+
if (typeof image === "string" && image !== "") {
|
|
77
|
+
return client.images.fromRegistry(image);
|
|
78
|
+
}
|
|
79
|
+
if (image !== void 0 && typeof image !== "string") {
|
|
80
|
+
return image;
|
|
81
|
+
}
|
|
82
|
+
return client.images.fromRegistry(DEFAULT_BASE_IMAGE).dockerfileCommands(DEFAULT_IMAGE_COMMANDS);
|
|
83
|
+
};
|
|
84
|
+
var listFiles = async (dir) => {
|
|
85
|
+
const entries = await readdir(dir, { withFileTypes: true, recursive: true });
|
|
86
|
+
return entries.filter((entry) => !entry.isDirectory()).map((entry) => join(entry.parentPath, entry.name));
|
|
87
|
+
};
|
|
88
|
+
var copyIn = async (sandbox, hostPath, sandboxPath) => {
|
|
89
|
+
const info = await stat(hostPath);
|
|
90
|
+
if (!info.isDirectory()) {
|
|
91
|
+
await sandbox.filesystem.copyFromLocal(hostPath, sandboxPath);
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
await sandbox.filesystem.makeDirectory(sandboxPath);
|
|
95
|
+
const files = await listFiles(hostPath);
|
|
96
|
+
await files.reduce(async (previous, file) => {
|
|
97
|
+
await previous;
|
|
98
|
+
const rel = relative(hostPath, file).split(sep).join("/");
|
|
99
|
+
await sandbox.filesystem.copyFromLocal(file, posix.join(sandboxPath, rel));
|
|
100
|
+
}, Promise.resolve());
|
|
101
|
+
};
|
|
102
|
+
var setUpOrTerminate = async (sandbox) => {
|
|
103
|
+
try {
|
|
104
|
+
await sandbox.filesystem.makeDirectory(MODAL_REPO_PATH);
|
|
105
|
+
} catch (error) {
|
|
106
|
+
await sandbox.terminate().catch(() => void 0);
|
|
107
|
+
throw new Error(
|
|
108
|
+
`modal(): could not create ${MODAL_REPO_PATH}: ${error instanceof Error ? error.message : String(error)}`,
|
|
109
|
+
{ cause: error }
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
var makeHandle = (client, sandbox, maxOutputTailChars) => ({
|
|
114
|
+
worktreePath: MODAL_REPO_PATH,
|
|
115
|
+
sandboxId: sandbox.sandboxId,
|
|
116
|
+
// Commands already run as root, so `sudo` needs nothing more.
|
|
117
|
+
exec: async (command, opts) => {
|
|
118
|
+
const proc = await sandbox.exec(["sh", "-c", command], {
|
|
119
|
+
workdir: opts?.cwd ?? MODAL_REPO_PATH
|
|
120
|
+
});
|
|
121
|
+
await feedStdin(proc, opts?.stdin);
|
|
122
|
+
return opts?.onLine ? collectStreamed(proc, opts.onLine, maxOutputTailChars) : collectBuffered(proc);
|
|
123
|
+
},
|
|
124
|
+
copyIn: async (hostPath, sandboxPath) => copyIn(sandbox, hostPath, sandboxPath),
|
|
125
|
+
copyFileOut: async (sandboxPath, hostPath) => sandbox.filesystem.copyToLocal(sandboxPath, hostPath),
|
|
126
|
+
close: async () => {
|
|
127
|
+
try {
|
|
128
|
+
await sandbox.terminate();
|
|
129
|
+
} finally {
|
|
130
|
+
client.close();
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
});
|
|
134
|
+
var modal = (options) => createIsolatedSandboxProvider({
|
|
135
|
+
name: "modal",
|
|
136
|
+
// Modal runs every command as root, where Claude Code refuses
|
|
137
|
+
// --dangerously-skip-permissions unless it knows it is in a sandbox.
|
|
138
|
+
env: { IS_SANDBOX: "1", ...options?.env },
|
|
139
|
+
create: async (createOptions) => {
|
|
140
|
+
const { ModalClient } = await import('modal');
|
|
141
|
+
const client = new ModalClient(toClientParams(options));
|
|
142
|
+
try {
|
|
143
|
+
const app = await client.apps.fromName(
|
|
144
|
+
options?.appName ?? DEFAULT_APP_NAME,
|
|
145
|
+
{ createIfMissing: true }
|
|
146
|
+
);
|
|
147
|
+
const sandbox = await client.sandboxes.create(
|
|
148
|
+
app,
|
|
149
|
+
toImage(client, options?.image),
|
|
150
|
+
{
|
|
151
|
+
...options?.create,
|
|
152
|
+
timeoutMs: options?.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
|
153
|
+
env: { ...createOptions.env, ...options?.create?.env }
|
|
154
|
+
}
|
|
155
|
+
);
|
|
156
|
+
await setUpOrTerminate(sandbox);
|
|
157
|
+
return makeHandle(
|
|
158
|
+
client,
|
|
159
|
+
sandbox,
|
|
160
|
+
options?.maxOutputTailChars ?? MAX_TAIL_CHARS
|
|
161
|
+
);
|
|
162
|
+
} catch (error) {
|
|
163
|
+
client.close();
|
|
164
|
+
throw error;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
export { modal };
|
|
170
|
+
//# sourceMappingURL=modal.js.map
|
|
171
|
+
//# sourceMappingURL=modal.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/sandboxes/modalExec.ts","../../src/sandboxes/modal.ts"],"names":[],"mappings":";;;;;;;;;AAUA,IAAM,WAAA,GAAc,OAClB,MAAA,EACA,MAAA,KACkB;AAClB,EAAA,IAAI,OAAA,GAAU,EAAA;AACd,EAAA,WAAA,MAAiB,SAAS,MAAA,EAAQ;AAChC,IAAA,MAAM,KAAA,GAAA,CAAS,OAAA,GAAU,KAAA,EAAO,KAAA,CAAM,IAAI,CAAA;AAC1C,IAAA,OAAA,GAAU,KAAA,CAAM,KAAI,IAAK,EAAA;AACzB,IAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,MAAA,MAAA,CAAO,IAAI,CAAA;AAAA,IACb;AAAA,EACF;AAEA,EAAA,IAAI,YAAY,EAAA,EAAI;AAClB,IAAA,MAAA,CAAO,OAAO,CAAA;AAAA,EAChB;AACF,CAAA;AAGA,IAAM,SAAA,GAAY,OAChB,MAAA,EACA,IAAA,KACkB;AAClB,EAAA,WAAA,MAAiB,SAAS,MAAA,EAAQ;AAChC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8B;AAAA,EAC5B,IAAA,EAAM,OAAA;AAAA;AAAA;AAAA,EAGN,KAAK,EAAE,UAAA,EAAY,GAAA,EAAK,GAAG,SAAS,GAAA,EAAI;AAAA,EACxC,MAAA,EAAQ,OAAO,aAAA,KAAkD;AAE/D,IAAA,MAAM,EAAE,WAAA,EAAY,GAAI,MAAM,OAAO,OAAO,CAAA;AAC5C,IAAA,MAAM,MAAA,GAAS,IAAI,WAAA,CAAY,cAAA,CAAe,OAAO,CAAC,CAAA;AACtD,IAAA,IAAI;AACF,MAAA,MAAM,GAAA,GAAM,MAAM,MAAA,CAAO,IAAA,CAAK,QAAA;AAAA,QAC5B,SAAS,OAAA,IAAW,gBAAA;AAAA,QACpB,EAAE,iBAAiB,IAAA;AAAK,OAC1B;AACA,MAAA,MAAM,OAAA,GAAU,MAAM,MAAA,CAAO,SAAA,CAAU,MAAA;AAAA,QACrC,GAAA;AAAA,QACA,OAAA,CAAQ,MAAA,EAAQ,OAAA,EAAS,KAAK,CAAA;AAAA,QAC9B;AAAA,UACE,GAAG,OAAA,EAAS,MAAA;AAAA,UACZ,SAAA,EAAW,SAAS,SAAA,IAAa,kBAAA;AAAA,UACjC,GAAA,EAAK,EAAE,GAAG,aAAA,CAAc,KAAK,GAAG,OAAA,EAAS,QAAQ,GAAA;AAAI;AACvD,OACF;AACA,MAAA,MAAM,iBAAiB,OAAO,CAAA;AAC9B,MAAA,OAAO,UAAA;AAAA,QACL,MAAA;AAAA,QACA,OAAA;AAAA,QACA,SAAS,kBAAA,IAAsB;AAAA,OACjC;AAAA,IACF,SAAS,KAAA,EAAO;AACd,MAAA,MAAA,CAAO,KAAA,EAAM;AACb,MAAA,MAAM,KAAA;AAAA,IACR;AAAA,EACF;AACF,CAAC","file":"modal.js","sourcesContent":["/**\n * Waiting on a command in a Modal sandbox: stdin, streamed or buffered\n * output, and the exit code. Used by `modal()` only.\n */\n\nimport type { ExecResult } from \"../SandboxProvider.js\";\nimport { BoundedTail } from \"../boundedTail.js\";\nimport type { ContainerProcess } from \"modal\";\n\n/** Read a text stream to its end, handing each line to `onLine`. */\nconst forEachLine = async (\n stream: ReadableStream<string>,\n onLine: (line: string) => void,\n): Promise<void> => {\n let partial = \"\";\n for await (const chunk of stream) {\n const lines = (partial + chunk).split(\"\\n\");\n partial = lines.pop() ?? \"\";\n for (const line of lines) {\n onLine(line);\n }\n }\n // A last line with no trailing newline is still a line.\n if (partial !== \"\") {\n onLine(partial);\n }\n};\n\n/** Read a text stream to its end, keeping a bounded tail of it. */\nconst drainInto = async (\n stream: ReadableStream<string>,\n tail: BoundedTail,\n): Promise<void> => {\n for await (const chunk of stream) {\n tail.push(chunk);\n }\n};\n\n/** Pipe `stdin` (if any) to the process, then close it so it reads EOF. */\nexport const feedStdin = async (\n proc: ContainerProcess<string>,\n stdin: string | undefined,\n): Promise<void> => {\n if (stdin !== undefined && stdin !== \"\") {\n await proc.stdin.writeText(stdin);\n }\n await proc.stdin.close();\n};\n\n/** Wait for a process, streaming its stdout lines to `onLine`. */\nexport const collectStreamed = async (\n proc: ContainerProcess<string>,\n onLine: (line: string) => void,\n maxOutputTailChars: number,\n): Promise<ExecResult> => {\n const stdoutTail = new BoundedTail(maxOutputTailChars, \"\\n\");\n const stderrTail = new BoundedTail(maxOutputTailChars, \"\");\n await Promise.all([\n forEachLine(proc.stdout, (line) => {\n stdoutTail.push(line);\n onLine(line);\n }),\n drainInto(proc.stderr, stderrTail),\n ]);\n const exitCode = await proc.wait();\n return {\n stdout: stdoutTail.toString(),\n stderr: stderrTail.toString(),\n exitCode,\n };\n};\n\n/** Wait for a process and return its whole output. */\nexport const collectBuffered = async (\n proc: ContainerProcess<string>,\n): Promise<ExecResult> => {\n const [stdout, stderr] = await Promise.all([\n proc.stdout.readText(),\n proc.stderr.readText(),\n ]);\n const exitCode = await proc.wait();\n return { stdout, stderr, exitCode };\n};\n","/**\n * Modal isolated sandbox provider — wraps the `modal` SDK into a SandboxProvider.\n *\n * Usage:\n * import { modal } from \"@ai-hero/sandcastle/sandboxes/modal\";\n * await run({ agent: claudeCode(\"claude-opus-4-8\"), sandbox: modal() });\n */\n\nimport { readdir, stat } from \"node:fs/promises\";\nimport { join, posix, relative, sep } from \"node:path\";\nimport { createIsolatedSandboxProvider } from \"../SandboxProvider.js\";\nimport type {\n ExecResult,\n IsolatedSandboxHandle,\n IsolatedSandboxProvider,\n} from \"../SandboxProvider.js\";\nimport { MAX_TAIL_CHARS } from \"../boundedTail.js\";\nimport { collectBuffered, collectStreamed, feedStdin } from \"./modalExec.js\";\nimport type {\n Image,\n ModalClient,\n ModalClientParams,\n Sandbox,\n SandboxCreateParams,\n} from \"modal\";\n\n/** Worktree path inside the Modal sandbox. Its parent, `/`, is root's. */\nconst MODAL_REPO_PATH = \"/workspace\";\n\n/** The Modal App sandboxes are created in, unless `appName` says otherwise. */\nconst DEFAULT_APP_NAME = \"sandcastle\";\n\n/** The sandbox's lifetime unless `timeoutMs` says otherwise: one hour. */\nconst DEFAULT_TIMEOUT_MS = 60 * 60 * 1000;\n\n/** The registry image the default image is built on: Node LTS, with git. */\nconst DEFAULT_BASE_IMAGE = \"node:24-bookworm\";\n\n/** Installs Claude Code into the default image. */\nconst DEFAULT_IMAGE_COMMANDS = [\n \"RUN npm install -g @anthropic-ai/claude-code && npm cache clean --force\",\n];\n\n/** Options for the Modal sandbox provider. */\nexport interface ModalOptions {\n /**\n * Modal token id. Falls back to the `MODAL_TOKEN_ID` environment variable,\n * then to `~/.modal.toml` (written by `modal token new`).\n */\n readonly tokenId?: string;\n\n /**\n * Modal token secret. Falls back to the `MODAL_TOKEN_SECRET` environment\n * variable, then to `~/.modal.toml`.\n */\n readonly tokenSecret?: string;\n\n /**\n * Modal environment to create sandboxes in. Falls back to\n * `MODAL_ENVIRONMENT`, then to the profile's default.\n */\n readonly environment?: string;\n\n /**\n * Name of the Modal App the sandboxes belong to (default: `\"sandcastle\"`).\n * It is created if it does not exist; no deploy step is needed.\n */\n readonly appName?: string;\n\n /**\n * The sandbox image: a registry tag such as `\"node:24-bookworm\"`, or a\n * Modal `Image` you built yourself (e.g. with `dockerfileCommands`).\n *\n * Omit it for Sandcastle's default: `node:24-bookworm` (Node LTS, git, tar)\n * with Claude Code installed. Any other image must have `sh`, `git` and\n * your agent's CLI, or install the CLI in an `onSandboxReady` hook.\n *\n * Modal runs every command as root, whatever the image's `USER`.\n */\n readonly image?: string | Image;\n\n /**\n * Maximum lifetime of the sandbox in milliseconds (default: one hour,\n * Modal's own default is 5 minutes). Modal can't extend it after create,\n * so set it above your longest run. Modal allows up to 24 hours.\n */\n readonly timeoutMs?: number;\n\n /**\n * Other `sandboxes.create()` options, passed through to Modal (`cpu`,\n * `memoryMiB`, `regions`, `blockNetwork`, …). Its `env` wins over the\n * env Sandcastle resolves.\n */\n readonly create?: Omit<SandboxCreateParams, \"timeoutMs\">;\n\n /** Environment variables injected by this provider. Merged at launch time with env resolver and agent provider env. */\n readonly env?: Record<string, string>;\n\n /**\n * Maximum number of characters of streamed `exec` output retained per stream\n * (stdout and stderr) when an `onLine` callback is supplied (default: 64KiB).\n *\n * Output is delivered live to `onLine` regardless; this only bounds the tail\n * returned in `ExecResult`, preventing a long-running agent's output from\n * overflowing V8's max string length and crashing the run.\n */\n readonly maxOutputTailChars?: number;\n}\n\n/** The `ModalClient` params: only the connection options that are set. */\nconst toClientParams = (options: ModalOptions | undefined): ModalClientParams =>\n Object.fromEntries(\n Object.entries({\n tokenId: options?.tokenId,\n tokenSecret: options?.tokenSecret,\n environment: options?.environment,\n }).filter(([, value]) => value !== undefined && value !== \"\"),\n );\n\n/** The image to create the sandbox from. */\nconst toImage = (\n client: ModalClient,\n image: string | Image | undefined,\n): Image => {\n if (typeof image === \"string\" && image !== \"\") {\n return client.images.fromRegistry(image);\n }\n if (image !== undefined && typeof image !== \"string\") {\n return image;\n }\n return client.images\n .fromRegistry(DEFAULT_BASE_IMAGE)\n .dockerfileCommands(DEFAULT_IMAGE_COMMANDS);\n};\n\n/** Every file under a host directory, recursively. */\nconst listFiles = async (dir: string): Promise<string[]> => {\n const entries = await readdir(dir, { withFileTypes: true, recursive: true });\n return entries\n .filter((entry) => !entry.isDirectory())\n .map((entry) => join(entry.parentPath, entry.name));\n};\n\n/** Copy a host file or directory into the sandbox. */\nconst copyIn = async (\n sandbox: Sandbox,\n hostPath: string,\n sandboxPath: string,\n): Promise<void> => {\n const info = await stat(hostPath);\n if (!info.isDirectory()) {\n await sandbox.filesystem.copyFromLocal(hostPath, sandboxPath);\n return;\n }\n await sandbox.filesystem.makeDirectory(sandboxPath);\n const files = await listFiles(hostPath);\n // One file at a time: each copy is its own exec in the sandbox.\n await files.reduce(async (previous, file) => {\n await previous;\n const rel = relative(hostPath, file).split(sep).join(\"/\");\n await sandbox.filesystem.copyFromLocal(file, posix.join(sandboxPath, rel));\n }, Promise.resolve());\n};\n\n/**\n * Create the worktree folder in a sandbox `create()` has just made. If that\n * fails, terminate the sandbox before rethrowing: no handle exists yet, so\n * neither Sandcastle's teardown nor `close()` can reach it, and it would run\n * until its timeout.\n */\nconst setUpOrTerminate = async (sandbox: Sandbox): Promise<void> => {\n try {\n await sandbox.filesystem.makeDirectory(MODAL_REPO_PATH);\n } catch (error) {\n await sandbox.terminate().catch(() => undefined);\n throw new Error(\n `modal(): could not create ${MODAL_REPO_PATH}: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n};\n\n/** The Sandcastle handle over a Modal sandbox whose worktree folder exists. */\nconst makeHandle = (\n client: ModalClient,\n sandbox: Sandbox,\n maxOutputTailChars: number,\n): IsolatedSandboxHandle => ({\n worktreePath: MODAL_REPO_PATH,\n sandboxId: sandbox.sandboxId,\n\n // Commands already run as root, so `sudo` needs nothing more.\n exec: async (command, opts): Promise<ExecResult> => {\n const proc = await sandbox.exec([\"sh\", \"-c\", command], {\n workdir: opts?.cwd ?? MODAL_REPO_PATH,\n });\n await feedStdin(proc, opts?.stdin);\n return opts?.onLine\n ? collectStreamed(proc, opts.onLine, maxOutputTailChars)\n : collectBuffered(proc);\n },\n\n copyIn: async (hostPath, sandboxPath) =>\n copyIn(sandbox, hostPath, sandboxPath),\n\n copyFileOut: async (sandboxPath, hostPath) =>\n sandbox.filesystem.copyToLocal(sandboxPath, hostPath),\n\n close: async (): Promise<void> => {\n try {\n await sandbox.terminate();\n } finally {\n client.close();\n }\n },\n});\n\n/**\n * Create a Modal isolated sandbox provider.\n *\n * Each `create()` starts a new Modal sandbox via the `modal` SDK, and\n * `close()` terminates it. Requires `modal` to be installed as a peer\n * dependency.\n */\nexport const modal = (options?: ModalOptions): IsolatedSandboxProvider =>\n createIsolatedSandboxProvider({\n name: \"modal\",\n // Modal runs every command as root, where Claude Code refuses\n // --dangerously-skip-permissions unless it knows it is in a sandbox.\n env: { IS_SANDBOX: \"1\", ...options?.env },\n create: async (createOptions): Promise<IsolatedSandboxHandle> => {\n // Dynamic import so the peer dependency is only loaded at runtime\n const { ModalClient } = await import(\"modal\");\n const client = new ModalClient(toClientParams(options));\n try {\n const app = await client.apps.fromName(\n options?.appName ?? DEFAULT_APP_NAME,\n { createIfMissing: true },\n );\n const sandbox = await client.sandboxes.create(\n app,\n toImage(client, options?.image),\n {\n ...options?.create,\n timeoutMs: options?.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n env: { ...createOptions.env, ...options?.create?.env },\n },\n );\n await setUpOrTerminate(sandbox);\n return makeHandle(\n client,\n sandbox,\n options?.maxOutputTailChars ?? MAX_TAIL_CHARS,\n );\n } catch (error) {\n client.close();\n throw error;\n }\n },\n });\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';
|
|
2
|
-
export { noSandbox } from '../chunk-
|
|
3
|
-
import '../chunk-
|
|
2
|
+
export { noSandbox } from '../chunk-7N7AMUYA.js';
|
|
3
|
+
import '../chunk-6NQPCXSG.js';
|
|
4
4
|
|
|
5
5
|
createRequire(import.meta.url);
|
|
6
6
|
//# sourceMappingURL=no-sandbox.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { S as SandboxProvider } from '../SandboxProvider-
|
|
1
|
+
import { S as SandboxProvider } from '../SandboxProvider-Chsi-Zs6.js';
|
|
2
2
|
import { M as MountConfig } from '../MountConfig-CmXclHA5.js';
|
|
3
|
-
import { S as SelinuxLabel } from '../
|
|
4
|
-
export { d as defaultImageName } from '../
|
|
3
|
+
import { S as SelinuxLabel, L as LinuxCapability } from '../LinuxCapability-B_PQfsY_.js';
|
|
4
|
+
export { d as defaultImageName } from '../LinuxCapability-B_PQfsY_.js';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Podman sandbox provider — creates Podman containers with bind-mounts.
|
|
@@ -76,6 +76,20 @@ interface PodmanOptions {
|
|
|
76
76
|
* When omitted, no `--group-add` flags are added.
|
|
77
77
|
*/
|
|
78
78
|
readonly groups?: readonly (string | number)[];
|
|
79
|
+
/**
|
|
80
|
+
* Linux capabilities to drop from the container, via `--cap-drop`.
|
|
81
|
+
*
|
|
82
|
+
* Names are written without the `CAP_` prefix, as `podman run` accepts them,
|
|
83
|
+
* and a misspelt name is a type error:
|
|
84
|
+
*
|
|
85
|
+
* - `["NET_RAW"]` → `--cap-drop NET_RAW` (no raw sockets, so no `ping`)
|
|
86
|
+
* - `["NET_RAW", "MKNOD"]` → `--cap-drop NET_RAW --cap-drop MKNOD`
|
|
87
|
+
* - `["ALL"]` → `--cap-drop ALL` (drop every capability)
|
|
88
|
+
*
|
|
89
|
+
* When omitted, no `--cap-drop` flags are added and the container keeps
|
|
90
|
+
* Podman's default capability set.
|
|
91
|
+
*/
|
|
92
|
+
readonly capDrop?: readonly LinuxCapability[];
|
|
79
93
|
/**
|
|
80
94
|
* Host devices to expose to the container, via `--device`.
|
|
81
95
|
*
|
|
@@ -121,4 +135,4 @@ interface PodmanOptions {
|
|
|
121
135
|
*/
|
|
122
136
|
declare const podman: (options?: PodmanOptions) => SandboxProvider;
|
|
123
137
|
|
|
124
|
-
export { type PodmanOptions, podman };
|
|
138
|
+
export { LinuxCapability, type PodmanOptions, podman };
|