@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.
Files changed (77) hide show
  1. package/README.md +15 -1368
  2. package/dist/LinuxCapability-B_PQfsY_.d.ts +32 -0
  3. package/dist/{SandboxProvider-EkSMuBp8.d.ts → SandboxProvider-Chsi-Zs6.d.ts} +31 -3
  4. package/dist/{chunk-NGBM7T3E.js → chunk-6NQPCXSG.js} +5 -2
  5. package/dist/chunk-6NQPCXSG.js.map +1 -0
  6. package/dist/chunk-7N7AMUYA.js +353 -0
  7. package/dist/chunk-7N7AMUYA.js.map +1 -0
  8. package/dist/chunk-ATA2V2TC.js +112 -0
  9. package/dist/chunk-ATA2V2TC.js.map +1 -0
  10. package/dist/chunk-BIF2X6QB.js +94 -0
  11. package/dist/chunk-BIF2X6QB.js.map +1 -0
  12. package/dist/{chunk-BIWNFKGV.js → chunk-BVZWLFFT.js} +2 -2
  13. package/dist/chunk-BVZWLFFT.js.map +1 -0
  14. package/dist/chunk-EXYXBRCX.js +60 -0
  15. package/dist/chunk-EXYXBRCX.js.map +1 -0
  16. package/dist/chunk-G2R53CVZ.js +3172 -0
  17. package/dist/chunk-G2R53CVZ.js.map +1 -0
  18. package/dist/{chunk-CP3TYXZA.js → chunk-GCLEXPXG.js} +95 -85
  19. package/dist/chunk-GCLEXPXG.js.map +1 -0
  20. package/dist/chunk-H2PEFS4W.js +1244 -0
  21. package/dist/chunk-H2PEFS4W.js.map +1 -0
  22. package/dist/chunk-HSXPRZKG.js +150 -0
  23. package/dist/chunk-HSXPRZKG.js.map +1 -0
  24. package/dist/chunk-IBK2XNSS.js +50 -0
  25. package/dist/chunk-IBK2XNSS.js.map +1 -0
  26. package/dist/chunk-RDW7FNN6.js +792 -0
  27. package/dist/chunk-RDW7FNN6.js.map +1 -0
  28. package/dist/{chunk-DJRHWPEH.js → chunk-S6UHPTRG.js} +284 -352
  29. package/dist/chunk-S6UHPTRG.js.map +1 -0
  30. package/dist/{chunk-VOG34SRF.js → chunk-STB2U7BB.js} +11823 -6977
  31. package/dist/chunk-STB2U7BB.js.map +1 -0
  32. package/dist/chunk-VRXR2T3S.js +24 -0
  33. package/dist/chunk-VRXR2T3S.js.map +1 -0
  34. package/dist/index.d.ts +241 -26
  35. package/dist/index.js +1082 -1679
  36. package/dist/index.js.map +1 -1
  37. package/dist/main.js +1248 -854
  38. package/dist/main.js.map +1 -1
  39. package/dist/sandboxes/bwrap.d.ts +58 -0
  40. package/dist/sandboxes/bwrap.js +296 -0
  41. package/dist/sandboxes/bwrap.js.map +1 -0
  42. package/dist/sandboxes/daytona.d.ts +1 -1
  43. package/dist/sandboxes/daytona.js +203 -98
  44. package/dist/sandboxes/daytona.js.map +1 -1
  45. package/dist/sandboxes/docker.d.ts +18 -4
  46. package/dist/sandboxes/docker.js +7 -4
  47. package/dist/sandboxes/e2b.d.ts +41 -0
  48. package/dist/sandboxes/e2b.js +202 -0
  49. package/dist/sandboxes/e2b.js.map +1 -0
  50. package/dist/sandboxes/modal.d.ts +78 -0
  51. package/dist/sandboxes/modal.js +171 -0
  52. package/dist/sandboxes/modal.js.map +1 -0
  53. package/dist/sandboxes/no-sandbox.d.ts +1 -1
  54. package/dist/sandboxes/no-sandbox.js +2 -2
  55. package/dist/sandboxes/podman.d.ts +18 -4
  56. package/dist/sandboxes/podman.js +72 -56
  57. package/dist/sandboxes/podman.js.map +1 -1
  58. package/dist/sandboxes/seatbelt.d.ts +65 -0
  59. package/dist/sandboxes/seatbelt.js +425 -0
  60. package/dist/sandboxes/seatbelt.js.map +1 -0
  61. package/dist/sandboxes/sprites.d.ts +54 -0
  62. package/dist/sandboxes/sprites.js +198 -0
  63. package/dist/sandboxes/sprites.js.map +1 -0
  64. package/dist/sandboxes/vercel.d.ts +12 -5
  65. package/dist/sandboxes/vercel.js +195 -126
  66. package/dist/sandboxes/vercel.js.map +1 -1
  67. package/dist/templates/parallel-planner/main.mts +13 -22
  68. package/dist/templates/parallel-planner-with-review/main.mts +13 -15
  69. package/package.json +63 -11
  70. package/dist/chunk-62WN33RK.js +0 -104
  71. package/dist/chunk-62WN33RK.js.map +0 -1
  72. package/dist/chunk-BIWNFKGV.js.map +0 -1
  73. package/dist/chunk-CP3TYXZA.js.map +0 -1
  74. package/dist/chunk-DJRHWPEH.js.map +0 -1
  75. package/dist/chunk-NGBM7T3E.js.map +0 -1
  76. package/dist/chunk-VOG34SRF.js.map +0 -1
  77. package/dist/mountUtils-CCA-bbpK.d.ts +0 -25
@@ -0,0 +1,198 @@
1
+ import { createRequire } from 'node:module';
2
+ import { registerShutdown } from '../chunk-EXYXBRCX.js';
3
+ import { Effect_exports, Config_exports } from '../chunk-STB2U7BB.js';
4
+ import { createIsolatedSandboxProvider } from '../chunk-BVZWLFFT.js';
5
+ import { MAX_TAIL_CHARS, BoundedTail } from '../chunk-6NQPCXSG.js';
6
+ import { randomUUID } from 'crypto';
7
+ import { mkdir, writeFile, stat, readFile, readdir } from 'fs/promises';
8
+ import { posix, dirname, join, relative } from 'path';
9
+ import { once } from 'events';
10
+ import { spawn } from 'child_process';
11
+
12
+ createRequire(import.meta.url);
13
+ var shellEscape = (s) => `'${s.replaceAll("'", String.raw`'\''`)}'`;
14
+ var outputSink = (separator, maxChars, onLine) => {
15
+ const chunks = [];
16
+ const tail = new BoundedTail(maxChars, separator);
17
+ let partial = "";
18
+ const emit = (line) => {
19
+ tail.push(line);
20
+ onLine?.(line);
21
+ };
22
+ return {
23
+ push: (chunk) => {
24
+ if (maxChars === void 0) {
25
+ chunks.push(chunk.toString());
26
+ return;
27
+ }
28
+ if (onLine === void 0) {
29
+ tail.push(chunk.toString());
30
+ return;
31
+ }
32
+ const lines = (partial + chunk.toString()).split("\n");
33
+ partial = lines.pop() ?? "";
34
+ for (const line of lines) {
35
+ emit(line);
36
+ }
37
+ },
38
+ flush: () => {
39
+ if (partial !== "") {
40
+ emit(partial);
41
+ partial = "";
42
+ }
43
+ },
44
+ toString: () => maxChars === void 0 ? chunks.join("") : tail.toString()
45
+ };
46
+ };
47
+ var execInSprite = async (sprite, request) => {
48
+ const { command, onLine, maxOutputTailChars } = request;
49
+ const line = request.sudo === true ? `sudo sh -c ${shellEscape(command)}` : command;
50
+ const proc = sprite.spawn("sh", ["-c", line], {
51
+ cwd: request.cwd,
52
+ env: request.env
53
+ });
54
+ const streamed = onLine !== void 0;
55
+ const stdout = outputSink(
56
+ "\n",
57
+ streamed ? maxOutputTailChars : void 0,
58
+ onLine
59
+ );
60
+ const stderr = outputSink("", streamed ? maxOutputTailChars : void 0);
61
+ proc.stdout.on("data", stdout.push);
62
+ proc.stderr.on("data", stderr.push);
63
+ proc.once("spawn", () => {
64
+ proc.stdin.end(request.stdin ?? "");
65
+ });
66
+ proc.on("error", () => void 0);
67
+ const [exitArgs] = await Promise.all([
68
+ once(proc, "exit"),
69
+ once(proc.stdout, "end"),
70
+ once(proc.stderr, "end")
71
+ ]);
72
+ const exitCode = exitArgs?.[0];
73
+ stdout.flush();
74
+ if (typeof exitCode !== "number" || exitCode < 0) {
75
+ throw new Error(
76
+ `sprites(): the connection closed before the command exited: ${command}`
77
+ );
78
+ }
79
+ return { stdout: stdout.toString(), stderr: stderr.toString(), exitCode };
80
+ };
81
+ var DELETE_SCRIPT = "fetch(process.argv[1], { method: 'DELETE', headers: { Authorization: 'Bearer ' + process.env.SANDCASTLE_SPRITES_TOKEN } }).catch(() => {});";
82
+ var registerSpriteDeletion = (baseURL, token, name) => registerShutdown(() => {
83
+ const url = `${baseURL}/v1/sprites/${encodeURIComponent(name)}`;
84
+ spawn(process.execPath, ["-e", DELETE_SCRIPT, url], {
85
+ detached: true,
86
+ stdio: "ignore",
87
+ windowsHide: true,
88
+ env: { ...process.env, SANDCASTLE_SPRITES_TOKEN: token }
89
+ }).unref();
90
+ });
91
+
92
+ // src/sandboxes/sprites.ts
93
+ var SPRITE_HOME = "/home/sprite";
94
+ var SPRITES_REPO_PATH = posix.join(SPRITE_HOME, "workspace");
95
+ var setOrUndefined = (value) => value === "" ? void 0 : value;
96
+ var envTokens = Effect_exports.all([
97
+ Config_exports.string("SPRITES_TOKEN").pipe(Config_exports.withDefault("")),
98
+ Config_exports.string("SPRITE_TOKEN").pipe(Config_exports.withDefault(""))
99
+ ]);
100
+ var resolveToken = async (options) => {
101
+ const [plural, singular] = await Effect_exports.runPromise(envTokens);
102
+ const token = setOrUndefined(options?.token) ?? setOrUndefined(plural) ?? setOrUndefined(singular);
103
+ if (token === void 0) {
104
+ throw new Error(
105
+ "sprites(): no Sprites token. Set SPRITES_TOKEN (or SPRITE_TOKEN), or pass the token option."
106
+ );
107
+ }
108
+ return token;
109
+ };
110
+ var copyIntoSprite = async (sprite, hostPath, sandboxPath) => {
111
+ const fs = sprite.filesystem();
112
+ const info = await stat(hostPath);
113
+ if (!info.isDirectory()) {
114
+ await fs.writeFile(sandboxPath, await readFile(hostPath));
115
+ return;
116
+ }
117
+ const entries = await readdir(hostPath, {
118
+ withFileTypes: true,
119
+ recursive: true
120
+ });
121
+ const files = entries.filter((entry) => entry.isFile()).map((entry) => join(entry.parentPath, entry.name));
122
+ await Promise.all(
123
+ files.map(async (file) => {
124
+ const parts = relative(hostPath, file).split(/[\\/]/u);
125
+ await fs.writeFile(
126
+ posix.join(sandboxPath, ...parts),
127
+ await readFile(file)
128
+ );
129
+ })
130
+ );
131
+ };
132
+ var makeHandle = (sprite, { env, maxOutputTailChars, unregisterShutdown }) => ({
133
+ worktreePath: SPRITES_REPO_PATH,
134
+ // A Sprite is addressed by its name in the Sprites API and CLI.
135
+ sandboxId: sprite.name,
136
+ exec: async (command, opts) => execInSprite(sprite, {
137
+ ...opts,
138
+ command,
139
+ cwd: opts?.cwd ?? SPRITES_REPO_PATH,
140
+ env,
141
+ maxOutputTailChars
142
+ }),
143
+ copyIn: async (hostPath, sandboxPath) => copyIntoSprite(sprite, hostPath, sandboxPath),
144
+ copyFileOut: async (sandboxPath, hostPath) => {
145
+ const buffer = await sprite.filesystem().readFile(sandboxPath, null);
146
+ await mkdir(dirname(hostPath), { recursive: true });
147
+ await writeFile(hostPath, buffer);
148
+ },
149
+ close: async () => {
150
+ await sprite.delete();
151
+ unregisterShutdown();
152
+ }
153
+ });
154
+ var makeWorktreeDir = async (sprite) => {
155
+ const result = await execInSprite(sprite, {
156
+ command: `mkdir -p ${SPRITES_REPO_PATH}`,
157
+ cwd: SPRITE_HOME,
158
+ env: {},
159
+ maxOutputTailChars: MAX_TAIL_CHARS
160
+ });
161
+ if (result.exitCode !== 0) {
162
+ throw new Error(
163
+ `sprites(): could not create ${SPRITES_REPO_PATH}: ${result.stderr.trim()}`
164
+ );
165
+ }
166
+ };
167
+ var sprites = (options) => createIsolatedSandboxProvider({
168
+ name: "sprites",
169
+ env: options?.env,
170
+ create: async ({ env }) => {
171
+ const token = await resolveToken(options);
172
+ const { SpritesClient } = await import('@fly/sprites');
173
+ const client = new SpritesClient(token);
174
+ const name = `sandcastle-${randomUUID()}`;
175
+ const unregisterShutdown = registerSpriteDeletion(
176
+ client.baseURL,
177
+ token,
178
+ name
179
+ );
180
+ try {
181
+ const sprite = await client.createSprite(name);
182
+ await makeWorktreeDir(sprite);
183
+ return makeHandle(sprite, {
184
+ env,
185
+ maxOutputTailChars: options?.maxOutputTailChars ?? MAX_TAIL_CHARS,
186
+ unregisterShutdown
187
+ });
188
+ } catch (error) {
189
+ await client.deleteSprite(name).catch(() => void 0);
190
+ unregisterShutdown();
191
+ throw error;
192
+ }
193
+ }
194
+ });
195
+
196
+ export { sprites };
197
+ //# sourceMappingURL=sprites.js.map
198
+ //# sourceMappingURL=sprites.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/sandboxes/spritesExec.ts","../../src/sandboxes/spritesShutdown.ts","../../src/sandboxes/sprites.ts"],"names":[],"mappings":";;;;;;;;;;;;AAsBA,IAAM,WAAA,GAAc,CAAC,CAAA,KACnB,CAAA,CAAA,EAAI,EAAE,UAAA,CAAW,GAAA,EAAK,MAA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AO;AAGd,MAAA,MAAM,OAAO,YAAA,CAAa,IAAI,CAAA,CAAE,KAAA,CAAM,MAAM,MAAS,CAAA;AACrD,MAAA,kBAAA,EAAmB;AACnB,MAAA,MAAM,KAAA;AAAA,IACR;AAAA,EACF;AACF,CAAC","file":"sprites.js","sourcesContent":["/**\n * `exec` for the Fly.io Sprites provider (`sprites.ts`): runs a command over\n * the `@fly/sprites` exec WebSocket and streams its stdout lines.\n */\n\nimport { once } from \"node:events\";\nimport type { ExecResult } from \"../SandboxProvider.js\";\nimport { BoundedTail } from \"../boundedTail.js\";\nimport type { Sprite } from \"@fly/sprites\";\n\n/** What one `exec` in a Sprite needs. */\nexport interface SpriteExecRequest {\n readonly command: string;\n readonly cwd: string;\n readonly env: Record<string, string>;\n readonly onLine?: (line: string) => void;\n readonly sudo?: boolean;\n readonly stdin?: string;\n /** Bound on the stdout and stderr tails of a streamed `exec`. */\n readonly maxOutputTailChars: number;\n}\n\nconst shellEscape = (s: string): string =>\n `'${s.replaceAll(\"'\", String.raw`'\\''`)}'`;\n\n/**\n * A sink for one output stream. Streamed: each complete line goes to\n * `onLine` at once and into a bounded tail, and `flush()` hands over a last\n * line that has no trailing newline. Buffered: the whole output is kept.\n */\nconst outputSink = (\n separator: string,\n maxChars: number | undefined,\n onLine?: (line: string) => void,\n) => {\n const chunks: string[] = [];\n const tail = new BoundedTail(maxChars, separator);\n let partial = \"\";\n const emit = (line: string): void => {\n tail.push(line);\n onLine?.(line);\n };\n return {\n push: (chunk: Buffer): void => {\n if (maxChars === undefined) {\n chunks.push(chunk.toString());\n return;\n }\n if (onLine === undefined) {\n tail.push(chunk.toString());\n return;\n }\n const lines = (partial + chunk.toString()).split(\"\\n\");\n partial = lines.pop() ?? \"\";\n for (const line of lines) {\n emit(line);\n }\n },\n flush: (): void => {\n if (partial !== \"\") {\n emit(partial);\n partial = \"\";\n }\n },\n toString: (): string =>\n maxChars === undefined ? chunks.join(\"\") : tail.toString(),\n };\n};\n\n/**\n * Run a command in the Sprite. stdin is always sent and closed (empty when\n * unset), so a command that reads it gets EOF rather than waiting. With\n * `onLine`, stdout lines are delivered live as they arrive; without it, the\n * whole stdout comes back, as sync-out needs.\n */\nexport const execInSprite = async (\n sprite: Sprite,\n request: SpriteExecRequest,\n): Promise<ExecResult> => {\n const { command, onLine, maxOutputTailChars } = request;\n const line =\n request.sudo === true ? `sudo sh -c ${shellEscape(command)}` : command;\n const proc = sprite.spawn(\"sh\", [\"-c\", line], {\n cwd: request.cwd,\n env: request.env,\n });\n const streamed = onLine !== undefined;\n const stdout = outputSink(\n \"\\n\",\n streamed ? maxOutputTailChars : undefined,\n onLine,\n );\n const stderr = outputSink(\"\", streamed ? maxOutputTailChars : undefined);\n proc.stdout.on(\"data\", stdout.push);\n proc.stderr.on(\"data\", stderr.push);\n proc.once(\"spawn\", () => {\n proc.stdin.end(request.stdin ?? \"\");\n });\n // A late error, after the command has exited, must not crash the process.\n proc.on(\"error\", () => undefined);\n // `once` rejects if the command emits \"error\" (a failed connection) first.\n // The SDK ends both streams on exit; wait for them so no chunk is missed.\n const [exitArgs]: unknown[][] = await Promise.all([\n once(proc, \"exit\"),\n once(proc.stdout, \"end\"),\n once(proc.stderr, \"end\"),\n ]);\n const exitCode = exitArgs?.[0];\n stdout.flush();\n if (typeof exitCode !== \"number\" || exitCode < 0) {\n throw new Error(\n `sprites(): the connection closed before the command exited: ${command}`,\n );\n }\n return { stdout: stdout.toString(), stderr: stderr.toString(), exitCode };\n};\n","/**\n * Interrupt teardown for the Fly.io Sprites provider (`sprites.ts`). Sprites\n * persist until deleted, so a run interrupted before `close()` would leave\n * its Sprite running.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { registerShutdown } from \"../shutdownRegistry.js\";\n\n/** Deletes the Sprite at `process.argv[1]`, with the token from the env. */\nconst DELETE_SCRIPT =\n \"fetch(process.argv[1], { method: 'DELETE', headers: { Authorization: 'Bearer ' + process.env.SANDCASTLE_SPRITES_TOKEN } }).catch(() => {});\";\n\n/**\n * Register a teardown that deletes the Sprite `name` if the process is\n * interrupted (`SIGINT`/`SIGTERM`) or exits before it is unregistered.\n * Shutdown teardowns are synchronous and the process exits as soon as they\n * return, so the delete can't be awaited: it runs in a detached child process,\n * which outlives this one and finishes it.\n *\n * @returns An idempotent function that unregisters the teardown.\n */\nexport const registerSpriteDeletion = (\n baseURL: string,\n token: string,\n name: string,\n): (() => void) =>\n registerShutdown(() => {\n const url = `${baseURL}/v1/sprites/${encodeURIComponent(name)}`;\n spawn(process.execPath, [\"-e\", DELETE_SCRIPT, url], {\n detached: true,\n stdio: \"ignore\",\n windowsHide: true,\n env: { ...process.env, SANDCASTLE_SPRITES_TOKEN: token },\n }).unref();\n });\n","/**\n * Fly.io Sprites isolated sandbox provider — wraps `@fly/sprites` into a\n * SandboxProvider.\n *\n * Usage:\n * import { sprites } from \"@ai-hero/sandcastle/sandboxes/sprites\";\n * await run({ agent: claudeCode(\"claude-opus-4-8\"), sandbox: sprites() });\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { mkdir, readdir, readFile, stat, writeFile } from \"node:fs/promises\";\nimport { dirname, join, posix, relative } from \"node:path\";\nimport { Config, Effect } from \"effect\";\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 { execInSprite } from \"./spritesExec.js\";\nimport { registerSpriteDeletion } from \"./spritesShutdown.js\";\nimport type { Sprite } from \"@fly/sprites\";\n\n/** The Sprite user's home: the worktree's parent, which the user can write. */\nconst SPRITE_HOME = \"/home/sprite\";\n\n/** Worktree path inside the Sprite. */\nconst SPRITES_REPO_PATH = posix.join(SPRITE_HOME, \"workspace\");\n\n/** Options for the Fly.io Sprites sandbox provider. */\nexport interface SpritesOptions {\n /**\n * Sprites API token.\n *\n * Falls back to the `SPRITES_TOKEN` environment variable, then to\n * `SPRITE_TOKEN` (the name the Sprites CLI uses).\n */\n readonly token?: string;\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/** An option or env var counts as unset when it is missing or empty. */\nconst setOrUndefined = (value: string | undefined): string | undefined =>\n value === \"\" ? undefined : value;\n\n/** `SPRITES_TOKEN` then `SPRITE_TOKEN` from the environment, \"\" when unset. */\nconst envTokens = Effect.all([\n Config.string(\"SPRITES_TOKEN\").pipe(Config.withDefault(\"\")),\n Config.string(\"SPRITE_TOKEN\").pipe(Config.withDefault(\"\")),\n]);\n\n/** The token: the option, then `SPRITES_TOKEN`, then `SPRITE_TOKEN`. */\nconst resolveToken = async (\n options: SpritesOptions | undefined,\n): Promise<string> => {\n const [plural, singular] = await Effect.runPromise(envTokens);\n const token =\n setOrUndefined(options?.token) ??\n setOrUndefined(plural) ??\n setOrUndefined(singular);\n if (token === undefined) {\n throw new Error(\n \"sprites(): no Sprites token. Set SPRITES_TOKEN (or SPRITE_TOKEN), or pass the token option.\",\n );\n }\n return token;\n};\n\n/** Copy a host file, or every file under a host directory, into the Sprite. */\nconst copyIntoSprite = async (\n sprite: Sprite,\n hostPath: string,\n sandboxPath: string,\n): Promise<void> => {\n const fs = sprite.filesystem();\n const info = await stat(hostPath);\n if (!info.isDirectory()) {\n await fs.writeFile(sandboxPath, await readFile(hostPath));\n return;\n }\n const entries = await readdir(hostPath, {\n withFileTypes: true,\n recursive: true,\n });\n const files = entries\n .filter((entry) => entry.isFile())\n .map((entry) => join(entry.parentPath, entry.name));\n // `writeFile` creates the parent folders in the Sprite.\n await Promise.all(\n files.map(async (file) => {\n const parts = relative(hostPath, file).split(/[\\\\/]/u);\n await fs.writeFile(\n posix.join(sandboxPath, ...parts),\n await readFile(file),\n );\n }),\n );\n};\n\n/** What a handle needs beyond its Sprite. */\ninterface HandleContext {\n readonly env: Record<string, string>;\n readonly maxOutputTailChars: number;\n readonly unregisterShutdown: () => void;\n}\n\n/** The Sandcastle handle over a Sprite whose worktree folder exists. */\nconst makeHandle = (\n sprite: Sprite,\n { env, maxOutputTailChars, unregisterShutdown }: HandleContext,\n): IsolatedSandboxHandle => ({\n worktreePath: SPRITES_REPO_PATH,\n // A Sprite is addressed by its name in the Sprites API and CLI.\n sandboxId: sprite.name,\n\n exec: async (command, opts): Promise<ExecResult> =>\n execInSprite(sprite, {\n ...opts,\n command,\n cwd: opts?.cwd ?? SPRITES_REPO_PATH,\n env,\n maxOutputTailChars,\n }),\n\n copyIn: async (hostPath, sandboxPath): Promise<void> =>\n copyIntoSprite(sprite, hostPath, sandboxPath),\n\n copyFileOut: async (sandboxPath, hostPath): Promise<void> => {\n const buffer = await sprite.filesystem().readFile(sandboxPath, null);\n await mkdir(dirname(hostPath), { recursive: true });\n await writeFile(hostPath, buffer);\n },\n\n close: async (): Promise<void> => {\n await sprite.delete();\n // Only once the delete has gone through: if it threw, the exit teardown\n // tries again.\n unregisterShutdown();\n },\n});\n\n/** Create the worktree folder as the Sprite user, so sync-in can replace it. */\nconst makeWorktreeDir = async (sprite: Sprite): Promise<void> => {\n const result = await execInSprite(sprite, {\n command: `mkdir -p ${SPRITES_REPO_PATH}`,\n cwd: SPRITE_HOME,\n env: {},\n maxOutputTailChars: MAX_TAIL_CHARS,\n });\n if (result.exitCode !== 0) {\n throw new Error(\n `sprites(): could not create ${SPRITES_REPO_PATH}: ${result.stderr.trim()}`,\n );\n }\n};\n\n/**\n * Create a Fly.io Sprites isolated sandbox provider.\n *\n * Each `create()` makes a new Sprite, and `close()` deletes it. Sprites\n * persist until deleted, so Sandcastle also deletes the Sprite when setup\n * fails, and when the process is interrupted or exits without closing it.\n * The default Sprite image ships `git`, Node and the `claude` CLI; install\n * other agent CLIs in an `onSandboxReady` hook.\n *\n * Requires `@fly/sprites` to be installed as a peer dependency (it asks for\n * Node 24 or later).\n *\n * @example\n * ```ts\n * import { sprites } from \"@ai-hero/sandcastle/sandboxes/sprites\";\n *\n * const provider = sprites({ env: { MY_VAR: \"value\" } });\n * ```\n */\nexport const sprites = (options?: SpritesOptions): IsolatedSandboxProvider =>\n createIsolatedSandboxProvider({\n name: \"sprites\",\n env: options?.env,\n create: async ({ env }): Promise<IsolatedSandboxHandle> => {\n const token = await resolveToken(options);\n // Dynamic import so the peer dependency is only loaded at runtime\n const { SpritesClient } = await import(\"@fly/sprites\");\n const client = new SpritesClient(token);\n const name = `sandcastle-${randomUUID()}`;\n // Registered before the create request, so an interrupt while it is in\n // flight still deletes the Sprite (deleting a missing name is a no-op).\n const unregisterShutdown = registerSpriteDeletion(\n client.baseURL,\n token,\n name,\n );\n try {\n const sprite = await client.createSprite(name);\n await makeWorktreeDir(sprite);\n return makeHandle(sprite, {\n env,\n maxOutputTailChars: options?.maxOutputTailChars ?? MAX_TAIL_CHARS,\n unregisterShutdown,\n });\n } catch (error) {\n // No handle exists yet, so neither Sandcastle's teardown nor\n // `close()` can reach the Sprite, and it would persist.\n await client.deleteSprite(name).catch(() => undefined);\n unregisterShutdown();\n throw error;\n }\n },\n });\n"]}
@@ -1,4 +1,4 @@
1
- import { I as IsolatedSandboxProvider } from '../SandboxProvider-EkSMuBp8.js';
1
+ import { I as IsolatedSandboxProvider } from '../SandboxProvider-Chsi-Zs6.js';
2
2
 
3
3
  /**
4
4
  * Vercel isolated sandbox provider — wraps `@vercel/sandbox` into a SandboxProvider.
@@ -18,9 +18,10 @@ interface VercelOptions {
18
18
  /**
19
19
  * Vercel access token.
20
20
  *
21
- * Falls back to the SDK's default auth behavior, which reads
22
- * `VERCEL_OIDC_TOKEN` (recommended for Vercel-hosted environments) or
23
- * `VERCEL_TOKEN` from the environment.
21
+ * Falls back to the `VERCEL_TOKEN` environment variable. A token needs a
22
+ * team and project id too (`teamId`/`VERCEL_TEAM_ID`,
23
+ * `projectId`/`VERCEL_PROJECT_ID`). With no token at all, the SDK's OIDC
24
+ * auth applies, which reads `VERCEL_OIDC_TOKEN`.
24
25
  */
25
26
  readonly token?: string;
26
27
  /**
@@ -54,7 +55,11 @@ interface VercelOptions {
54
55
  };
55
56
  /**
56
57
  * The runtime of the sandbox (e.g. `"node24"`, `"node22"`, `"python3.13"`).
57
- * Defaults to `"node24"`.
58
+ *
59
+ * Omit it to get Vercel's default image (`vercel/sandbox/universal` as of
60
+ * `@vercel/sandbox` 3.x), which ships coding agent CLIs such as `claude`.
61
+ * The named runtimes ship none: install your agent's CLI in an
62
+ * `onSandboxReady` hook.
58
63
  */
59
64
  readonly runtime?: string;
60
65
  /**
@@ -64,10 +69,12 @@ interface VercelOptions {
64
69
  readonly networkPolicy?: Record<string, unknown>;
65
70
  /**
66
71
  * Vercel project ID to associate sandbox operations with.
72
+ * Falls back to the `VERCEL_PROJECT_ID` environment variable when a token is used.
67
73
  */
68
74
  readonly projectId?: string;
69
75
  /**
70
76
  * Vercel team ID to associate sandbox operations with.
77
+ * Falls back to the `VERCEL_TEAM_ID` environment variable when a token is used.
71
78
  */
72
79
  readonly teamId?: string;
73
80
  /**
@@ -1,7 +1,8 @@
1
1
  import { createRequire } from 'node:module';
2
- import { createIsolatedSandboxProvider } from '../chunk-BIWNFKGV.js';
3
- import { MAX_TAIL_CHARS, BoundedTail } from '../chunk-NGBM7T3E.js';
2
+ import { createIsolatedSandboxProvider } from '../chunk-BVZWLFFT.js';
3
+ import { MAX_TAIL_CHARS, BoundedTail } from '../chunk-6NQPCXSG.js';
4
4
  import { execSync } from 'child_process';
5
+ import { randomUUID } from 'crypto';
5
6
  import { mkdir, writeFile, stat, readFile, unlink } from 'fs/promises';
6
7
  import { tmpdir } from 'os';
7
8
  import { dirname, join } from 'path';
@@ -9,137 +10,205 @@ import { Writable } from 'stream';
9
10
 
10
11
  createRequire(import.meta.url);
11
12
  var VERCEL_REPO_PATH = "/vercel/sandbox/workspace";
13
+ var setOrUndefined = (value) => value === "" ? void 0 : value;
14
+ var resolveVercelAuth = (options) => {
15
+ const { env } = process;
16
+ const tokenOption = setOrUndefined(options?.token);
17
+ const teamIdOption = setOrUndefined(options?.teamId);
18
+ const projectIdOption = setOrUndefined(options?.projectId);
19
+ const token = tokenOption ?? setOrUndefined(env.VERCEL_TOKEN);
20
+ if (token === void 0) {
21
+ return {
22
+ ...teamIdOption === void 0 ? {} : { teamId: teamIdOption },
23
+ ...projectIdOption === void 0 ? {} : { projectId: projectIdOption }
24
+ };
25
+ }
26
+ const teamId = teamIdOption ?? setOrUndefined(env.VERCEL_TEAM_ID);
27
+ const projectId = projectIdOption ?? setOrUndefined(env.VERCEL_PROJECT_ID);
28
+ const missing = [
29
+ teamId === void 0 ? "VERCEL_TEAM_ID (or the teamId option)" : null,
30
+ projectId === void 0 ? "VERCEL_PROJECT_ID (or the projectId option)" : null
31
+ ].filter((name) => name !== null);
32
+ if (missing.length > 0) {
33
+ const source = tokenOption === void 0 ? "VERCEL_TOKEN" : "the token option";
34
+ throw new Error(
35
+ `vercel(): ${source} is set, but a Vercel token also needs a team and project id. Missing: ${missing.join(", ")}.`
36
+ );
37
+ }
38
+ return { token, teamId, projectId };
39
+ };
40
+ var setUpOrStop = async (sandbox, setUp) => {
41
+ try {
42
+ await setUp();
43
+ } catch (error) {
44
+ try {
45
+ await sandbox.stop();
46
+ } catch {
47
+ }
48
+ throw error;
49
+ }
50
+ };
51
+ var toCreateParams = (options, env) => {
52
+ const o = options ?? {};
53
+ const passThrough = {
54
+ source: o.source,
55
+ ports: o.ports,
56
+ resources: o.resources,
57
+ networkPolicy: o.networkPolicy,
58
+ // runtime takes precedence over the template convenience alias
59
+ runtime: o.runtime ?? o.template,
60
+ // prefer explicit timeout, fall back to the timeoutMs alias
61
+ timeout: o.timeout ?? o.timeoutMs
62
+ };
63
+ return {
64
+ // An unset option (or an empty runtime) is left out for the SDK default.
65
+ ...Object.fromEntries(
66
+ Object.entries(passThrough).filter(
67
+ ([, value]) => value !== void 0 && value !== ""
68
+ )
69
+ ),
70
+ env,
71
+ ...resolveVercelAuth(options)
72
+ };
73
+ };
74
+ var withStdin = async (sandbox, command, stdin) => {
75
+ if (stdin === void 0) {
76
+ return command;
77
+ }
78
+ const stdinPath = `/tmp/sandcastle-stdin-${randomUUID()}`;
79
+ await sandbox.writeFiles([{ path: stdinPath, content: Buffer.from(stdin) }]);
80
+ return `{ rm -f ${stdinPath}; ${command}
81
+ } < ${stdinPath}`;
82
+ };
83
+ var lineWritable = (onLine, tail) => {
84
+ let partial = "";
85
+ return new Writable({
86
+ write(chunk, _encoding, callback) {
87
+ const text = partial + chunk.toString();
88
+ const lines = text.split("\n");
89
+ partial = lines.pop() ?? "";
90
+ for (const line of lines) {
91
+ tail.push(line);
92
+ onLine(line);
93
+ }
94
+ callback();
95
+ },
96
+ final(callback) {
97
+ if (partial) {
98
+ tail.push(partial);
99
+ onLine(partial);
100
+ partial = "";
101
+ }
102
+ callback();
103
+ }
104
+ });
105
+ };
106
+ var tailWritable = (tail) => new Writable({
107
+ write(chunk, _encoding, callback) {
108
+ tail.push(chunk.toString());
109
+ callback();
110
+ }
111
+ });
112
+ var execStreamed = async (sandbox, params, {
113
+ onLine,
114
+ maxOutputTailChars
115
+ }) => {
116
+ const stdoutTail = new BoundedTail(maxOutputTailChars, "\n");
117
+ const stderrTail = new BoundedTail(maxOutputTailChars, "");
118
+ const result = await sandbox.runCommand({
119
+ ...params,
120
+ stdout: lineWritable(onLine, stdoutTail),
121
+ stderr: tailWritable(stderrTail)
122
+ });
123
+ return {
124
+ stdout: stdoutTail.toString(),
125
+ stderr: stderrTail.toString(),
126
+ exitCode: result.exitCode
127
+ };
128
+ };
129
+ var execBuffered = async (sandbox, params) => {
130
+ const result = await sandbox.runCommand(params);
131
+ const stdout = await result.stdout();
132
+ const stderr = await result.stderr();
133
+ return { stdout, stderr, exitCode: result.exitCode };
134
+ };
135
+ var copyDirIn = async (sandbox, hostPath, sandboxPath) => {
136
+ const tarPath = join(tmpdir(), `sandcastle-copyin-${Date.now()}.tar.gz`);
137
+ execSync(`tar -czf "${tarPath}" -C "${hostPath}" .`);
138
+ try {
139
+ const tarContent = await readFile(tarPath);
140
+ const sandboxTarPath = `/tmp/sandcastle-copyin-${Date.now()}.tar.gz`;
141
+ await sandbox.writeFiles([{ path: sandboxTarPath, content: tarContent }]);
142
+ await sandbox.runCommand({
143
+ cmd: "sh",
144
+ args: [
145
+ "-c",
146
+ `mkdir -p "${sandboxPath}" && tar -xzf "${sandboxTarPath}" -C "${sandboxPath}" && rm -f "${sandboxTarPath}"`
147
+ ]
148
+ });
149
+ } finally {
150
+ await unlink(tarPath).catch(() => void 0);
151
+ }
152
+ };
153
+ var makeWorktreeDir = async (sandbox) => {
154
+ const mkdirResult = await sandbox.runCommand({
155
+ cmd: "mkdir",
156
+ args: ["-p", VERCEL_REPO_PATH]
157
+ });
158
+ if (mkdirResult.exitCode !== 0) {
159
+ const stderr = await mkdirResult.stderr();
160
+ throw new Error(
161
+ `vercel(): could not create ${VERCEL_REPO_PATH}: ${stderr.trim()}`
162
+ );
163
+ }
164
+ };
165
+ var makeHandle = (sandbox, maxOutputTailChars) => ({
166
+ worktreePath: VERCEL_REPO_PATH,
167
+ // `@vercel/sandbox` 2 renamed the sandbox's id from `sandboxId` to `name`.
168
+ sandboxId: sandbox.name ?? sandbox.sandboxId,
169
+ exec: async (command, opts) => {
170
+ const params = {
171
+ cmd: "sh",
172
+ args: ["-c", await withStdin(sandbox, command, opts?.stdin)],
173
+ cwd: opts?.cwd ?? VERCEL_REPO_PATH,
174
+ ...opts?.sudo === true ? { sudo: true } : {}
175
+ };
176
+ return opts?.onLine ? execStreamed(sandbox, params, {
177
+ onLine: opts.onLine,
178
+ maxOutputTailChars
179
+ }) : execBuffered(sandbox, params);
180
+ },
181
+ copyIn: async (hostPath, sandboxPath) => {
182
+ const info = await stat(hostPath);
183
+ if (info.isDirectory()) {
184
+ await copyDirIn(sandbox, hostPath, sandboxPath);
185
+ } else {
186
+ const content = await readFile(hostPath);
187
+ await sandbox.writeFiles([{ path: sandboxPath, content }]);
188
+ }
189
+ },
190
+ copyFileOut: async (sandboxPath, hostPath) => {
191
+ const buffer = await sandbox.readFileToBuffer({ path: sandboxPath });
192
+ if (!buffer) {
193
+ throw new Error(`File not found in Vercel sandbox: ${sandboxPath}`);
194
+ }
195
+ await mkdir(dirname(hostPath), { recursive: true });
196
+ await writeFile(hostPath, buffer);
197
+ },
198
+ close: async () => {
199
+ await sandbox.stop();
200
+ }
201
+ });
12
202
  var vercel = (options) => createIsolatedSandboxProvider({
13
203
  name: "vercel",
14
204
  env: options?.env,
15
205
  create: async (createOptions) => {
16
- const maxOutputTailChars = options?.maxOutputTailChars ?? MAX_TAIL_CHARS;
17
206
  const { Sandbox } = await import('@vercel/sandbox');
18
- const createParams = {};
19
- if (options?.source) createParams.source = options.source;
20
- if (options?.ports) createParams.ports = options.ports;
21
- if (options?.resources) createParams.resources = options.resources;
22
- if (options?.networkPolicy)
23
- createParams.networkPolicy = options.networkPolicy;
24
- const resolvedRuntime = options?.runtime ?? options?.template;
25
- if (resolvedRuntime) createParams.runtime = resolvedRuntime;
26
- const timeoutValue = options?.timeout ?? options?.timeoutMs;
27
- if (timeoutValue !== void 0) createParams.timeout = timeoutValue;
28
- createParams.env = createOptions.env;
29
- if (options?.token) createParams.token = options.token;
30
- if (options?.projectId) createParams.projectId = options.projectId;
31
- if (options?.teamId) createParams.teamId = options.teamId;
32
207
  const sandbox = await Sandbox.create(
33
- createParams
208
+ toCreateParams(options, createOptions.env)
34
209
  );
35
- await sandbox.mkDir(VERCEL_REPO_PATH);
36
- const handle = {
37
- worktreePath: VERCEL_REPO_PATH,
38
- exec: async (command, opts) => {
39
- if (opts?.onLine) {
40
- const onLine = opts.onLine;
41
- const stdoutTail = new BoundedTail(maxOutputTailChars, "\n");
42
- const stderrTail = new BoundedTail(maxOutputTailChars, "");
43
- let partial = "";
44
- const stdoutWritable = new Writable({
45
- write(chunk, _encoding, callback) {
46
- const text = partial + chunk.toString();
47
- const lines = text.split("\n");
48
- partial = lines.pop() ?? "";
49
- for (const line of lines) {
50
- stdoutTail.push(line);
51
- onLine(line);
52
- }
53
- callback();
54
- },
55
- final(callback) {
56
- if (partial) {
57
- stdoutTail.push(partial);
58
- onLine(partial);
59
- partial = "";
60
- }
61
- callback();
62
- }
63
- });
64
- const stderrWritable = new Writable({
65
- write(chunk, _encoding, callback) {
66
- stderrTail.push(chunk.toString());
67
- callback();
68
- }
69
- });
70
- const result2 = await sandbox.runCommand({
71
- cmd: "sh",
72
- args: ["-c", command],
73
- cwd: opts?.cwd ?? VERCEL_REPO_PATH,
74
- stdout: stdoutWritable,
75
- stderr: stderrWritable,
76
- ...opts?.sudo ? { sudo: true } : {}
77
- });
78
- return {
79
- stdout: stdoutTail.toString(),
80
- stderr: stderrTail.toString(),
81
- exitCode: result2.exitCode
82
- };
83
- }
84
- const result = await sandbox.runCommand({
85
- cmd: "sh",
86
- args: ["-c", command],
87
- cwd: opts?.cwd ?? VERCEL_REPO_PATH,
88
- ...opts?.sudo ? { sudo: true } : {}
89
- });
90
- const stdout = await result.stdout();
91
- const stderr = await result.stderr();
92
- return {
93
- stdout,
94
- stderr,
95
- exitCode: result.exitCode
96
- };
97
- },
98
- copyIn: async (hostPath, sandboxPath) => {
99
- const info = await stat(hostPath);
100
- if (info.isDirectory()) {
101
- const tarPath = join(
102
- tmpdir(),
103
- `sandcastle-copyin-${Date.now()}.tar.gz`
104
- );
105
- execSync(`tar -czf "${tarPath}" -C "${hostPath}" .`);
106
- try {
107
- const tarContent = await readFile(tarPath);
108
- const sandboxTarPath = `/tmp/sandcastle-copyin-${Date.now()}.tar.gz`;
109
- await sandbox.writeFiles([
110
- { path: sandboxTarPath, content: tarContent }
111
- ]);
112
- await sandbox.runCommand({
113
- cmd: "sh",
114
- args: [
115
- "-c",
116
- `mkdir -p "${sandboxPath}" && tar -xzf "${sandboxTarPath}" -C "${sandboxPath}" && rm -f "${sandboxTarPath}"`
117
- ]
118
- });
119
- } finally {
120
- await unlink(tarPath).catch(() => {
121
- });
122
- }
123
- } else {
124
- const content = await readFile(hostPath);
125
- await sandbox.writeFiles([{ path: sandboxPath, content }]);
126
- }
127
- },
128
- copyFileOut: async (sandboxPath, hostPath) => {
129
- const buffer = await sandbox.readFileToBuffer({
130
- path: sandboxPath
131
- });
132
- if (!buffer) {
133
- throw new Error(`File not found in Vercel sandbox: ${sandboxPath}`);
134
- }
135
- await mkdir(dirname(hostPath), { recursive: true });
136
- await writeFile(hostPath, buffer);
137
- },
138
- close: async () => {
139
- await sandbox.stop();
140
- }
141
- };
142
- return handle;
210
+ await setUpOrStop(sandbox, async () => makeWorktreeDir(sandbox));
211
+ return makeHandle(sandbox, options?.maxOutputTailChars ?? MAX_TAIL_CHARS);
143
212
  }
144
213
  });
145
214