@ai-hero/sandcastle 0.14.0 → 0.14.1

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 (74) hide show
  1. package/dist/{SandboxProvider-Chsi-Zs6.d.ts → SandboxProvider-CwRLxIXZ.d.ts} +2 -39
  2. package/dist/{chunk-BVZWLFFT.js → chunk-4BB7DNPW.js} +3 -3
  3. package/dist/chunk-4BB7DNPW.js.map +1 -0
  4. package/dist/chunk-4GZMUHVO.js +60 -0
  5. package/dist/chunk-4GZMUHVO.js.map +1 -0
  6. package/dist/{chunk-S6UHPTRG.js → chunk-7JUTKCHL.js} +4 -4
  7. package/dist/{chunk-S6UHPTRG.js.map → chunk-7JUTKCHL.js.map} +1 -1
  8. package/dist/chunk-7PHPLDVS.js +284 -0
  9. package/dist/chunk-7PHPLDVS.js.map +1 -0
  10. package/dist/{chunk-HSXPRZKG.js → chunk-BXLS4HRY.js} +15 -6
  11. package/dist/chunk-BXLS4HRY.js.map +1 -0
  12. package/dist/{chunk-G2R53CVZ.js → chunk-EM4QNWKF.js} +695 -706
  13. package/dist/chunk-EM4QNWKF.js.map +1 -0
  14. package/dist/{chunk-STB2U7BB.js → chunk-JEQ4IVQM.js} +384 -264
  15. package/dist/chunk-JEQ4IVQM.js.map +1 -0
  16. package/dist/{chunk-VRXR2T3S.js → chunk-L3BU47F6.js} +3 -3
  17. package/dist/{chunk-VRXR2T3S.js.map → chunk-L3BU47F6.js.map} +1 -1
  18. package/dist/{chunk-7N7AMUYA.js → chunk-PTJEKJPQ.js} +7 -5
  19. package/dist/chunk-PTJEKJPQ.js.map +1 -0
  20. package/dist/{chunk-H2PEFS4W.js → chunk-SAQXFLO2.js} +30 -6
  21. package/dist/chunk-SAQXFLO2.js.map +1 -0
  22. package/dist/{chunk-ATA2V2TC.js → chunk-TBVRAXYF.js} +3 -3
  23. package/dist/{chunk-ATA2V2TC.js.map → chunk-TBVRAXYF.js.map} +1 -1
  24. package/dist/{chunk-IBK2XNSS.js → chunk-VUOXFCWO.js} +3 -3
  25. package/dist/{chunk-IBK2XNSS.js.map → chunk-VUOXFCWO.js.map} +1 -1
  26. package/dist/{chunk-GCLEXPXG.js → chunk-WYOGXC72.js} +46 -84
  27. package/dist/chunk-WYOGXC72.js.map +1 -0
  28. package/dist/{chunk-RDW7FNN6.js → chunk-YDQW5IOY.js} +11 -4
  29. package/dist/chunk-YDQW5IOY.js.map +1 -0
  30. package/dist/index.d.ts +47 -4
  31. package/dist/index.js +536 -445
  32. package/dist/index.js.map +1 -1
  33. package/dist/main.js +72 -16
  34. package/dist/main.js.map +1 -1
  35. package/dist/sandboxes/bwrap.d.ts +1 -1
  36. package/dist/sandboxes/bwrap.js +9 -17
  37. package/dist/sandboxes/bwrap.js.map +1 -1
  38. package/dist/sandboxes/daytona.d.ts +1 -1
  39. package/dist/sandboxes/daytona.js +82 -79
  40. package/dist/sandboxes/daytona.js.map +1 -1
  41. package/dist/sandboxes/docker.d.ts +23 -1
  42. package/dist/sandboxes/docker.js +6 -5
  43. package/dist/sandboxes/e2b.d.ts +1 -1
  44. package/dist/sandboxes/e2b.js +4 -4
  45. package/dist/sandboxes/modal.d.ts +1 -1
  46. package/dist/sandboxes/modal.js +1 -1
  47. package/dist/sandboxes/no-sandbox.d.ts +1 -1
  48. package/dist/sandboxes/no-sandbox.js +1 -1
  49. package/dist/sandboxes/podman.d.ts +27 -4
  50. package/dist/sandboxes/podman.js +18 -45
  51. package/dist/sandboxes/podman.js.map +1 -1
  52. package/dist/sandboxes/seatbelt.d.ts +2 -2
  53. package/dist/sandboxes/seatbelt.js +10 -10
  54. package/dist/sandboxes/seatbelt.js.map +1 -1
  55. package/dist/sandboxes/sprites.d.ts +1 -1
  56. package/dist/sandboxes/sprites.js +25 -4
  57. package/dist/sandboxes/sprites.js.map +1 -1
  58. package/dist/sandboxes/vercel.d.ts +10 -1
  59. package/dist/sandboxes/vercel.js +74 -46
  60. package/dist/sandboxes/vercel.js.map +1 -1
  61. package/dist/templates/parallel-planner/main.mts +43 -21
  62. package/dist/templates/parallel-planner-with-review/main.mts +55 -27
  63. package/dist/templates/sequential-reviewer/main.mts +1 -1
  64. package/package.json +7 -3
  65. package/dist/chunk-7N7AMUYA.js.map +0 -1
  66. package/dist/chunk-BIF2X6QB.js +0 -94
  67. package/dist/chunk-BIF2X6QB.js.map +0 -1
  68. package/dist/chunk-BVZWLFFT.js.map +0 -1
  69. package/dist/chunk-G2R53CVZ.js.map +0 -1
  70. package/dist/chunk-GCLEXPXG.js.map +0 -1
  71. package/dist/chunk-H2PEFS4W.js.map +0 -1
  72. package/dist/chunk-HSXPRZKG.js.map +0 -1
  73. package/dist/chunk-RDW7FNN6.js.map +0 -1
  74. package/dist/chunk-STB2U7BB.js.map +0 -1
@@ -1,7 +1,7 @@
1
1
  import { createRequire } from 'node:module';
2
2
  import { registerShutdown } from '../chunk-EXYXBRCX.js';
3
- import { Effect_exports, Config_exports } from '../chunk-STB2U7BB.js';
4
- import { createIsolatedSandboxProvider } from '../chunk-BVZWLFFT.js';
3
+ import { Effect_exports, Config_exports } from '../chunk-JEQ4IVQM.js';
4
+ import { createIsolatedSandboxProvider } from '../chunk-4BB7DNPW.js';
5
5
  import { MAX_TAIL_CHARS, BoundedTail } from '../chunk-6NQPCXSG.js';
6
6
  import { randomUUID } from 'crypto';
7
7
  import { mkdir, writeFile, stat, readFile, readdir } from 'fs/promises';
@@ -44,6 +44,20 @@ var outputSink = (separator, maxChars, onLine) => {
44
44
  toString: () => maxChars === void 0 ? chunks.join("") : tail.toString()
45
45
  };
46
46
  };
47
+ var stripUrlQueries = (text) => text.replaceAll(
48
+ /(?<url>(?:wss?|https?):\/\/[^\s?#)]*)[?#][^\s)]*/giu,
49
+ "$<url>"
50
+ );
51
+ var connectionError = (command, error) => {
52
+ const sdkError = error instanceof Error ? error : new Error(String(error));
53
+ const cause = new Error(stripUrlQueries(sdkError.message));
54
+ cause.name = sdkError.name;
55
+ cause.stack = sdkError.stack === void 0 ? void 0 : stripUrlQueries(sdkError.stack);
56
+ return new Error(
57
+ `sprites(): the connection failed: ${command} (${cause.message})`,
58
+ { cause }
59
+ );
60
+ };
47
61
  var execInSprite = async (sprite, request) => {
48
62
  const { command, onLine, maxOutputTailChars } = request;
49
63
  const line = request.sudo === true ? `sudo sh -c ${shellEscape(command)}` : command;
@@ -68,7 +82,9 @@ var execInSprite = async (sprite, request) => {
68
82
  once(proc, "exit"),
69
83
  once(proc.stdout, "end"),
70
84
  once(proc.stderr, "end")
71
- ]);
85
+ ]).catch((error) => {
86
+ throw connectionError(command, error);
87
+ });
72
88
  const exitCode = exitArgs?.[0];
73
89
  stdout.flush();
74
90
  if (typeof exitCode !== "number" || exitCode < 0) {
@@ -129,6 +145,7 @@ var copyIntoSprite = async (sprite, hostPath, sandboxPath) => {
129
145
  })
130
146
  );
131
147
  };
148
+ var isSpriteNotFound = (error) => error instanceof Error && "statusCode" in error && error.statusCode === 404;
132
149
  var makeHandle = (sprite, { env, maxOutputTailChars, unregisterShutdown }) => ({
133
150
  worktreePath: SPRITES_REPO_PATH,
134
151
  // A Sprite is addressed by its name in the Sprites API and CLI.
@@ -147,7 +164,11 @@ var makeHandle = (sprite, { env, maxOutputTailChars, unregisterShutdown }) => ({
147
164
  await writeFile(hostPath, buffer);
148
165
  },
149
166
  close: async () => {
150
- await sprite.delete();
167
+ await sprite.delete().catch((error) => {
168
+ if (!isSpriteNotFound(error)) {
169
+ throw error;
170
+ }
171
+ });
151
172
  unregisterShutdown();
152
173
  }
153
174
  });
@@ -1 +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,MAAA,CAAO,GAAA,CAAA,IAAA,CAAS,CAAC,CAAA,CAAA,CAAA;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,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
+ {"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,MAAA,CAAO,GAAA,CAAA,IAAA,CAAS,CAAC,CAAA,CAAA,CAAA;AAOzC,IAAM,UAAA,GAAa,CACjB,SAAA,EACA,QAAA,EACA,MAAA,KACG;AACH,EAAA,MAAM,SAAmB,EAAC;AAC1B,EAAA,MAAM,IAAA,GAAO,IAAI,WAAA,CAAY,QAAA,EAAU,SAAS,CAAA;AAChD,EAAA,IAAI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AAA,GAAU,CAAC,OAAA,KACtB,6BAAA,CAA8B;AAAA,EAC5B,IAAA,EAAM,SAAA;AAAA,EACN,KAAK,OAAA,EAAS,GAAA;AAAA,EACd,MAAA,EAAQ,OAAO,EAAE,GAAA,EAAI,KAAsC;AACzD,IAAA,MAAM,KAAA,GAAQ,MAAM,YAAA,CAAa,OAAO,CAAA;AAExC,IAAA,MAAM,EAAE,aAAA,EAAc,GAAI,MAAM,OAAO,cAAc,CAAA;AACrD,IAAA,MAAM,MAAA,GAAS,IAAI,aAAA,CAAc,KAAK,CAAA;AACtC,IAAA,MAAM,IAAA,GAAO,CAAA,WAAA,EAAc,UAAA,EAAY,CAAA,CAAA;AAGvC,IAAA,MAAM,kBAAA,GAAqB,sBAAA;AAAA,MACzB,MAAA,CAAO,OAAA;AAAA,MACP,KAAA;AAAA,MACA;AAAA,KACF;AACA,IAAA,IAAI;AACF,MAAA,MAAM,MAAA,GAAS,MAAM,MAAA,CAAO,YAAA,CAAa,IAAI,CAAA;AAC7C,MAAA,MAAM,gBAAgB,MAAM,CAAA;AAC5B,MAAA,OAAO,WAAW,MAAA,EAAQ;AAAA,QACxB,GAAA;AAAA,QACA,kBAAA,EAAoB,SAAS,kBAAA,IAAsB,cAAA;AAAA,QACnD;AAAA,OACD,CAAA;AAAA,IACH,SAAS,KAAA,EAAO;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/** Drop the query string from every URL in `text`. */\nconst stripUrlQueries = (text: string): string =>\n text.replaceAll(\n /(?<url>(?:wss?|https?):\\/\\/[^\\s?#)]*)[?#][^\\s)]*/giu,\n \"$<url>\",\n );\n\n/**\n * The error for a failed exec connection. The SDK's error names the exec URL,\n * whose query string carries the command's env, so the error and its `cause`\n * keep only the URL's path.\n */\nconst connectionError = (command: string, error: unknown): Error => {\n const sdkError = error instanceof Error ? error : new Error(String(error));\n const cause = new Error(stripUrlQueries(sdkError.message));\n cause.name = sdkError.name;\n cause.stack =\n sdkError.stack === undefined ? undefined : stripUrlQueries(sdkError.stack);\n return new Error(\n `sprites(): the connection failed: ${command} (${cause.message})`,\n { cause },\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 ]).catch((error: unknown) => {\n throw connectionError(command, error);\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/**\n * Whether `error` is the Sprites API's answer to deleting a Sprite that\n * doesn't exist: the SDK's `APIError` with status 404 (body\n * `{\"error\":\"sprite not found\"}`).\n */\nconst isSpriteNotFound = (error: unknown): boolean =>\n error instanceof Error && \"statusCode\" in error && error.statusCode === 404;\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().catch((error: unknown) => {\n // Already gone (deleted out-of-band, expired or reaped): closed.\n if (!isSpriteNotFound(error)) {\n throw error;\n }\n });\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-Chsi-Zs6.js';
1
+ import { I as IsolatedSandboxProvider } from '../SandboxProvider-CwRLxIXZ.js';
2
2
 
3
3
  /**
4
4
  * Vercel isolated sandbox provider — wraps `@vercel/sandbox` into a SandboxProvider.
@@ -86,6 +86,15 @@ interface VercelOptions {
86
86
  * Maps to the `runtime` option.
87
87
  */
88
88
  readonly template?: string;
89
+ /**
90
+ * Whether Vercel keeps the sandbox's filesystem when it stops (default:
91
+ * `false`).
92
+ *
93
+ * Vercel snapshots a persistent sandbox each time it stops, and the snapshot
94
+ * counts against your snapshot storage. Sandcastle makes one sandbox per
95
+ * run, so it turns this off unless you set it.
96
+ */
97
+ readonly persistent?: boolean;
89
98
  /** Environment variables injected by this provider. Merged at launch time with env resolver and agent provider env. */
90
99
  readonly env?: Record<string, string>;
91
100
  /**
@@ -1,15 +1,17 @@
1
1
  import { createRequire } from 'node:module';
2
- import { createIsolatedSandboxProvider } from '../chunk-BVZWLFFT.js';
2
+ import { createIsolatedSandboxProvider } from '../chunk-4BB7DNPW.js';
3
3
  import { MAX_TAIL_CHARS, BoundedTail } from '../chunk-6NQPCXSG.js';
4
- import { execSync } from 'child_process';
5
- import { randomUUID } from 'crypto';
4
+ import { spawn } from 'child_process';
5
+ import { once } from 'events';
6
6
  import { mkdir, writeFile, stat, readFile, unlink } from 'fs/promises';
7
7
  import { tmpdir } from 'os';
8
8
  import { dirname, join } from 'path';
9
+ import { randomUUID } from 'crypto';
9
10
  import { Writable } from 'stream';
10
11
 
11
12
  createRequire(import.meta.url);
12
- var VERCEL_REPO_PATH = "/vercel/sandbox/workspace";
13
+
14
+ // src/sandboxes/vercelAuth.ts
13
15
  var setOrUndefined = (value) => value === "" ? void 0 : value;
14
16
  var resolveVercelAuth = (options) => {
15
17
  const { env } = process;
@@ -37,40 +39,6 @@ var resolveVercelAuth = (options) => {
37
39
  }
38
40
  return { token, teamId, projectId };
39
41
  };
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
42
  var withStdin = async (sandbox, command, stdin) => {
75
43
  if (stdin === void 0) {
76
44
  return command;
@@ -82,7 +50,14 @@ var withStdin = async (sandbox, command, stdin) => {
82
50
  };
83
51
  var lineWritable = (onLine, tail) => {
84
52
  let partial = "";
85
- return new Writable({
53
+ const flush = () => {
54
+ if (partial) {
55
+ tail.push(partial);
56
+ onLine(partial);
57
+ partial = "";
58
+ }
59
+ };
60
+ const stream = new Writable({
86
61
  write(chunk, _encoding, callback) {
87
62
  const text = partial + chunk.toString();
88
63
  const lines = text.split("\n");
@@ -94,14 +69,11 @@ var lineWritable = (onLine, tail) => {
94
69
  callback();
95
70
  },
96
71
  final(callback) {
97
- if (partial) {
98
- tail.push(partial);
99
- onLine(partial);
100
- partial = "";
101
- }
72
+ flush();
102
73
  callback();
103
74
  }
104
75
  });
76
+ return { stream, flush };
105
77
  };
106
78
  var tailWritable = (tail) => new Writable({
107
79
  write(chunk, _encoding, callback) {
@@ -115,11 +87,13 @@ var execStreamed = async (sandbox, params, {
115
87
  }) => {
116
88
  const stdoutTail = new BoundedTail(maxOutputTailChars, "\n");
117
89
  const stderrTail = new BoundedTail(maxOutputTailChars, "");
90
+ const stdout = lineWritable(onLine, stdoutTail);
118
91
  const result = await sandbox.runCommand({
119
92
  ...params,
120
- stdout: lineWritable(onLine, stdoutTail),
93
+ stdout: stdout.stream,
121
94
  stderr: tailWritable(stderrTail)
122
95
  });
96
+ stdout.flush();
123
97
  return {
124
98
  stdout: stdoutTail.toString(),
125
99
  stderr: stderrTail.toString(),
@@ -132,9 +106,63 @@ var execBuffered = async (sandbox, params) => {
132
106
  const stderr = await result.stderr();
133
107
  return { stdout, stderr, exitCode: result.exitCode };
134
108
  };
109
+
110
+ // src/sandboxes/vercel.ts
111
+ var VERCEL_REPO_PATH = "/vercel/sandbox/workspace";
112
+ var setUpOrStop = async (sandbox, setUp) => {
113
+ try {
114
+ await setUp();
115
+ } catch (error) {
116
+ try {
117
+ await sandbox.stop();
118
+ } catch {
119
+ }
120
+ throw error;
121
+ }
122
+ };
123
+ var toCreateParams = (options, env) => {
124
+ const o = options ?? {};
125
+ const passThrough = {
126
+ source: o.source,
127
+ ports: o.ports,
128
+ resources: o.resources,
129
+ networkPolicy: o.networkPolicy,
130
+ // runtime takes precedence over the template convenience alias
131
+ runtime: o.runtime ?? o.template,
132
+ // prefer explicit timeout, fall back to the timeoutMs alias
133
+ timeout: o.timeout ?? o.timeoutMs,
134
+ // Vercel defaults to persistent, which snapshots the sandbox on stop().
135
+ persistent: o.persistent ?? false
136
+ };
137
+ return {
138
+ // An unset option (or an empty runtime) is left out for the SDK default.
139
+ ...Object.fromEntries(
140
+ Object.entries(passThrough).filter(
141
+ ([, value]) => value !== void 0 && value !== ""
142
+ )
143
+ ),
144
+ env,
145
+ ...resolveVercelAuth(options)
146
+ };
147
+ };
148
+ var tarDirectory = async (archive, dir) => {
149
+ const tar = spawn("tar", ["-czf", archive, "-C", dir, "."], {
150
+ stdio: ["ignore", "ignore", "pipe"]
151
+ });
152
+ let stderr = "";
153
+ tar.stderr.on("data", (chunk) => {
154
+ stderr += chunk.toString();
155
+ });
156
+ await once(tar, "close");
157
+ if (tar.exitCode !== 0) {
158
+ throw new Error(
159
+ `tar exited with ${String(tar.exitCode)}: ${stderr.trim()}`
160
+ );
161
+ }
162
+ };
135
163
  var copyDirIn = async (sandbox, hostPath, sandboxPath) => {
136
164
  const tarPath = join(tmpdir(), `sandcastle-copyin-${Date.now()}.tar.gz`);
137
- execSync(`tar -czf "${tarPath}" -C "${hostPath}" .`);
165
+ await tarDirectory(tarPath, hostPath);
138
166
  try {
139
167
  const tarContent = await readFile(tarPath);
140
168
  const sandboxTarPath = `/tmp/sandcastle-copyin-${Date.now()}.tar.gz`;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/sandboxes/vercel.ts"],"names":[],"mappings":";;;;;;;;;;;AAwBA,IAAM,gBAAA,GAAmB,2BAAA;AA+GzB,IAAM,cAAA,GAAiB,CAAC,KAAA,KACtB,KAAA,KAAU,KAAK,MAAA,GAAY,KAAA;AAU7B,IAAM,iBAAA,GAAoB,CACxB,OAAA,KAC4D;AAC5D,EAAA,MAAM,EAAE,KAAI,GAAI,OAAA;AAChB,EAAA,MAAM,WAAA,GAAc,cAAA,CAAe,OAAA,EAAS,KAAK,CAAA;AACjD,EAAA,MAAM,YAAA,GAAe,cAAA,CAAe,OAAA,EAAS,MAAM,CAAA;AACnD,EAAA,MAAM,eAAA,GAAkB,cAAA,CAAe,OAAA,EAAS,SAAS,CAAA;AACzD,EAAA,MAAM,KAAA,GAAQ,WAAA,IAAe,cAAA,CAAe,GAAA,CAAI,YAAY,CAAA;AAE5D,EAAA,IAAI,UAAU,MAAA,EAAW;AAEvB,IAAA,OAAO;AAAA,MACL,GAAI,YAAA,KAAiB,MAAA,GAAY,EAAC,GAAI,EAAE,QAAQ,YAAA,EAAa;AAAA,MAC7D,GAAI,eAAA,KAAoB,MAAA,GAAY,EAAC,GAAI,EAAE,WAAW,eAAA;AAAgB,KACxE;AAAA,EACF;AAEA,EAAA,MAAM,MAAA,GAAS,YAAA,IAAgB,cAAA,CAAe,GAAA,CAAI,cAAc,CAAA;AAChE,EAAA,MAAM,SAAA,GAAY,eAAA,IAAmB,cAAA,CAAe,GAAA,C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,YAAY,eAAA,CAAgB,OAAO,CAAC,CAAA;AAC/D,IAAA,OAAO,UAAA,CAAW,OAAA,EAAS,OAAA,EAAS,kBAAA,IAAsB,cAAc,CAAA;AAAA,EAC1E;AACF,CAAC","file":"vercel.js","sourcesContent":["/**\n * Vercel isolated sandbox provider — wraps `@vercel/sandbox` into a SandboxProvider.\n *\n * Usage:\n * import { vercel } from \"sandcastle/sandboxes/vercel\";\n * await run({ agent: claudeCode(\"claude-opus-4-8\"), sandbox: vercel() });\n */\n\nimport { execSync } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport { readFile, unlink, writeFile, mkdir, stat } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { Writable } from \"node:stream\";\nimport { createIsolatedSandboxProvider } from \"../SandboxProvider.js\";\nimport type {\n ExecResult,\n IsolatedSandboxHandle,\n IsolatedSandboxProvider,\n} from \"../SandboxProvider.js\";\nimport type { SandboxInstance } from \"@vercel/sandbox\";\nimport { BoundedTail, MAX_TAIL_CHARS } from \"../boundedTail.js\";\n\n/** Worktree path inside the Vercel sandbox. */\nconst VERCEL_REPO_PATH = \"/vercel/sandbox/workspace\";\n\n/**\n * Options for creating a Vercel sandbox provider.\n *\n * All `@vercel/sandbox` `Sandbox.create()` options are accepted as pass-through,\n * plus Sandcastle-specific options for auth and branch strategy.\n */\nexport interface VercelOptions {\n /**\n * Vercel access token.\n *\n * Falls back to the `VERCEL_TOKEN` environment variable. A token needs a\n * team and project id too (`teamId`/`VERCEL_TEAM_ID`,\n * `projectId`/`VERCEL_PROJECT_ID`). With no token at all, the SDK's OIDC\n * auth applies, which reads `VERCEL_OIDC_TOKEN`.\n */\n readonly token?: string;\n\n // ---- Pass-through @vercel/sandbox Sandbox.create() options ----\n\n /**\n * The source of the sandbox (git repo, tarball, or snapshot).\n * Omit to start an empty sandbox.\n */\n readonly source?:\n | {\n type: \"git\";\n url: string;\n depth?: number;\n revision?: string;\n username?: string;\n password?: string;\n }\n | {\n type: \"tarball\";\n url: string;\n }\n | {\n type: \"snapshot\";\n snapshotId: string;\n };\n\n /** Array of port numbers to expose from the sandbox (up to 4). */\n readonly ports?: number[];\n\n /** Timeout in milliseconds before the sandbox auto-terminates. */\n readonly timeout?: number;\n\n /**\n * Resources to allocate to the sandbox.\n * Each vCPU gets 2048 MB of memory.\n */\n readonly resources?: {\n vcpus: number;\n };\n\n /**\n * The runtime of the sandbox (e.g. `\"node24\"`, `\"node22\"`, `\"python3.13\"`).\n *\n * Omit it to get Vercel's default image (`vercel/sandbox/universal` as of\n * `@vercel/sandbox` 3.x), which ships coding agent CLIs such as `claude`.\n * The named runtimes ship none: install your agent's CLI in an\n * `onSandboxReady` hook.\n */\n readonly runtime?: string;\n\n /**\n * Network policy for the sandbox.\n * Defaults to full internet access if not specified.\n */\n readonly networkPolicy?: Record<string, unknown>;\n\n /**\n * Vercel project ID to associate sandbox operations with.\n * Falls back to the `VERCEL_PROJECT_ID` environment variable when a token is used.\n */\n readonly projectId?: string;\n\n /**\n * Vercel team ID to associate sandbox operations with.\n * Falls back to the `VERCEL_TEAM_ID` environment variable when a token is used.\n */\n readonly teamId?: string;\n\n /**\n * Timeout in milliseconds (alias for `timeout`, kept for discoverability).\n */\n readonly timeoutMs?: number;\n\n /**\n * Sandbox template shorthand (e.g. `\"node-22\"`).\n * Maps to the `runtime` option.\n */\n readonly template?: 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/**\n * Resolve the auth params for `Sandbox.create()`.\n *\n * `@vercel/sandbox` only accepts a token as an explicit param, together with\n * `teamId` and `projectId` (all three or none); otherwise it falls back to\n * OIDC. So read `VERCEL_TOKEN`, `VERCEL_TEAM_ID` and `VERCEL_PROJECT_ID`\n * here, explicit options first.\n */\nconst resolveVercelAuth = (\n options: VercelOptions | undefined,\n): { token?: string; teamId?: string; projectId?: string } => {\n const { env } = process;\n const tokenOption = setOrUndefined(options?.token);\n const teamIdOption = setOrUndefined(options?.teamId);\n const projectIdOption = setOrUndefined(options?.projectId);\n const token = tokenOption ?? setOrUndefined(env.VERCEL_TOKEN);\n\n if (token === undefined) {\n // No token: the SDK's OIDC flow, which may use team/project ids as hints.\n return {\n ...(teamIdOption === undefined ? {} : { teamId: teamIdOption }),\n ...(projectIdOption === undefined ? {} : { projectId: projectIdOption }),\n };\n }\n\n const teamId = teamIdOption ?? setOrUndefined(env.VERCEL_TEAM_ID);\n const projectId = projectIdOption ?? setOrUndefined(env.VERCEL_PROJECT_ID);\n const missing = [\n teamId === undefined ? \"VERCEL_TEAM_ID (or the teamId option)\" : null,\n projectId === undefined\n ? \"VERCEL_PROJECT_ID (or the projectId option)\"\n : null,\n ].filter((name): name is string => name !== null);\n\n if (missing.length > 0) {\n const source =\n tokenOption === undefined ? \"VERCEL_TOKEN\" : \"the token option\";\n throw new Error(\n `vercel(): ${source} is set, but a Vercel token also needs a team and project id. ` +\n `Missing: ${missing.join(\", \")}.`,\n );\n }\n\n return { token, teamId, projectId };\n};\n\n/**\n * Run the setup of a sandbox that `create()` has just made. If it fails, stop\n * the sandbox before rethrowing: no handle exists yet, so neither Sandcastle's\n * teardown nor `close()` can reach it, and it would run until Vercel's\n * timeout.\n */\nconst setUpOrStop = async (\n sandbox: { stop: () => Promise<unknown> },\n setUp: () => Promise<void>,\n): Promise<void> => {\n try {\n await setUp();\n } catch (error) {\n try {\n await sandbox.stop();\n } catch {\n // Report the setup error, which says why create() failed.\n }\n throw error;\n }\n};\n\n/** The `Sandbox.create` params: SDK pass-through options, env and auth. */\nconst toCreateParams = (\n options: VercelOptions | undefined,\n env: Record<string, string>,\n): Record<string, unknown> => {\n const o = options ?? {};\n const passThrough: Record<string, unknown> = {\n source: o.source,\n ports: o.ports,\n resources: o.resources,\n networkPolicy: o.networkPolicy,\n // runtime takes precedence over the template convenience alias\n runtime: o.runtime ?? o.template,\n // prefer explicit timeout, fall back to the timeoutMs alias\n timeout: o.timeout ?? o.timeoutMs,\n };\n return {\n // An unset option (or an empty runtime) is left out for the SDK default.\n ...Object.fromEntries(\n Object.entries(passThrough).filter(\n ([, value]) => value !== undefined && value !== \"\",\n ),\n ),\n env,\n ...resolveVercelAuth(options),\n };\n};\n\ntype RunCommandParams = Parameters<SandboxInstance[\"runCommand\"]>[0];\n\n/**\n * The command to run for `exec`. `runCommand` gives a command no stdin\n * unless it is detached: the command reads EOF. So write stdin to a file in\n * the sandbox and redirect it in (a file, not an argument, keeps clear of the\n * per-arg size limit). The redirect opens the file before the group runs, so\n * the group can delete it straight away and leave nothing behind.\n */\nconst withStdin = async (\n sandbox: SandboxInstance,\n command: string,\n stdin: string | undefined,\n): Promise<string> => {\n if (stdin === undefined) {\n return command;\n }\n const stdinPath = `/tmp/sandcastle-stdin-${randomUUID()}`;\n await sandbox.writeFiles([{ path: stdinPath, content: Buffer.from(stdin) }]);\n return `{ rm -f ${stdinPath}; ${command}\\n} < ${stdinPath}`;\n};\n\n/** A stream that hands each stdout line to `onLine` and keeps a bounded tail. */\nconst lineWritable = (\n onLine: (line: string) => void,\n tail: BoundedTail,\n): Writable => {\n let partial = \"\";\n return new Writable({\n write(chunk: Buffer, _encoding, callback) {\n const text = partial + chunk.toString();\n const lines = text.split(\"\\n\");\n partial = lines.pop() ?? \"\";\n for (const line of lines) {\n tail.push(line);\n onLine(line);\n }\n callback();\n },\n final(callback) {\n if (partial) {\n tail.push(partial);\n onLine(partial);\n partial = \"\";\n }\n callback();\n },\n });\n};\n\n/** A stream that only keeps a bounded tail of what is written to it. */\nconst tailWritable = (tail: BoundedTail): Writable =>\n new Writable({\n write(chunk: Buffer, _encoding, callback) {\n tail.push(chunk.toString());\n callback();\n },\n });\n\n/** Run a command, streaming stdout lines to `onLine`; returns bounded tails. */\nconst execStreamed = async (\n sandbox: SandboxInstance,\n params: RunCommandParams,\n {\n onLine,\n maxOutputTailChars,\n }: {\n readonly onLine: (line: string) => void;\n readonly maxOutputTailChars: number;\n },\n): Promise<ExecResult> => {\n const stdoutTail = new BoundedTail(maxOutputTailChars, \"\\n\");\n const stderrTail = new BoundedTail(maxOutputTailChars, \"\");\n const result = await sandbox.runCommand({\n ...params,\n stdout: lineWritable(onLine, stdoutTail),\n stderr: tailWritable(stderrTail),\n });\n return {\n stdout: stdoutTail.toString(),\n stderr: stderrTail.toString(),\n exitCode: result.exitCode,\n };\n};\n\n/** Run a command to completion and return its whole output. */\nconst execBuffered = async (\n sandbox: SandboxInstance,\n params: RunCommandParams,\n): Promise<ExecResult> => {\n const result = await sandbox.runCommand(params);\n const stdout = await result.stdout();\n const stderr = await result.stderr();\n return { stdout, stderr, exitCode: result.exitCode };\n};\n\n/** Copy a host directory in as a tarball, unpacked at `sandboxPath`. */\nconst copyDirIn = async (\n sandbox: SandboxInstance,\n hostPath: string,\n sandboxPath: string,\n): Promise<void> => {\n const tarPath = join(tmpdir(), `sandcastle-copyin-${Date.now()}.tar.gz`);\n execSync(`tar -czf \"${tarPath}\" -C \"${hostPath}\" .`);\n try {\n const tarContent = await readFile(tarPath);\n const sandboxTarPath = `/tmp/sandcastle-copyin-${Date.now()}.tar.gz`;\n await sandbox.writeFiles([{ path: sandboxTarPath, content: tarContent }]);\n await sandbox.runCommand({\n cmd: \"sh\",\n args: [\n \"-c\",\n `mkdir -p \"${sandboxPath}\" && tar -xzf \"${sandboxTarPath}\" -C \"${sandboxPath}\" && rm -f \"${sandboxTarPath}\"`,\n ],\n });\n } finally {\n await unlink(tarPath).catch(() => undefined);\n }\n};\n\n/**\n * Create the worktree folder with its parents: Vercel's default image has no\n * /vercel/sandbox (its user's home is /vercel), and `mkDir` isn't recursive.\n */\nconst makeWorktreeDir = async (sandbox: SandboxInstance): Promise<void> => {\n const mkdirResult = await sandbox.runCommand({\n cmd: \"mkdir\",\n args: [\"-p\", VERCEL_REPO_PATH],\n });\n if (mkdirResult.exitCode !== 0) {\n const stderr = await mkdirResult.stderr();\n throw new Error(\n `vercel(): could not create ${VERCEL_REPO_PATH}: ${stderr.trim()}`,\n );\n }\n};\n\n/** The Sandcastle handle over a Vercel sandbox whose worktree folder exists. */\nconst makeHandle = (\n sandbox: SandboxInstance,\n maxOutputTailChars: number,\n): IsolatedSandboxHandle => ({\n worktreePath: VERCEL_REPO_PATH,\n // `@vercel/sandbox` 2 renamed the sandbox's id from `sandboxId` to `name`.\n sandboxId: sandbox.name ?? sandbox.sandboxId,\n\n exec: async (command, opts): Promise<ExecResult> => {\n const params: RunCommandParams = {\n cmd: \"sh\",\n args: [\"-c\", await withStdin(sandbox, command, opts?.stdin)],\n cwd: opts?.cwd ?? VERCEL_REPO_PATH,\n ...(opts?.sudo === true ? { sudo: true } : {}),\n };\n return opts?.onLine\n ? execStreamed(sandbox, params, {\n onLine: opts.onLine,\n maxOutputTailChars,\n })\n : execBuffered(sandbox, params);\n },\n\n copyIn: async (hostPath, sandboxPath): Promise<void> => {\n const info = await stat(hostPath);\n if (info.isDirectory()) {\n await copyDirIn(sandbox, hostPath, sandboxPath);\n } else {\n const content = await readFile(hostPath);\n await sandbox.writeFiles([{ path: sandboxPath, content }]);\n }\n },\n\n copyFileOut: async (sandboxPath, hostPath): Promise<void> => {\n const buffer = await sandbox.readFileToBuffer({ path: sandboxPath });\n if (!buffer) {\n throw new Error(`File not found in Vercel sandbox: ${sandboxPath}`);\n }\n await mkdir(dirname(hostPath), { recursive: true });\n await writeFile(hostPath, buffer);\n },\n\n close: async (): Promise<void> => {\n await sandbox.stop();\n },\n});\n\n/**\n * Create a Vercel isolated sandbox provider.\n *\n * The returned provider creates Vercel Firecracker microVM sandboxes via\n * the `@vercel/sandbox` SDK. Each sandbox is ephemeral — one sandbox per run.\n *\n * Requires `@vercel/sandbox` to be installed as a peer dependency.\n */\nexport const vercel = (options?: VercelOptions): IsolatedSandboxProvider =>\n createIsolatedSandboxProvider({\n name: \"vercel\",\n env: options?.env,\n create: async (createOptions): Promise<IsolatedSandboxHandle> => {\n // Dynamic import so the peer dependency is only loaded at runtime\n const { Sandbox } = await import(\"@vercel/sandbox\");\n const sandbox = await Sandbox.create(\n toCreateParams(options, createOptions.env),\n );\n await setUpOrStop(sandbox, async () => makeWorktreeDir(sandbox));\n return makeHandle(sandbox, options?.maxOutputTailChars ?? MAX_TAIL_CHARS);\n },\n });\n"]}
1
+ {"version":3,"sources":["../../src/sandboxes/vercelAuth.ts","../../src/sandboxes/vercelExec.ts","../../src/sandboxes/vercel.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAaA,IAAM,cAAA,GAAiB,CAAC,KAAA,KACtB,KAAA,KAAU,KAAK,MAAA,GAAY,KAAA;AAUtB,IAAM,iBAAA,GAAoB,CAC/B,OAAA,KAC4D;AAC5D,EAAA,MAAM,EAAE,KAAI,GAAI,OAAA;AAChB,EAAA,MAAM,WAAA,GAAc,cAAA,CAAe,OAAA,EAAS,KAAK,CAAA;AACjD,EAAA,MAAM,YAAA,GAAe,cAAA,CAAe,OAAA,EAAS,MAAM,CAAA;AACnD,EAAA,MAAM,eAAA,GAAkB,cAAA,CAAe,OAAA,EAAS,SAAS,CAAA;AACzD,EAAA,MAAM,KAAA,GAAQ,WAAA,IAAe,cAAA,CAAe,GAAA,CAAI,YAAY,CAAA;AAE5D,EAAA,IAAI,UAAU,MAAA,EAAW;AAEvB,IAAA,OAAO;AAAA,MACL,GAAI,YAAA,KAAiB,MAAA,GAAY,EAAC,GAAI,EAAE,QAAQ,YAAA,EAAa;AAAA,MAC7D,GAAI,eAAA,KAAoB,MAAA,GAAY,EAAC,GAAI,EAAE,WAAW,eAAA;AAAgB,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AAA;AAAA,EAC1E;AACF,CAAC","file":"vercel.js","sourcesContent":["/**\n * Auth for the Vercel sandbox provider (`./vercel.ts`): the token, team and\n * project ids `Sandbox.create()` takes, from options or env vars.\n */\n\n/** The auth options of `VercelOptions`. */\nexport interface VercelAuthOptions {\n readonly token?: string;\n readonly teamId?: string;\n readonly projectId?: string;\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/**\n * Resolve the auth params for `Sandbox.create()`.\n *\n * `@vercel/sandbox` only accepts a token as an explicit param, together with\n * `teamId` and `projectId` (all three or none); otherwise it falls back to\n * OIDC. So read `VERCEL_TOKEN`, `VERCEL_TEAM_ID` and `VERCEL_PROJECT_ID`\n * here, explicit options first.\n */\nexport const resolveVercelAuth = (\n options: VercelAuthOptions | undefined,\n): { token?: string; teamId?: string; projectId?: string } => {\n const { env } = process;\n const tokenOption = setOrUndefined(options?.token);\n const teamIdOption = setOrUndefined(options?.teamId);\n const projectIdOption = setOrUndefined(options?.projectId);\n const token = tokenOption ?? setOrUndefined(env.VERCEL_TOKEN);\n\n if (token === undefined) {\n // No token: the SDK's OIDC flow, which may use team/project ids as hints.\n return {\n ...(teamIdOption === undefined ? {} : { teamId: teamIdOption }),\n ...(projectIdOption === undefined ? {} : { projectId: projectIdOption }),\n };\n }\n\n const teamId = teamIdOption ?? setOrUndefined(env.VERCEL_TEAM_ID);\n const projectId = projectIdOption ?? setOrUndefined(env.VERCEL_PROJECT_ID);\n const missing = [\n teamId === undefined ? \"VERCEL_TEAM_ID (or the teamId option)\" : null,\n projectId === undefined\n ? \"VERCEL_PROJECT_ID (or the projectId option)\"\n : null,\n ].filter((name): name is string => name !== null);\n\n if (missing.length > 0) {\n const source =\n tokenOption === undefined ? \"VERCEL_TOKEN\" : \"the token option\";\n throw new Error(\n `vercel(): ${source} is set, but a Vercel token also needs a team and project id. ` +\n `Missing: ${missing.join(\", \")}.`,\n );\n }\n\n return { token, teamId, projectId };\n};\n","/**\n * The `exec` of the Vercel sandbox provider (`./vercel.ts`): stdin through a\n * file, live line streaming with bounded tails, or buffered output.\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { Writable } from \"node:stream\";\nimport type { SandboxInstance } from \"@vercel/sandbox\";\nimport type { ExecResult } from \"../SandboxProvider.js\";\nimport { BoundedTail } from \"../boundedTail.js\";\n\nexport type RunCommandParams = Parameters<SandboxInstance[\"runCommand\"]>[0];\n\n/**\n * The command to run for `exec`. `runCommand` gives a command no stdin\n * unless it is detached: the command reads EOF. So write stdin to a file in\n * the sandbox and redirect it in (a file, not an argument, keeps clear of the\n * per-arg size limit). The redirect opens the file before the group runs, so\n * the group can delete it straight away and leave nothing behind.\n */\nexport const withStdin = async (\n sandbox: SandboxInstance,\n command: string,\n stdin: string | undefined,\n): Promise<string> => {\n if (stdin === undefined) {\n return command;\n }\n const stdinPath = `/tmp/sandcastle-stdin-${randomUUID()}`;\n await sandbox.writeFiles([{ path: stdinPath, content: Buffer.from(stdin) }]);\n return `{ rm -f ${stdinPath}; ${command}\\n} < ${stdinPath}`;\n};\n\n/**\n * A stream that hands each stdout line to `onLine` and keeps a bounded tail.\n * The SDK never ends it, so `final()` never runs: call `flush()` once the\n * command has finished to deliver a last line that has no trailing newline.\n * Flushing twice delivers it once.\n */\nconst lineWritable = (\n onLine: (line: string) => void,\n tail: BoundedTail,\n): { readonly stream: Writable; readonly flush: () => void } => {\n let partial = \"\";\n const flush = (): void => {\n if (partial) {\n tail.push(partial);\n onLine(partial);\n partial = \"\";\n }\n };\n const stream = new Writable({\n write(chunk: Buffer, _encoding, callback) {\n const text = partial + chunk.toString();\n const lines = text.split(\"\\n\");\n partial = lines.pop() ?? \"\";\n for (const line of lines) {\n tail.push(line);\n onLine(line);\n }\n callback();\n },\n final(callback) {\n flush();\n callback();\n },\n });\n return { stream, flush };\n};\n\n/** A stream that only keeps a bounded tail of what is written to it. */\nconst tailWritable = (tail: BoundedTail): Writable =>\n new Writable({\n write(chunk: Buffer, _encoding, callback) {\n tail.push(chunk.toString());\n callback();\n },\n });\n\n/** Run a command, streaming stdout lines to `onLine`; returns bounded tails. */\nexport const execStreamed = async (\n sandbox: SandboxInstance,\n params: RunCommandParams,\n {\n onLine,\n maxOutputTailChars,\n }: {\n readonly onLine: (line: string) => void;\n readonly maxOutputTailChars: number;\n },\n): Promise<ExecResult> => {\n const stdoutTail = new BoundedTail(maxOutputTailChars, \"\\n\");\n const stderrTail = new BoundedTail(maxOutputTailChars, \"\");\n const stdout = lineWritable(onLine, stdoutTail);\n const result = await sandbox.runCommand({\n ...params,\n stdout: stdout.stream,\n stderr: tailWritable(stderrTail),\n });\n stdout.flush();\n return {\n stdout: stdoutTail.toString(),\n stderr: stderrTail.toString(),\n exitCode: result.exitCode,\n };\n};\n\n/** Run a command to completion and return its whole output. */\nexport const execBuffered = async (\n sandbox: SandboxInstance,\n params: RunCommandParams,\n): Promise<ExecResult> => {\n const result = await sandbox.runCommand(params);\n const stdout = await result.stdout();\n const stderr = await result.stderr();\n return { stdout, stderr, exitCode: result.exitCode };\n};\n","/**\n * Vercel isolated sandbox provider — wraps `@vercel/sandbox` into a SandboxProvider.\n *\n * Usage:\n * import { vercel } from \"sandcastle/sandboxes/vercel\";\n * await run({ agent: claudeCode(\"claude-opus-4-8\"), sandbox: vercel() });\n */\n\nimport { spawn } from \"node:child_process\";\nimport { once } from \"node:events\";\nimport { readFile, unlink, writeFile, mkdir, stat } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { createIsolatedSandboxProvider } from \"../SandboxProvider.js\";\nimport type {\n ExecResult,\n IsolatedSandboxHandle,\n IsolatedSandboxProvider,\n} from \"../SandboxProvider.js\";\nimport type { SandboxInstance } from \"@vercel/sandbox\";\nimport { MAX_TAIL_CHARS } from \"../boundedTail.js\";\nimport { resolveVercelAuth } from \"./vercelAuth.js\";\nimport { execBuffered, execStreamed, withStdin } from \"./vercelExec.js\";\nimport type { RunCommandParams } from \"./vercelExec.js\";\n\n/** Worktree path inside the Vercel sandbox. */\nconst VERCEL_REPO_PATH = \"/vercel/sandbox/workspace\";\n\n/**\n * Options for creating a Vercel sandbox provider.\n *\n * All `@vercel/sandbox` `Sandbox.create()` options are accepted as pass-through,\n * plus Sandcastle-specific options for auth and branch strategy.\n */\nexport interface VercelOptions {\n /**\n * Vercel access token.\n *\n * Falls back to the `VERCEL_TOKEN` environment variable. A token needs a\n * team and project id too (`teamId`/`VERCEL_TEAM_ID`,\n * `projectId`/`VERCEL_PROJECT_ID`). With no token at all, the SDK's OIDC\n * auth applies, which reads `VERCEL_OIDC_TOKEN`.\n */\n readonly token?: string;\n\n // ---- Pass-through @vercel/sandbox Sandbox.create() options ----\n\n /**\n * The source of the sandbox (git repo, tarball, or snapshot).\n * Omit to start an empty sandbox.\n */\n readonly source?:\n | {\n type: \"git\";\n url: string;\n depth?: number;\n revision?: string;\n username?: string;\n password?: string;\n }\n | {\n type: \"tarball\";\n url: string;\n }\n | {\n type: \"snapshot\";\n snapshotId: string;\n };\n\n /** Array of port numbers to expose from the sandbox (up to 4). */\n readonly ports?: number[];\n\n /** Timeout in milliseconds before the sandbox auto-terminates. */\n readonly timeout?: number;\n\n /**\n * Resources to allocate to the sandbox.\n * Each vCPU gets 2048 MB of memory.\n */\n readonly resources?: {\n vcpus: number;\n };\n\n /**\n * The runtime of the sandbox (e.g. `\"node24\"`, `\"node22\"`, `\"python3.13\"`).\n *\n * Omit it to get Vercel's default image (`vercel/sandbox/universal` as of\n * `@vercel/sandbox` 3.x), which ships coding agent CLIs such as `claude`.\n * The named runtimes ship none: install your agent's CLI in an\n * `onSandboxReady` hook.\n */\n readonly runtime?: string;\n\n /**\n * Network policy for the sandbox.\n * Defaults to full internet access if not specified.\n */\n readonly networkPolicy?: Record<string, unknown>;\n\n /**\n * Vercel project ID to associate sandbox operations with.\n * Falls back to the `VERCEL_PROJECT_ID` environment variable when a token is used.\n */\n readonly projectId?: string;\n\n /**\n * Vercel team ID to associate sandbox operations with.\n * Falls back to the `VERCEL_TEAM_ID` environment variable when a token is used.\n */\n readonly teamId?: string;\n\n /**\n * Timeout in milliseconds (alias for `timeout`, kept for discoverability).\n */\n readonly timeoutMs?: number;\n\n /**\n * Sandbox template shorthand (e.g. `\"node-22\"`).\n * Maps to the `runtime` option.\n */\n readonly template?: string;\n\n /**\n * Whether Vercel keeps the sandbox's filesystem when it stops (default:\n * `false`).\n *\n * Vercel snapshots a persistent sandbox each time it stops, and the snapshot\n * counts against your snapshot storage. Sandcastle makes one sandbox per\n * run, so it turns this off unless you set it.\n */\n readonly persistent?: boolean;\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/**\n * Run the setup of a sandbox that `create()` has just made. If it fails, stop\n * the sandbox before rethrowing: no handle exists yet, so neither Sandcastle's\n * teardown nor `close()` can reach it, and it would run until Vercel's\n * timeout.\n */\nconst setUpOrStop = async (\n sandbox: { stop: () => Promise<unknown> },\n setUp: () => Promise<void>,\n): Promise<void> => {\n try {\n await setUp();\n } catch (error) {\n try {\n await sandbox.stop();\n } catch {\n // Report the setup error, which says why create() failed.\n }\n throw error;\n }\n};\n\n/** The `Sandbox.create` params: SDK pass-through options, env and auth. */\nconst toCreateParams = (\n options: VercelOptions | undefined,\n env: Record<string, string>,\n): Record<string, unknown> => {\n const o = options ?? {};\n const passThrough: Record<string, unknown> = {\n source: o.source,\n ports: o.ports,\n resources: o.resources,\n networkPolicy: o.networkPolicy,\n // runtime takes precedence over the template convenience alias\n runtime: o.runtime ?? o.template,\n // prefer explicit timeout, fall back to the timeoutMs alias\n timeout: o.timeout ?? o.timeoutMs,\n // Vercel defaults to persistent, which snapshots the sandbox on stop().\n persistent: o.persistent ?? false,\n };\n return {\n // An unset option (or an empty runtime) is left out for the SDK default.\n ...Object.fromEntries(\n Object.entries(passThrough).filter(\n ([, value]) => value !== undefined && value !== \"\",\n ),\n ),\n env,\n ...resolveVercelAuth(options),\n };\n};\n\n/** Pack `dir` into a gzipped tarball at `archive` on the host. */\nconst tarDirectory = async (archive: string, dir: string): Promise<void> => {\n const tar = spawn(\"tar\", [\"-czf\", archive, \"-C\", dir, \".\"], {\n stdio: [\"ignore\", \"ignore\", \"pipe\"],\n });\n let stderr = \"\";\n tar.stderr.on(\"data\", (chunk: Buffer) => {\n stderr += chunk.toString();\n });\n await once(tar, \"close\");\n if (tar.exitCode !== 0) {\n throw new Error(\n `tar exited with ${String(tar.exitCode)}: ${stderr.trim()}`,\n );\n }\n};\n\n/** Copy a host directory in as a tarball, unpacked at `sandboxPath`. */\nconst copyDirIn = async (\n sandbox: SandboxInstance,\n hostPath: string,\n sandboxPath: string,\n): Promise<void> => {\n const tarPath = join(tmpdir(), `sandcastle-copyin-${Date.now()}.tar.gz`);\n await tarDirectory(tarPath, hostPath);\n try {\n const tarContent = await readFile(tarPath);\n const sandboxTarPath = `/tmp/sandcastle-copyin-${Date.now()}.tar.gz`;\n await sandbox.writeFiles([{ path: sandboxTarPath, content: tarContent }]);\n await sandbox.runCommand({\n cmd: \"sh\",\n args: [\n \"-c\",\n `mkdir -p \"${sandboxPath}\" && tar -xzf \"${sandboxTarPath}\" -C \"${sandboxPath}\" && rm -f \"${sandboxTarPath}\"`,\n ],\n });\n } finally {\n await unlink(tarPath).catch(() => undefined);\n }\n};\n\n/**\n * Create the worktree folder with its parents: Vercel's default image has no\n * /vercel/sandbox (its user's home is /vercel), and `mkDir` isn't recursive.\n */\nconst makeWorktreeDir = async (sandbox: SandboxInstance): Promise<void> => {\n const mkdirResult = await sandbox.runCommand({\n cmd: \"mkdir\",\n args: [\"-p\", VERCEL_REPO_PATH],\n });\n if (mkdirResult.exitCode !== 0) {\n const stderr = await mkdirResult.stderr();\n throw new Error(\n `vercel(): could not create ${VERCEL_REPO_PATH}: ${stderr.trim()}`,\n );\n }\n};\n\n/** The Sandcastle handle over a Vercel sandbox whose worktree folder exists. */\nconst makeHandle = (\n sandbox: SandboxInstance,\n maxOutputTailChars: number,\n): IsolatedSandboxHandle => ({\n worktreePath: VERCEL_REPO_PATH,\n // `@vercel/sandbox` 2 renamed the sandbox's id from `sandboxId` to `name`.\n sandboxId: sandbox.name ?? sandbox.sandboxId,\n\n exec: async (command, opts): Promise<ExecResult> => {\n const params: RunCommandParams = {\n cmd: \"sh\",\n args: [\"-c\", await withStdin(sandbox, command, opts?.stdin)],\n cwd: opts?.cwd ?? VERCEL_REPO_PATH,\n ...(opts?.sudo === true ? { sudo: true } : {}),\n };\n return opts?.onLine\n ? execStreamed(sandbox, params, {\n onLine: opts.onLine,\n maxOutputTailChars,\n })\n : execBuffered(sandbox, params);\n },\n\n copyIn: async (hostPath, sandboxPath): Promise<void> => {\n const info = await stat(hostPath);\n if (info.isDirectory()) {\n await copyDirIn(sandbox, hostPath, sandboxPath);\n } else {\n const content = await readFile(hostPath);\n await sandbox.writeFiles([{ path: sandboxPath, content }]);\n }\n },\n\n copyFileOut: async (sandboxPath, hostPath): Promise<void> => {\n const buffer = await sandbox.readFileToBuffer({ path: sandboxPath });\n if (!buffer) {\n throw new Error(`File not found in Vercel sandbox: ${sandboxPath}`);\n }\n await mkdir(dirname(hostPath), { recursive: true });\n await writeFile(hostPath, buffer);\n },\n\n close: async (): Promise<void> => {\n await sandbox.stop();\n },\n});\n\n/**\n * Create a Vercel isolated sandbox provider.\n *\n * The returned provider creates Vercel Firecracker microVM sandboxes via\n * the `@vercel/sandbox` SDK. Each sandbox is ephemeral — one sandbox per run.\n *\n * Requires `@vercel/sandbox` to be installed as a peer dependency.\n */\nexport const vercel = (options?: VercelOptions): IsolatedSandboxProvider =>\n createIsolatedSandboxProvider({\n name: \"vercel\",\n env: options?.env,\n create: async (createOptions): Promise<IsolatedSandboxHandle> => {\n // Dynamic import so the peer dependency is only loaded at runtime\n const { Sandbox } = await import(\"@vercel/sandbox\");\n const sandbox = await Sandbox.create(\n toCreateParams(options, createOptions.env),\n );\n await setUpOrStop(sandbox, async () => makeWorktreeDir(sandbox));\n return makeHandle(sandbox, options?.maxOutputTailChars ?? MAX_TAIL_CHARS);\n },\n });\n"]}
@@ -6,7 +6,8 @@
6
6
  // with their target branch names.
7
7
  // Phase 2 (Execute): N sonnet agents run in parallel via Promise.allSettled,
8
8
  // each working a single issue on its own branch.
9
- // Phase 3 (Merge): A sonnet agent merges all branches that produced commits.
9
+ // Phase 3 (Merge): A sonnet agent merges every branch that is ahead of the
10
+ // current branch.
10
11
  //
11
12
  // The outer loop repeats up to MAX_ITERATIONS times so that newly unblocked
12
13
  // issues are picked up after each round of merges.
@@ -16,6 +17,8 @@
16
17
  // Or add to package.json:
17
18
  // "scripts": { "sandcastle": "npx tsx .sandcastle/main.mts" }
18
19
 
20
+ import { spawn } from "node:child_process";
21
+ import { once } from "node:events";
19
22
  import * as sandcastle from "@ai-hero/sandcastle";
20
23
  import { docker } from "@ai-hero/sandcastle/sandboxes/docker";
21
24
  import { z } from "zod";
@@ -30,6 +33,23 @@ const planSchema = z.object({
30
33
  ),
31
34
  });
32
35
 
36
+ // True when `branch` has commits the current branch doesn't. The merge phase
37
+ // asks git rather than trusting this cycle's `commits`: a branch an earlier
38
+ // cycle advanced but never merged gets no new commits when its issue comes
39
+ // round again, so gating on `commits.length` would strand it forever.
40
+ const isAheadOfHead = async (branch: string): Promise<boolean> => {
41
+ const git = spawn("git", ["rev-list", "--count", `HEAD..${branch}`], {
42
+ stdio: ["ignore", "pipe", "inherit"],
43
+ });
44
+ const closed = once(git, "close");
45
+ let count = "";
46
+ for await (const chunk of git.stdout) {
47
+ count += String(chunk);
48
+ }
49
+ await closed;
50
+ return git.exitCode === 0 && Number(count.trim()) > 0;
51
+ };
52
+
33
53
  // ---------------------------------------------------------------------------
34
54
  // Configuration
35
55
  // ---------------------------------------------------------------------------
@@ -38,15 +58,18 @@ const planSchema = z.object({
38
58
  // Raise this if your backlog is large; lower it for a quick smoke-test run.
39
59
  const MAX_ITERATIONS = 10;
40
60
 
41
- // Hooks run inside the sandbox before the agent starts each iteration.
42
- // npm install ensures the sandbox always has fresh dependencies.
43
- const hooks = {
61
+ // Install hooks only for worktree phases (execute). Planner and merger
62
+ // bind-mount the real checkout (no branchStrategy), so an `npm install`
63
+ // there would rewrite the host's node_modules — e.g. Linux native binaries
64
+ // on macOS, or packages removed from the host tree.
65
+ const installHooks = {
44
66
  sandbox: { onSandboxReady: [{ command: "npm install" }] },
45
67
  };
46
68
 
47
- // Copy node_modules from the host into the worktree before each sandbox
48
- // starts. Avoids a full npm install from scratch; the hook above handles
49
- // platform-specific binaries and any packages added since the last copy.
69
+ // Copy node_modules from the host into the worktree before each execute
70
+ // sandbox starts. Avoids a full npm install from scratch; the hook above
71
+ // handles platform-specific binaries and any packages added since the last
72
+ // copy. Safe only with a worktree — never pair this with a head bind-mount.
50
73
  const copyToWorktree = ["node_modules"];
51
74
 
52
75
  // ---------------------------------------------------------------------------
@@ -66,7 +89,6 @@ for (let iteration = 1; iteration <= MAX_ITERATIONS; iteration++) {
66
89
  // It outputs a <plan> JSON block — Output.object parses and validates it.
67
90
  // -------------------------------------------------------------------------
68
91
  const plan = await sandcastle.run({
69
- hooks,
70
92
  sandbox: docker(),
71
93
  name: "planner",
72
94
  // One iteration is enough: the planner just needs to read and reason,
@@ -108,7 +130,7 @@ for (let iteration = 1; iteration <= MAX_ITERATIONS; iteration++) {
108
130
  const settled = await Promise.allSettled(
109
131
  issues.map((issue) =>
110
132
  sandcastle.run({
111
- hooks,
133
+ hooks: installHooks,
112
134
  copyToWorktree,
113
135
  // Each agent starts on its own branch via branchStrategy on run().
114
136
  sandbox: docker(),
@@ -132,35 +154,36 @@ for (let iteration = 1; iteration <= MAX_ITERATIONS; iteration++) {
132
154
  );
133
155
 
134
156
  // Log any agents that threw (network error, sandbox crash, etc.), and
135
- // only pass branches that actually produced commits to the merge phase.
136
- // An agent that ran successfully but made no commits has nothing to merge.
137
- const completedIssues: typeof issues = [];
157
+ // only pass branches that are ahead of the current branch to the merge
158
+ // phase, whichever cycle made their commits (see isAheadOfHead).
159
+ const finishedIssues: typeof issues = [];
138
160
  for (const [i, issue] of issues.entries()) {
139
161
  const outcome = settled[i];
140
162
  if (outcome?.status === "rejected") {
141
163
  console.error(
142
164
  ` ✗ ${issue.id} (${issue.branch}) failed: ${outcome.reason}`,
143
165
  );
144
- } else if (
145
- outcome?.status === "fulfilled" &&
146
- outcome.value.commits.length > 0
147
- ) {
148
- completedIssues.push(issue);
166
+ } else if (outcome?.status === "fulfilled") {
167
+ finishedIssues.push(issue);
149
168
  }
150
169
  }
170
+ const ahead = await Promise.all(
171
+ finishedIssues.map(async (issue) => isAheadOfHead(issue.branch)),
172
+ );
173
+ const completedIssues = finishedIssues.filter((_, i) => ahead[i] === true);
151
174
 
152
175
  const completedBranches = completedIssues.map((i) => i.branch);
153
176
 
154
177
  console.log(
155
- `\nExecution complete. ${completedBranches.length} branch(es) with commits:`,
178
+ `\nExecution complete. ${completedBranches.length} branch(es) ahead of HEAD:`,
156
179
  );
157
180
  for (const branch of completedBranches) {
158
181
  console.log(` ${branch}`);
159
182
  }
160
183
 
161
184
  if (completedBranches.length === 0) {
162
- // All agents ran but none made commits — nothing to merge this cycle.
163
- console.log("No commits produced. Nothing to merge.");
185
+ // No branch has work the current branch lacks — nothing to merge.
186
+ console.log("No branches ahead of HEAD. Nothing to merge.");
164
187
  continue;
165
188
  }
166
189
 
@@ -174,7 +197,6 @@ for (let iteration = 1; iteration <= MAX_ITERATIONS; iteration++) {
174
197
  // uses to know which branches to merge and which issues to close.
175
198
  // -------------------------------------------------------------------------
176
199
  await sandcastle.run({
177
- hooks,
178
200
  sandbox: docker(),
179
201
  name: "merger",
180
202
  maxIterations: 1,